From 41cf7b26bf859ddbec39a4514b52be00a5ed458e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Fri, 15 Nov 2019 11:43:59 +0100 Subject: [PATCH 01/41] Polish FileDataStorageManager --- .../datamodel/FileDataStorageManager.kt | 1463 +++++++---------- .../android/ui/activity/ToolbarActivity.java | 4 +- .../ui/fragment/OCFileListFragment.java | 4 +- .../ui/preview/PreviewImageActivity.java | 2 +- 4 files changed, 601 insertions(+), 872 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt index 07b20363291..1ddf67149c5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt @@ -47,9 +47,11 @@ import com.owncloud.android.MainApp import com.owncloud.android.R import com.owncloud.android.authentication.AccountUtils import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.db.ProviderMeta.ProviderTableMeta +import com.owncloud.android.datamodel.OCFile.* +import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.* import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.datamodel.OCFile.AvailableOfflineStatus.* import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.shares.RemoteShare @@ -62,8 +64,8 @@ import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream +import java.lang.Long.parseLong import java.util.ArrayList -import java.util.Collections import java.util.HashSet import java.util.Vector @@ -93,13 +95,14 @@ class FileDataStorageManager { var cursorOnKeptInSync: Cursor? = null try { cursorOnKeptInSync = contentResolver!!.query( - ProviderTableMeta.CONTENT_URI, null, - ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ? OR " + - ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?", + CONTENT_URI, + null, + "$FILE_KEEP_IN_SYNC = ? OR $FILE_KEEP_IN_SYNC = ?", arrayOf( - OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE.value.toString(), - OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT.value.toString() - ), null + AVAILABLE_OFFLINE.value.toString(), + AVAILABLE_OFFLINE_PARENT.value.toString() + ), + null ) if (cursorOnKeptInSync != null && cursorOnKeptInSync.moveToFirst()) { @@ -108,7 +111,7 @@ class FileDataStorageManager { do { file = createFileInstance(cursorOnKeptInSync) accountName = cursorOnKeptInSync.getString( - cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER) + cursorOnKeptInSync.getColumnIndex(FILE_ACCOUNT_OWNER) ) if (!file!!.isFolder && AccountUtils.exists(accountName, mContext)) { result.add(Pair(file, accountName)) @@ -140,15 +143,15 @@ class FileDataStorageManager { var cursorOnKeptInSync: Cursor? = null try { cursorOnKeptInSync = contentResolver!!.query( - ProviderTableMeta.CONTENT_URI, null, - "(" + ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ? AND NOT " + - ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ? ) AND " + - ProviderTableMeta.FILE_ACCOUNT_OWNER + " = ? ", + CONTENT_URI, + null, + "($FILE_KEEP_IN_SYNC = ? AND NOT $FILE_KEEP_IN_SYNC = ? ) AND $FILE_ACCOUNT_OWNER = ? ", arrayOf( - OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE.value.toString(), - OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT.value.toString(), + AVAILABLE_OFFLINE.value.toString(), + AVAILABLE_OFFLINE_PARENT.value.toString(), account!!.name - ), null + ), + null ) if (cursorOnKeptInSync != null && cursorOnKeptInSync.moveToFirst()) { @@ -166,7 +169,7 @@ class FileDataStorageManager { cursorOnKeptInSync?.close() } - Collections.sort(result) + result.sort() return result } @@ -185,7 +188,7 @@ class FileDataStorageManager { } fun getFileByPath(path: String): OCFile? { - val c = getFileCursorForValue(ProviderTableMeta.FILE_PATH, path) + val c = getFileCursorForValue(FILE_PATH, path) var file: OCFile? = null if (c != null) { if (c.moveToFirst()) { @@ -193,20 +196,17 @@ class FileDataStorageManager { } c.close() } - return if (file == null && OCFile.ROOT_PATH == path) { + return if (file == null && ROOT_PATH == path) { createRootDir() // root should always exist } else file } fun getFileById(id: Long): OCFile? { - val c = getFileCursorForValue(ProviderTableMeta._ID, id.toString()) - var file: OCFile? = null - if (c != null) { - if (c.moveToFirst()) { - file = createFileInstance(c) - } - c.close() - } + val c = getFileCursorForValue(_ID, id.toString()) ?: return null + val file: OCFile? = if (c.moveToFirst()) { + createFileInstance(c) + } else null + c.close() return file } @@ -215,43 +215,33 @@ class FileDataStorageManager { * Its the fileId ownCloud Core uses to identify a file even if its name has changed. * * - * An Explenation about how to use ETags an those FileIds can be found here: + * An Explanation about how to use ETags an those FileIds can be found here: * [](https://github.com/owncloud/client/wiki/Etags-and-file-ids) * * @param remoteID * @return */ fun getFileByRemoteId(remoteID: String): OCFile? { - val c = getFileCursorForValue(ProviderTableMeta.FILE_REMOTE_ID, remoteID) - var file: OCFile? = null - if (c != null) { - if (c.moveToFirst()) { - file = createFileInstance(c) - } - c.close() - } + val c = getFileCursorForValue(FILE_REMOTE_ID, remoteID) ?: return null + val file: OCFile? = if (c.moveToFirst()) { + createFileInstance(c) + } else null + c.close() return file } fun getFileByLocalPath(path: String): OCFile? { - val c = getFileCursorForValue(ProviderTableMeta.FILE_STORAGE_PATH, path) - var file: OCFile? = null - if (c != null) { - if (c.moveToFirst()) { - file = createFileInstance(c) - } - c.close() - } + val c = getFileCursorForValue(FILE_STORAGE_PATH, path) ?: return null + val file: OCFile? = if (c.moveToFirst()) { + createFileInstance(c) + } else null + c.close() return file } - fun fileExists(id: Long): Boolean { - return fileExists(ProviderTableMeta._ID, id.toString()) - } + fun fileExists(id: Long): Boolean = fileExists(_ID, id.toString()) - fun fileExists(path: String): Boolean { - return fileExists(ProviderTableMeta.FILE_PATH, path) - } + fun fileExists(path: String): Boolean = fileExists(FILE_PATH, path) fun getFolderContent(f: OCFile?, onlyAvailableOffline: Boolean): Vector { return if (f != null && f.isFolder && f.fileId != -1L) { @@ -279,34 +269,30 @@ class FileDataStorageManager { fun saveFile(file: OCFile): Boolean { var overriden = false - val cv = ContentValues() - cv.put(ProviderTableMeta.FILE_MODIFIED, file.modificationTimestamp) - cv.put( - ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, - file.modificationTimestampAtLastSyncForData - ) - cv.put(ProviderTableMeta.FILE_CREATION, file.creationTimestamp) - cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.fileLength) - cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.mimetype) - cv.put(ProviderTableMeta.FILE_NAME, file.fileName) - cv.put(ProviderTableMeta.FILE_PARENT, file.parentId) - cv.put(ProviderTableMeta.FILE_PATH, file.remotePath) - if (!file.isFolder) { - cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.storagePath) + val cv = ContentValues().apply { + put(FILE_MODIFIED, file.modificationTimestamp) + put(FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.modificationTimestampAtLastSyncForData) + put(FILE_CREATION, file.creationTimestamp) + put(FILE_CONTENT_LENGTH, file.fileLength) + put(FILE_CONTENT_TYPE, file.mimetype) + put(FILE_NAME, file.fileName) + put(FILE_PARENT, file.parentId) + put(FILE_PATH, file.remotePath) + if (!file.isFolder) put(FILE_STORAGE_PATH, file.storagePath) + put(FILE_ACCOUNT_OWNER, account!!.name) + put(FILE_LAST_SYNC_DATE, file.lastSyncDateForProperties) + put(FILE_LAST_SYNC_DATE_FOR_DATA, file.lastSyncDateForData) + put(FILE_ETAG, file.etag) + put(FILE_TREE_ETAG, file.treeEtag) + put(FILE_SHARED_VIA_LINK, if (file.isSharedViaLink) 1 else 0) + put(FILE_SHARED_WITH_SHAREE, if (file.isSharedWithSharee) 1 else 0) + put(FILE_PERMISSIONS, file.permissions) + put(FILE_REMOTE_ID, file.remoteId) + put(FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail()) + put(FILE_IS_DOWNLOADING, file.isDownloading) + put(FILE_ETAG_IN_CONFLICT, file.etagInConflict) + put(FILE_PRIVATE_LINK, file.privateLink) } - cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, account!!.name) - cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.lastSyncDateForProperties) - cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.lastSyncDateForData) - cv.put(ProviderTableMeta.FILE_ETAG, file.etag) - cv.put(ProviderTableMeta.FILE_TREE_ETAG, file.treeEtag) - cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, if (file.isSharedViaLink) 1 else 0) - cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, if (file.isSharedWithSharee) 1 else 0) - cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.permissions) - cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.remoteId) - cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail()) - cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading) - cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.etagInConflict) - cv.put(ProviderTableMeta.FILE_PRIVATE_LINK, file.privateLink) val sameRemotePath = fileExists(file.remotePath) if (sameRemotePath || fileExists(file.fileId)) { // for renamed files; no more delete and create @@ -321,52 +307,31 @@ class FileDataStorageManager { overriden = true if (contentResolver != null) { - contentResolver!!.update( - ProviderTableMeta.CONTENT_URI, cv, - ProviderTableMeta._ID + "=?", - arrayOf(file.fileId.toString()) - ) + contentResolver!!.update(CONTENT_URI, cv, "$_ID=?", arrayOf(file.fileId.toString())) } else { try { - contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI, - cv, ProviderTableMeta._ID + "=?", - arrayOf(file.fileId.toString()) - ) + contentProviderClient!!.update(CONTENT_URI, cv, "$_ID=?", arrayOf(file.fileId.toString())) } catch (e: RemoteException) { - Log_OC.e( - TAG, - "Fail to insert insert file to database " + e.message - ) + Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}", e) } - } } else { // new file setInitialAvailableOfflineStatus(file, cv) - var result_uri: Uri? = null + var resultUri: Uri? = null if (contentResolver != null) { - result_uri = contentResolver!!.insert( - ProviderTableMeta.CONTENT_URI_FILE, cv - ) + resultUri = contentResolver!!.insert(CONTENT_URI_FILE, cv) } else { try { - result_uri = contentProviderClient!!.insert( - ProviderTableMeta.CONTENT_URI_FILE, cv - ) + resultUri = contentProviderClient!!.insert(CONTENT_URI_FILE, cv) } catch (e: RemoteException) { - Log_OC.e( - TAG, - "Fail to insert insert file to database " + e.message - ) + Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}", e) } - } - if (result_uri != null) { - val new_id = java.lang.Long.parseLong(result_uri.pathSegments[1]) - file.fileId = new_id + resultUri?.let { + file.fileId = it.pathSegments[1].toLong() } } @@ -387,76 +352,67 @@ class FileDataStorageManager { fun saveFolder( folder: OCFile, updatedFiles: Collection, filesToRemove: Collection ) { - Log_OC.d( - TAG, "Saving folder " + folder.remotePath + " with " + updatedFiles.size - + " children and " + filesToRemove.size + " files to remove" + TAG, "Saving folder ${folder.remotePath} with ${updatedFiles.size} children and " + + "${filesToRemove.size} files to remove" ) val operations = ArrayList(updatedFiles.size) // prepare operations to insert or update files to save in the given folder for (file in updatedFiles) { - val cv = ContentValues() - cv.put(ProviderTableMeta.FILE_MODIFIED, file.modificationTimestamp) - cv.put( - ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, - file.modificationTimestampAtLastSyncForData - ) - cv.put(ProviderTableMeta.FILE_CREATION, file.creationTimestamp) - cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.fileLength) - cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.mimetype) - cv.put(ProviderTableMeta.FILE_NAME, file.fileName) - cv.put(ProviderTableMeta.FILE_PARENT, folder.fileId) - cv.put(ProviderTableMeta.FILE_PATH, file.remotePath) - if (!file.isFolder) { - cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.storagePath) + val cv = ContentValues().apply { + put(FILE_MODIFIED, file.modificationTimestamp) + put(FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.modificationTimestampAtLastSyncForData) + put(FILE_CREATION, file.creationTimestamp) + put(FILE_CONTENT_LENGTH, file.fileLength) + put(FILE_CONTENT_TYPE, file.mimetype) + put(FILE_NAME, file.fileName) + put(FILE_PARENT, folder.fileId) + put(FILE_PATH, file.remotePath) + if (!file.isFolder) put(FILE_STORAGE_PATH, file.storagePath) + put(FILE_ACCOUNT_OWNER, account!!.name) + put(FILE_LAST_SYNC_DATE, file.lastSyncDateForProperties) + put(FILE_LAST_SYNC_DATE_FOR_DATA, file.lastSyncDateForData) + put(FILE_ETAG, file.etag) + put(FILE_TREE_ETAG, file.treeEtag) + put(FILE_SHARED_VIA_LINK, if (file.isSharedViaLink) 1 else 0) + put(FILE_SHARED_WITH_SHAREE, if (file.isSharedWithSharee) 1 else 0) + put(FILE_PERMISSIONS, file.permissions) + put(FILE_REMOTE_ID, file.remoteId) + put(FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail()) + put(FILE_IS_DOWNLOADING, file.isDownloading) + put(FILE_ETAG_IN_CONFLICT, file.etagInConflict) + put(FILE_PRIVATE_LINK, file.privateLink) } - cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, account!!.name) - cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.lastSyncDateForProperties) - cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.lastSyncDateForData) - cv.put(ProviderTableMeta.FILE_ETAG, file.etag) - cv.put(ProviderTableMeta.FILE_TREE_ETAG, file.treeEtag) - cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, if (file.isSharedViaLink) 1 else 0) - cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, if (file.isSharedWithSharee) 1 else 0) - cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.permissions) - cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.remoteId) - cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail()) - cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading) - cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.etagInConflict) - cv.put(ProviderTableMeta.FILE_PRIVATE_LINK, file.privateLink) val existsByPath = fileExists(file.remotePath) if (existsByPath || fileExists(file.fileId)) { // updating an existing file operations.add( - ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv).withSelection( - ProviderTableMeta._ID + "=?", + ContentProviderOperation.newUpdate(CONTENT_URI).withValues(cv).withSelection( + "$_ID=?", arrayOf(file.fileId.toString()) ) .build() ) - } else { // adding a new file setInitialAvailableOfflineStatus(file, cv) - operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build()) + operations.add(ContentProviderOperation.newInsert(CONTENT_URI).withValues(cv).build()) } } // prepare operations to remove files in the given folder - val where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + - ProviderTableMeta.FILE_PATH + "=?" - var whereArgs: Array? = null + val where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?" + var whereArgs: Array? for (file in filesToRemove) { if (file.parentId == folder.fileId) { whereArgs = arrayOf(account!!.name, file.remotePath) if (file.isFolder) { operations.add( ContentProviderOperation.newDelete( - ContentUris.withAppendedId( - ProviderTableMeta.CONTENT_URI_DIR, file.fileId - ) + ContentUris.withAppendedId(CONTENT_URI_DIR, file.fileId) ).withSelection(where, whereArgs).build() ) @@ -467,9 +423,7 @@ class FileDataStorageManager { } else { operations.add( ContentProviderOperation.newDelete( - ContentUris.withAppendedId( - ProviderTableMeta.CONTENT_URI_FILE, file.fileId - ) + ContentUris.withAppendedId(CONTENT_URI_FILE, file.fileId) ).withSelection(where, whereArgs).build() ) @@ -483,68 +437,65 @@ class FileDataStorageManager { } // update metadata of folder - val cv = ContentValues() - cv.put(ProviderTableMeta.FILE_MODIFIED, folder.modificationTimestamp) - cv.put( - ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, - folder.modificationTimestampAtLastSyncForData - ) - cv.put(ProviderTableMeta.FILE_CREATION, folder.creationTimestamp) - cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, folder.fileLength) - cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, folder.mimetype) - cv.put(ProviderTableMeta.FILE_NAME, folder.fileName) - cv.put(ProviderTableMeta.FILE_PARENT, folder.parentId) - cv.put(ProviderTableMeta.FILE_PATH, folder.remotePath) - cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, account!!.name) - cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, folder.lastSyncDateForProperties) - cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, folder.lastSyncDateForData) - cv.put(ProviderTableMeta.FILE_ETAG, folder.etag) - cv.put(ProviderTableMeta.FILE_TREE_ETAG, folder.treeEtag) - cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, if (folder.isSharedViaLink) 1 else 0) - cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, if (folder.isSharedWithSharee) 1 else 0) - cv.put(ProviderTableMeta.FILE_PERMISSIONS, folder.permissions) - cv.put(ProviderTableMeta.FILE_REMOTE_ID, folder.remoteId) - cv.put(ProviderTableMeta.FILE_PRIVATE_LINK, folder.privateLink) + val cv = ContentValues().apply { + put(FILE_MODIFIED, folder.modificationTimestamp) + put(FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, folder.modificationTimestampAtLastSyncForData) + put(FILE_CREATION, folder.creationTimestamp) + put(FILE_CONTENT_LENGTH, folder.fileLength) + put(FILE_CONTENT_TYPE, folder.mimetype) + put(FILE_NAME, folder.fileName) + put(FILE_PARENT, folder.parentId) + put(FILE_PATH, folder.remotePath) + put(FILE_ACCOUNT_OWNER, account!!.name) + put(FILE_LAST_SYNC_DATE, folder.lastSyncDateForProperties) + put(FILE_LAST_SYNC_DATE_FOR_DATA, folder.lastSyncDateForData) + put(FILE_ETAG, folder.etag) + put(FILE_TREE_ETAG, folder.treeEtag) + put(FILE_SHARED_VIA_LINK, if (folder.isSharedViaLink) 1 else 0) + put(FILE_SHARED_WITH_SHAREE, if (folder.isSharedWithSharee) 1 else 0) + put(FILE_PERMISSIONS, folder.permissions) + put(FILE_REMOTE_ID, folder.remoteId) + put(FILE_PRIVATE_LINK, folder.privateLink) + } operations.add( - ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv).withSelection( - ProviderTableMeta._ID + "=?", - arrayOf(folder.fileId.toString()) + ContentProviderOperation.newUpdate(CONTENT_URI).withValues(cv).withSelection( + "$_ID=?", arrayOf(folder.fileId.toString()) ) .build() ) // apply operations in batch var results: Array? = null - Log_OC.d(TAG, "Sending " + operations.size + " operations to FileContentProvider") + Log_OC.d(TAG, "Sending ${operations.size} operations to FileContentProvider") try { - if (contentResolver != null) { - results = contentResolver!!.applyBatch(MainApp.authority, operations) - - } else { - results = contentProviderClient!!.applyBatch(operations) - } + results = + if (contentResolver != null) { + contentResolver!!.applyBatch(MainApp.authority, operations) + } else { + contentProviderClient!!.applyBatch(operations) + } } catch (e: OperationApplicationException) { - Log_OC.e(TAG, "Exception in batch of operations " + e.message) + Log_OC.e(TAG, "Exception in batch of operations ${e.message}", e) } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception in batch of operations " + e.message) + Log_OC.e(TAG, "Exception in batch of operations ${e.message}", e) } // update new id in file objects for insertions if (results != null) { var newId: Long val filesIt = updatedFiles.iterator() - var file: OCFile? = null + var file: OCFile? for (i in results.indices) { - if (filesIt.hasNext()) { - file = filesIt.next() + file = if (filesIt.hasNext()) { + filesIt.next() } else { - file = null + null } if (results[i].uri != null) { - newId = java.lang.Long.parseLong(results[i].uri.pathSegments[1]) + newId = parseLong(results[i].uri.pathSegments[1]) //updatedFiles.get(i).setFileId(newId); if (file != null) { file.fileId = newId @@ -552,11 +503,10 @@ class FileDataStorageManager { } } } - } /** - * Adds the appropriate initial value for ProviderTableMeta.FILE_KEEP_IN_SYNC to + * Adds the appropriate initial value for FILE_KEEP_IN_SYNC to * passed [ContentValues] instance. * * @param file [OCFile] which av-offline property will be set. @@ -566,15 +516,9 @@ class FileDataStorageManager { // set appropriate av-off folder depending on ancestor val inFolderAvailableOffline = isAnyAncestorAvailableOfflineFolder(file) if (inFolderAvailableOffline) { - cv.put( - ProviderTableMeta.FILE_KEEP_IN_SYNC, - OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT.value - ) + cv.put(FILE_KEEP_IN_SYNC, AVAILABLE_OFFLINE_PARENT.value) } else { - cv.put( - ProviderTableMeta.FILE_KEEP_IN_SYNC, - OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE.value - ) + cv.put(FILE_KEEP_IN_SYNC, NOT_AVAILABLE_OFFLINE.value) } } @@ -596,39 +540,30 @@ class FileDataStorageManager { } val newStatus = file.availableOfflineStatus - require(OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT != newStatus) { "Forbidden value, AVAILABLE_OFFLINE_PARENT is calculated, cannot be set" } + require(AVAILABLE_OFFLINE_PARENT != newStatus) { + "Forbidden value, AVAILABLE_OFFLINE_PARENT is calculated, cannot be set" + } val cv = ContentValues() - cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.availableOfflineStatus.value) + cv.put(FILE_KEEP_IN_SYNC, file.availableOfflineStatus.value) var updatedCount: Int if (contentResolver != null) { - updatedCount = contentResolver!!.update( - ProviderTableMeta.CONTENT_URI, - cv, - ProviderTableMeta._ID + "=?", - arrayOf(file.fileId.toString()) - ) + updatedCount = contentResolver!!.update(CONTENT_URI, cv, "$_ID=?", arrayOf(file.fileId.toString())) // Update descendants if (file.isFolder && updatedCount > 0) { val descendantsCv = ContentValues() - if (newStatus == OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE) { + if (newStatus == AVAILABLE_OFFLINE) { // all descendant files MUST be av-off due to inheritance, not due to previous value - descendantsCv.put( - ProviderTableMeta.FILE_KEEP_IN_SYNC, - OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT.value - ) + descendantsCv.put(FILE_KEEP_IN_SYNC, AVAILABLE_OFFLINE_PARENT.value) } else { // all descendant files MUST be not-available offline - descendantsCv.put( - ProviderTableMeta.FILE_KEEP_IN_SYNC, - OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE.value - ) + descendantsCv.put(FILE_KEEP_IN_SYNC, NOT_AVAILABLE_OFFLINE.value) } val selectDescendants = selectionForAllDescendantsOf(file) updatedCount += contentResolver!!.update( - ProviderTableMeta.CONTENT_URI, + CONTENT_URI, descendantsCv, selectDescendants.first, selectDescendants.second @@ -637,23 +572,16 @@ class FileDataStorageManager { } else { try { - updatedCount = contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI, - cv, - ProviderTableMeta._ID + "=?", - arrayOf(file.fileId.toString()) - ) + updatedCount = + contentProviderClient!!.update(CONTENT_URI, cv, "$_ID=?", arrayOf(file.fileId.toString())) // If file is a folder, all children files that were available offline must be unset if (file.isFolder && updatedCount > 0) { val descendantsCv = ContentValues() - descendantsCv.put( - ProviderTableMeta.FILE_KEEP_IN_SYNC, - OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE.value - ) + descendantsCv.put(FILE_KEEP_IN_SYNC, NOT_AVAILABLE_OFFLINE.value) val selectDescendants = selectionForAllDescendantsOf(file) updatedCount += contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI, + CONTENT_URI, descendantsCv, selectDescendants.first, selectDescendants.second @@ -678,23 +606,19 @@ class FileDataStorageManager { } else { if (removeDBData) { - val file_uri = ContentUris.withAppendedId( - ProviderTableMeta.CONTENT_URI_FILE, - file.fileId - ) - val where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + - ProviderTableMeta.FILE_PATH + "=?" + val fileUri = ContentUris.withAppendedId(CONTENT_URI_FILE, file.fileId) + val where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?" val whereArgs = arrayOf(account!!.name, file.remotePath) var deleted = 0 if (contentProviderClient != null) { try { - deleted = contentProviderClient!!.delete(file_uri, where, whereArgs) + deleted = contentProviderClient!!.delete(fileUri, where, whereArgs) } catch (e: RemoteException) { e.printStackTrace() } } else { - deleted = contentResolver!!.delete(file_uri, where, whereArgs) + deleted = contentResolver!!.delete(fileUri, where, whereArgs) } success = success and (deleted > 0) } @@ -703,12 +627,12 @@ class FileDataStorageManager { success = File(localPath).delete() if (success) { deleteFileInMediaScan(localPath) - } - if (!removeDBData && success) { - // maybe unnecessary, but should be checked TODO remove if unnecessary - file.storagePath = null - saveFile(file) - saveConflict(file, null) + if (!removeDBData) { + // maybe unnecessary, but should be checked TODO remove if unnecessary + file.storagePath = null + saveFile(file) + saveConflict(file, null) + } } } } @@ -732,21 +656,20 @@ class FileDataStorageManager { } private fun removeFolderInDb(folder: OCFile): Boolean { - val folder_uri = - Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, "" + folder.fileId) // URI for recursive deletion - val where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + - ProviderTableMeta.FILE_PATH + "=?" + val folderUri = + Uri.withAppendedPath(CONTENT_URI_DIR, "" + folder.fileId) // URI for recursive deletion + val where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?" val whereArgs = arrayOf(account!!.name, folder.remotePath) var deleted = 0 if (contentProviderClient != null) { try { - deleted = contentProviderClient!!.delete(folder_uri, where, whereArgs) + deleted = contentProviderClient!!.delete(folderUri, where, whereArgs) } catch (e: RemoteException) { e.printStackTrace() } } else { - deleted = contentResolver!!.delete(folder_uri, where, whereArgs) + deleted = contentResolver!!.delete(folderUri, where, whereArgs) } return deleted > 0 } @@ -758,20 +681,18 @@ class FileDataStorageManager { if (localFolder.exists()) { // stage 1: remove the local files already registered in the files database val files = getFolderContent(folder.fileId, false) - if (files != null) { - for (file in files) { - if (file.isFolder) { - success = success and removeLocalFolder(file) - } else { - if (file.isDown) { - val localFile = File(file.storagePath) - success = success and localFile.delete() - if (success) { - // notify MediaScanner about removed file - deleteFileInMediaScan(file.storagePath) - file.storagePath = null - saveFile(file) - } + for (file in files) { + if (file.isFolder) { + success = success and removeLocalFolder(file) + } else { + if (file.isDown) { + val localFile = File(file.storagePath) + success = success and localFile.delete() + if (success) { + // notify MediaScanner about removed file + deleteFileInMediaScan(file.storagePath) + file.storagePath = null + saveFile(file) } } } @@ -789,11 +710,11 @@ class FileDataStorageManager { val localFiles = localFolder.listFiles() if (localFiles != null) { for (localFile in localFiles) { - if (localFile.isDirectory) { - success = success and removeLocalFolder(localFile) + success = if (localFile.isDirectory) { + success and removeLocalFolder(localFile) } else { val path = localFile.absolutePath - success = success and localFile.delete() + success and localFile.delete() } } } @@ -809,7 +730,7 @@ class FileDataStorageManager { */ fun moveLocalFile(file: OCFile?, targetPath: String, targetParentPath: String) { - if (file != null && file.fileExists() && OCFile.ROOT_PATH != file.fileName) { + if (file != null && file.fileExists() && ROOT_PATH != file.fileName) { val targetParent = getFileByPath(targetParentPath) ?: throw IllegalStateException( @@ -821,11 +742,11 @@ class FileDataStorageManager { if (contentProviderClient != null) { try { c = contentProviderClient!!.query( - ProviderTableMeta.CONTENT_URI, null, - ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + - ProviderTableMeta.FILE_PATH + " LIKE ? ", - arrayOf(account!!.name, file.remotePath + "%"), - ProviderTableMeta.FILE_PATH + " ASC " + CONTENT_URI, + null, + "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH LIKE ? ", + arrayOf(account!!.name, "${file.remotePath}%"), + "$FILE_PATH ASC " ) } catch (e: RemoteException) { Log_OC.e(TAG, e.message) @@ -833,11 +754,11 @@ class FileDataStorageManager { } else { c = contentResolver!!.query( - ProviderTableMeta.CONTENT_URI, null, - ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + - ProviderTableMeta.FILE_PATH + " LIKE ? ", + CONTENT_URI, + null, + "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH LIKE ? ", arrayOf(account!!.name, file.remotePath + "%"), - ProviderTableMeta.FILE_PATH + " ASC " + "$FILE_PATH ASC " ) } @@ -854,47 +775,34 @@ class FileDataStorageManager { do { val cv = ContentValues() // keep construction in the loop val child = createFileInstance(c) - cv.put( - ProviderTableMeta.FILE_PATH, - targetPath + child!!.remotePath.substring(lengthOfOldPath) - ) + cv.put(FILE_PATH, targetPath + child!!.remotePath.substring(lengthOfOldPath)) if (child.storagePath != null && child.storagePath.startsWith(defaultSavePath)) { // update link to downloaded content - but local move is not done here! val targetLocalPath = defaultSavePath + targetPath + child.storagePath.substring(lengthOfOldStoragePath) - cv.put(ProviderTableMeta.FILE_STORAGE_PATH, targetLocalPath) + cv.put(FILE_STORAGE_PATH, targetLocalPath) originalPathsToTriggerMediaScan.add(child.storagePath) newPathsToTriggerMediaScan.add(targetLocalPath) } - if (targetParent.availableOfflineStatus != OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE) { + if (targetParent.availableOfflineStatus != NOT_AVAILABLE_OFFLINE) { // moving to an available offline subfolder - cv.put( - ProviderTableMeta.FILE_KEEP_IN_SYNC, - OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT.value - ) - + cv.put(FILE_KEEP_IN_SYNC, AVAILABLE_OFFLINE_PARENT.value) } else { // moving to a not available offline subfolder - with care - if (file.availableOfflineStatus == OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT) { - cv.put( - ProviderTableMeta.FILE_KEEP_IN_SYNC, - OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE.value - ) + if (file.availableOfflineStatus == AVAILABLE_OFFLINE_PARENT) { + cv.put(FILE_KEEP_IN_SYNC, NOT_AVAILABLE_OFFLINE.value) } } if (child.remotePath == file.remotePath) { - cv.put( - ProviderTableMeta.FILE_PARENT, - targetParent.fileId - ) + cv.put(FILE_PARENT, targetParent.fileId) } operations.add( - ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv).withSelection( - ProviderTableMeta._ID + "=?", + ContentProviderOperation.newUpdate(CONTENT_URI).withValues(cv).withSelection( + "$_ID=?", arrayOf(child.fileId.toString()) ) .build() @@ -914,10 +822,7 @@ class FileDataStorageManager { } } catch (e: Exception) { - Log_OC.e( - TAG, "Fail to update " + file.fileId + " and descendants in database", - e - ) + Log_OC.e(TAG, "Fail to update ${file.fileId} and descendants in database", e) } } @@ -952,7 +857,7 @@ class FileDataStorageManager { } fun copyLocalFile(originalFile: OCFile?, targetPath: String, targetFileRemoteId: String) { - if (originalFile != null && originalFile.fileExists() && OCFile.ROOT_PATH != originalFile.fileName) { + if (originalFile != null && originalFile.fileExists() && ROOT_PATH != originalFile.fileName) { // 1. Copy in database val ocTargetFile = OCFile(targetPath) val parentId = getFileByPath(FileStorageUtils.getParentPath(targetPath))!!.fileId @@ -1023,38 +928,34 @@ class FileDataStorageManager { private fun getFolderContent(parentId: Long, onlyAvailableOffline: Boolean): Vector { val ret = Vector() - val req_uri = Uri.withAppendedPath( - ProviderTableMeta.CONTENT_URI_DIR, - parentId.toString() - ) - var c: Cursor? = null + val reqUri = Uri.withAppendedPath(CONTENT_URI_DIR, parentId.toString()) + var c: Cursor? val selection: String val selectionArgs: Array if (!onlyAvailableOffline) { - selection = ProviderTableMeta.FILE_PARENT + "=?" + selection = "$FILE_PARENT=?" selectionArgs = arrayOf(parentId.toString()) } else { - selection = ProviderTableMeta.FILE_PARENT + "=? AND (" + ProviderTableMeta.FILE_KEEP_IN_SYNC + - " = ? OR " + ProviderTableMeta.FILE_KEEP_IN_SYNC + "=? )" + selection = "$FILE_PARENT=? AND ($FILE_KEEP_IN_SYNC = ? OR $FILE_KEEP_IN_SYNC=? )" selectionArgs = arrayOf( parentId.toString(), - OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE.value.toString(), - OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT.value.toString() + AVAILABLE_OFFLINE.value.toString(), + AVAILABLE_OFFLINE_PARENT.value.toString() ) } - if (contentProviderClient != null) { + c = if (contentProviderClient != null) { try { - c = contentProviderClient!!.query(req_uri, null, selection, selectionArgs, null) + contentProviderClient!!.query(reqUri, null, selection, selectionArgs, null) } catch (e: RemoteException) { Log_OC.e(TAG, e.message) return ret } } else { - c = contentResolver!!.query(req_uri, null, selection, selectionArgs, null) + contentResolver!!.query(reqUri, null, selection, selectionArgs, null) } if (c != null) { @@ -1067,9 +968,7 @@ class FileDataStorageManager { c.close() } - Collections.sort(ret) - - return ret + return ret.apply { sort() } } /** @@ -1078,9 +977,7 @@ class FileDataStorageManager { * @param file [OCFile] which ancestors will be searched. * @return true/false */ - private fun isAnyAncestorAvailableOfflineFolder(file: OCFile): Boolean { - return getAvailableOfflineAncestorOf(file) != null - } + private fun isAnyAncestorAvailableOfflineFolder(file: OCFile) = getAvailableOfflineAncestorOf(file) != null /** * Returns ancestor folder with available offline status AVAILABLE_OFFLINE. @@ -1089,13 +986,13 @@ class FileDataStorageManager { * @return Ancestor folder with available offline status AVAILABLE_OFFLINE, or null if * does not exist. */ - fun getAvailableOfflineAncestorOf(file: OCFile): OCFile? { + private fun getAvailableOfflineAncestorOf(file: OCFile): OCFile? { var avOffAncestor: OCFile? = null val parent = getFileById(file.parentId) if (parent != null && parent.isFolder) { // file is null for the parent of the root folder - if (parent.availableOfflineStatus == OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE) { + if (parent.availableOfflineStatus == AVAILABLE_OFFLINE) { avOffAncestor = parent - } else if (parent.fileName != OCFile.ROOT_PATH) { + } else if (parent.fileName != ROOT_PATH) { avOffAncestor = getAvailableOfflineAncestorOf(parent) } } @@ -1103,9 +1000,9 @@ class FileDataStorageManager { } private fun createRootDir(): OCFile { - val file = OCFile(OCFile.ROOT_PATH) + val file = OCFile(ROOT_PATH) file.mimetype = "DIR" - file.parentId = FileDataStorageManager.ROOT_PARENT_ID.toLong() + file.parentId = ROOT_PARENT_ID.toLong() saveFile(file) return file } @@ -1115,25 +1012,23 @@ class FileDataStorageManager { if (contentResolver != null) { c = contentResolver!! .query( - ProviderTableMeta.CONTENT_URI, null, - cmp_key + "=? AND " - + ProviderTableMeta.FILE_ACCOUNT_OWNER - + "=?", - arrayOf(value, account!!.name), null + CONTENT_URI, + null, + "$cmp_key=? AND $FILE_ACCOUNT_OWNER=?", + arrayOf(value, account!!.name), + null ) } else { try { c = contentProviderClient!!.query( - ProviderTableMeta.CONTENT_URI, null, - cmp_key + "=? AND " - + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", - arrayOf(value, account!!.name), null + CONTENT_URI, + null, + "$cmp_key=? AND $FILE_ACCOUNT_OWNER=?", + arrayOf(value, account!!.name), + null ) } catch (e: RemoteException) { - Log_OC.e( - TAG, - "Couldn't determine file existance, assuming non existance: " + e.message - ) + Log_OC.e(TAG, "Couldn't determine file existence, assuming non existence: ${e.message}", e) return false } @@ -1151,180 +1046,121 @@ class FileDataStorageManager { if (contentResolver != null) { c = contentResolver!! .query( - ProviderTableMeta.CONTENT_URI, null, - key + "=? AND " - + ProviderTableMeta.FILE_ACCOUNT_OWNER - + "=?", - arrayOf(value, account!!.name), null + CONTENT_URI, + null, + "$key=? AND $FILE_ACCOUNT_OWNER=?", + arrayOf(value, account!!.name), + null ) } else { - try { - c = contentProviderClient!!.query( - ProviderTableMeta.CONTENT_URI, null, - key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER - + "=?", arrayOf(value, account!!.name), null + c = try { + contentProviderClient!!.query( + CONTENT_URI, + null, + "$key=? AND $FILE_ACCOUNT_OWNER=?", + arrayOf(value, account!!.name), + null ) } catch (e: RemoteException) { - Log_OC.e(TAG, "Could not get file details: " + e.message) - c = null + Log_OC.e(TAG, "Could not get file details: ${e.message}", e) + null } - } return c } - private fun createFileInstance(c: Cursor?): OCFile? { - var file: OCFile? = null - if (c != null) { - file = OCFile( - c.getString( - c - .getColumnIndex(ProviderTableMeta.FILE_PATH) - ) - ) - file.fileId = c.getLong(c.getColumnIndex(ProviderTableMeta._ID)) - file.parentId = c.getLong( - c - .getColumnIndex(ProviderTableMeta.FILE_PARENT) - ) - file.mimetype = c.getString( - c - .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE) - ) - if (!file.isFolder) { - file.storagePath = c.getString( - c - .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH) - ) - if (file.storagePath == null) { + private fun createFileInstance(c: Cursor?): OCFile? = c?.let { + OCFile(it.getString(it.getColumnIndex(FILE_PATH))).apply { + fileId = it.getLong(it.getColumnIndex(_ID)) + parentId = it.getLong(it.getColumnIndex(FILE_PARENT)) + mimetype = it.getString(it.getColumnIndex(FILE_CONTENT_TYPE)) + if (!isFolder) { + storagePath = it.getString(it.getColumnIndex(FILE_STORAGE_PATH)) + if (storagePath == null) { // try to find existing file and bind it with current account; // with the current update of SynchronizeFolderOperation, this won't be // necessary anymore after a full synchronization of the account - val f = File(FileStorageUtils.getDefaultSavePathFor(account!!.name, file)) + val f = File(FileStorageUtils.getDefaultSavePathFor(account!!.name, this)) if (f.exists()) { - file.storagePath = f.absolutePath - file.lastSyncDateForData = f.lastModified() + storagePath = f.absolutePath + lastSyncDateForData = f.lastModified() } } } - file.fileLength = c.getLong( - c - .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH) - ) - file.creationTimestamp = c.getLong( - c - .getColumnIndex(ProviderTableMeta.FILE_CREATION) - ) - file.modificationTimestamp = c.getLong( - c - .getColumnIndex(ProviderTableMeta.FILE_MODIFIED) - ) - file.modificationTimestampAtLastSyncForData = c.getLong( - c - .getColumnIndex(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA) - ) - file.lastSyncDateForProperties = c.getLong( - c - .getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE) - ) - file.lastSyncDateForData = c.getLong(c.getColumnIndex(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA)) - file.availableOfflineStatus = OCFile.AvailableOfflineStatus.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.FILE_KEEP_IN_SYNC)) - ) - file.etag = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ETAG)) - file.treeEtag = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_TREE_ETAG)) - file.isSharedViaLink = c.getInt( - c.getColumnIndex(ProviderTableMeta.FILE_SHARED_VIA_LINK) - ) == 1 - file.isSharedWithSharee = c.getInt( - c.getColumnIndex(ProviderTableMeta.FILE_SHARED_WITH_SHAREE) - ) == 1 - file.permissions = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PERMISSIONS)) - file.remoteId = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID)) - file.setNeedsUpdateThumbnail( - c.getInt( - c.getColumnIndex(ProviderTableMeta.FILE_UPDATE_THUMBNAIL) - ) == 1 - ) - file.isDownloading = c.getInt( - c.getColumnIndex(ProviderTableMeta.FILE_IS_DOWNLOADING) - ) == 1 - file.etagInConflict = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_ETAG_IN_CONFLICT)) - file.privateLink = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PRIVATE_LINK)) - + fileLength = it.getLong(it.getColumnIndex(FILE_CONTENT_LENGTH)) + creationTimestamp = it.getLong(it.getColumnIndex(FILE_CREATION)) + modificationTimestamp = it.getLong(it.getColumnIndex(FILE_MODIFIED)) + modificationTimestampAtLastSyncForData = it.getLong(it.getColumnIndex(FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA)) + lastSyncDateForProperties = it.getLong(it.getColumnIndex(FILE_LAST_SYNC_DATE)) + lastSyncDateForData = it.getLong(it.getColumnIndex(FILE_LAST_SYNC_DATE_FOR_DATA)) + availableOfflineStatus = fromValue(it.getInt(it.getColumnIndex(FILE_KEEP_IN_SYNC))) + etag = it.getString(it.getColumnIndex(FILE_ETAG)) + treeEtag = it.getString(it.getColumnIndex(FILE_TREE_ETAG)) + isSharedViaLink = it.getInt(it.getColumnIndex(FILE_SHARED_VIA_LINK)) == 1 + isSharedWithSharee = it.getInt(it.getColumnIndex(FILE_SHARED_WITH_SHAREE)) == 1 + permissions = it.getString(it.getColumnIndex(FILE_PERMISSIONS)) + remoteId = it.getString(it.getColumnIndex(FILE_REMOTE_ID)) + setNeedsUpdateThumbnail(it.getInt(it.getColumnIndex(FILE_UPDATE_THUMBNAIL)) == 1) + isDownloading = it.getInt(it.getColumnIndex(FILE_IS_DOWNLOADING)) == 1 + etagInConflict = it.getString(it.getColumnIndex(FILE_ETAG_IN_CONFLICT)) + privateLink = it.getString(it.getColumnIndex(FILE_PRIVATE_LINK)) } - return file } // Methods for Shares fun saveShare(remoteShare: RemoteShare): Boolean { var overriden = false - val cv = ContentValues() - cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, remoteShare.fileSource) - cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, remoteShare.itemSource) - cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, remoteShare.shareType!!.value) - cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, remoteShare.shareWith) - cv.put(ProviderTableMeta.OCSHARES_PATH, remoteShare.path) - cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, remoteShare.permissions) - cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, remoteShare.sharedDate) - cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, remoteShare.expirationDate) - cv.put(ProviderTableMeta.OCSHARES_TOKEN, remoteShare.token) - cv.put( - ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME, - remoteShare.sharedWithDisplayName - ) - cv.put( - ProviderTableMeta.OCSHARES_SHARE_WITH_ADDITIONAL_INFO, - remoteShare.sharedWithAdditionalInfo - ) - cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, if (remoteShare.isFolder) 1 else 0) - cv.put(ProviderTableMeta.OCSHARES_USER_ID, remoteShare.userId) - cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, remoteShare.id) - cv.put(ProviderTableMeta.OCSHARES_NAME, remoteShare.name) - cv.put(ProviderTableMeta.OCSHARES_URL, remoteShare.shareLink) - cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, account!!.name) + val cv = ContentValues().apply { + put(OCSHARES_FILE_SOURCE, remoteShare.fileSource) + put(OCSHARES_ITEM_SOURCE, remoteShare.itemSource) + put(OCSHARES_SHARE_TYPE, remoteShare.shareType!!.value) + put(OCSHARES_SHARE_WITH, remoteShare.shareWith) + put(OCSHARES_PATH, remoteShare.path) + put(OCSHARES_PERMISSIONS, remoteShare.permissions) + put(OCSHARES_SHARED_DATE, remoteShare.sharedDate) + put(OCSHARES_EXPIRATION_DATE, remoteShare.expirationDate) + put(OCSHARES_TOKEN, remoteShare.token) + put(OCSHARES_SHARE_WITH_DISPLAY_NAME, remoteShare.sharedWithDisplayName) + put(OCSHARES_SHARE_WITH_ADDITIONAL_INFO, remoteShare.sharedWithAdditionalInfo) + put(OCSHARES_IS_DIRECTORY, if (remoteShare.isFolder) 1 else 0) + put(OCSHARES_USER_ID, remoteShare.userId) + put(OCSHARES_ID_REMOTE_SHARED, remoteShare.id) + put(OCSHARES_NAME, remoteShare.name) + put(OCSHARES_URL, remoteShare.shareLink) + put(OCSHARES_ACCOUNT_OWNER, account!!.name) + } if (shareExistsForRemoteId(remoteShare.id)) {// for renamed files; no more delete and create overriden = true if (contentResolver != null) { contentResolver!!.update( - ProviderTableMeta.CONTENT_URI_SHARE, cv, - ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?", + CONTENT_URI_SHARE, + cv, + "$OCSHARES_ID_REMOTE_SHARED=?", arrayOf(remoteShare.id.toString()) ) } else { try { contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI_SHARE, - cv, ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?", + CONTENT_URI_SHARE, + cv, + "$OCSHARES_ID_REMOTE_SHARED=?", arrayOf(remoteShare.id.toString()) ) } catch (e: RemoteException) { - Log_OC.e( - TAG, - "Fail to insert insert file to database " + e.message - ) + Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}", e) } - } } else { - var result_uri: Uri? = null + var resultUri: Uri? = null if (contentResolver != null) { - result_uri = contentResolver!!.insert( - ProviderTableMeta.CONTENT_URI_SHARE, cv - ) + resultUri = contentResolver!!.insert(CONTENT_URI_SHARE, cv) } else { try { - result_uri = contentProviderClient!!.insert( - ProviderTableMeta.CONTENT_URI_SHARE, cv - ) + resultUri = contentProviderClient!!.insert(CONTENT_URI_SHARE, cv) } catch (e: RemoteException) { - Log_OC.e( - TAG, - "Fail to insert insert file to database " + e.message - ) + Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}", e) } - } } @@ -1339,10 +1175,7 @@ class FileDataStorageManager { */ fun getShareById(id: Long): OCShareEntity? { var share: OCShareEntity? = null - val c = getShareCursorForValue( - ProviderTableMeta._ID, - id.toString() - ) + val c = getShareCursorForValue(_ID, id.toString()) if (c != null) { if (c.moveToFirst()) { share = createShareInstance(c) @@ -1360,10 +1193,7 @@ class FileDataStorageManager { */ fun getShareByRemoteId(id: Long): OCShareEntity? { var share: OCShareEntity? = null - val c = getShareCursorForValue( - ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, - id.toString() - ) + val c = getShareCursorForValue(OCSHARES_ID_REMOTE_SHARED, id.toString()) if (c != null) { if (c.moveToFirst()) { share = createShareInstance(c) @@ -1381,7 +1211,7 @@ class FileDataStorageManager { * @return 'True' if a matching [RemoteShare] is stored in the current account. */ private fun shareExistsForRemoteId(remoteId: Long): Boolean { - return shareExistsForValue(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, remoteId.toString()) + return shareExistsForValue(OCSHARES_ID_REMOTE_SHARED, remoteId.toString()) } /** @@ -1411,169 +1241,139 @@ class FileDataStorageManager { * @return 'True' if a matching [RemoteShare] is stored in the current account. */ private fun getShareCursorForValue(key: String, value: String): Cursor? { - var c: Cursor? - if (contentResolver != null) { - c = contentResolver!! - .query( - ProviderTableMeta.CONTENT_URI_SHARE, null, - key + "=? AND " - + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?", - arrayOf(value, account!!.name), null - ) + return if (contentResolver != null) { + contentResolver!!.query( + CONTENT_URI_SHARE, + null, + "$key=? AND $OCSHARES_ACCOUNT_OWNER=?", + arrayOf(value, account!!.name), + null + ) } else { try { - c = contentProviderClient!!.query( - ProviderTableMeta.CONTENT_URI_SHARE, null, - key + "=? AND " - + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?", - arrayOf(value, account!!.name), null + contentProviderClient!!.query( + CONTENT_URI_SHARE, + null, + "$key=? AND $OCSHARES_ACCOUNT_OWNER=?", + arrayOf(value, account!!.name), + null ) } catch (e: RemoteException) { - Log_OC.w( - TAG, - "Could not get details, assuming share does not exist: " + e.message - ) - c = null + Log_OC.w(TAG, "Could not get details, assuming share does not exist: ${e.message}") + null } - } - return c } - private fun createShareInstance(c: Cursor?): OCShareEntity? { - var share: OCShareEntity? = null - if (c != null) { - share = OCShareEntity( - c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_FILE_SOURCE)), - c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ITEM_SOURCE)), - c.getInt(c.getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_TYPE)), - c.getString(c.getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH)), - c.getString(c.getColumnIndex(ProviderTableMeta.OCSHARES_PATH)), - c.getInt(c.getColumnIndex(ProviderTableMeta.OCSHARES_PERMISSIONS)), - c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_SHARED_DATE)), - c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_EXPIRATION_DATE)), - c.getString(c.getColumnIndex(ProviderTableMeta.OCSHARES_TOKEN)), - c.getString(c.getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME)), - c.getString(c.getColumnIndex(ProviderTableMeta.OCSHARES_SHARE_WITH_ADDITIONAL_INFO)), - c.getInt(c.getColumnIndex(ProviderTableMeta.OCSHARES_IS_DIRECTORY)) == 1, - c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_USER_ID)), - c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED)), - c.getString(c.getColumnIndex(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER)), - c.getString(c.getColumnIndex(ProviderTableMeta.OCSHARES_NAME)), - c.getString(c.getColumnIndex(ProviderTableMeta.OCSHARES_URL)) - ) - } - return share + private fun createShareInstance(c: Cursor?) = c?.let { + OCShareEntity( + it.getLong(it.getColumnIndex(OCSHARES_FILE_SOURCE)), + it.getLong(it.getColumnIndex(OCSHARES_ITEM_SOURCE)), + it.getInt(it.getColumnIndex(OCSHARES_SHARE_TYPE)), + it.getString(it.getColumnIndex(OCSHARES_SHARE_WITH)), + it.getString(it.getColumnIndex(OCSHARES_PATH)), + it.getInt(it.getColumnIndex(OCSHARES_PERMISSIONS)), + it.getLong(it.getColumnIndex(OCSHARES_SHARED_DATE)), + it.getLong(it.getColumnIndex(OCSHARES_EXPIRATION_DATE)), + it.getString(it.getColumnIndex(OCSHARES_TOKEN)), + it.getString(it.getColumnIndex(OCSHARES_SHARE_WITH_DISPLAY_NAME)), + it.getString(it.getColumnIndex(OCSHARES_SHARE_WITH_ADDITIONAL_INFO)), + it.getInt(it.getColumnIndex(OCSHARES_IS_DIRECTORY)) == 1, + it.getLong(it.getColumnIndex(OCSHARES_USER_ID)), + it.getLong(it.getColumnIndex(OCSHARES_ID_REMOTE_SHARED)), + it.getString(it.getColumnIndex(OCSHARES_ACCOUNT_OWNER)), + it.getString(it.getColumnIndex(OCSHARES_NAME)), + it.getString(it.getColumnIndex(OCSHARES_URL)) + ) } private fun resetShareFlagsInAllFiles() { val cv = ContentValues() - cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false) - cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false) - cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "") - val where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + cv.put(FILE_SHARED_VIA_LINK, false) + cv.put(FILE_SHARED_WITH_SHAREE, false) + cv.put(FILE_PUBLIC_LINK, "") + val where = "$FILE_ACCOUNT_OWNER=?" val whereArgs = arrayOf(account!!.name) if (contentResolver != null) { - contentResolver!!.update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs) + contentResolver!!.update(CONTENT_URI, cv, where, whereArgs) } else { try { - contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI, cv, where, - whereArgs - ) + contentProviderClient!!.update(CONTENT_URI, cv, where, whereArgs) } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception in resetShareFlagsInAllFiles" + e.message) + Log_OC.e(TAG, "Exception in resetShareFlagsInAllFiles ${e.message}", e) } - } } private fun resetShareFlagsInFolder(folder: OCFile) { val cv = ContentValues() - cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false) - cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false) - cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "") - val where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + - ProviderTableMeta.FILE_PARENT + "=?" + cv.put(FILE_SHARED_VIA_LINK, false) + cv.put(FILE_SHARED_WITH_SHAREE, false) + cv.put(FILE_PUBLIC_LINK, "") + val where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PARENT=?" val whereArgs = arrayOf(account!!.name, folder.fileId.toString()) if (contentResolver != null) { - contentResolver!!.update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs) + contentResolver!!.update(CONTENT_URI, cv, where, whereArgs) } else { try { - contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI, cv, where, - whereArgs - ) + contentProviderClient!!.update(CONTENT_URI, cv, where, whereArgs) } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception in resetShareFlagsInFolder " + e.message) + Log_OC.e(TAG, "Exception in resetShareFlagsInFolder ${e.message}", e) } - } } private fun resetShareFlagInAFile(filePath: String) { val cv = ContentValues() - cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, false) - cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, false) - cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "") - val where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + - ProviderTableMeta.FILE_PATH + "=?" + cv.put(FILE_SHARED_VIA_LINK, false) + cv.put(FILE_SHARED_WITH_SHAREE, false) + cv.put(FILE_PUBLIC_LINK, "") + val where = FILE_ACCOUNT_OWNER + "=? AND " + FILE_PATH + "=?" val whereArgs = arrayOf(account!!.name, filePath) if (contentResolver != null) { - contentResolver!!.update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs) - + contentResolver!!.update(CONTENT_URI, cv, where, whereArgs) } else { try { - contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI, cv, where, - whereArgs - ) + contentProviderClient!!.update(CONTENT_URI, cv, where, whereArgs) } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception in resetShareFlagsInFolder " + e.message) + Log_OC.e(TAG, "Exception in resetShareFlagsInFolder ${e.message}", e) } - } } private fun cleanShares() { - val where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + val where = "$OCSHARES_ACCOUNT_OWNER=?" val whereArgs = arrayOf(account!!.name) if (contentResolver != null) { - contentResolver!!.delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs) + contentResolver!!.delete(CONTENT_URI_SHARE, where, whereArgs) } else { try { - contentProviderClient!!.delete( - ProviderTableMeta.CONTENT_URI_SHARE, where, - whereArgs - ) + contentProviderClient!!.delete(CONTENT_URI_SHARE, where, whereArgs) } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception in cleanShares" + e.message) + Log_OC.e(TAG, "Exception in cleanShares ${e.message}", e) } - } } fun removeShare(share: OCShareEntity) { - val share_uri = ProviderTableMeta.CONTENT_URI_SHARE - val where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " + - ProviderTableMeta._ID + "=?" - val whereArgs = arrayOf(account!!.name, java.lang.Long.toString(share.id.toLong())) + val shareUri = CONTENT_URI_SHARE + val where = "$OCSHARES_ACCOUNT_OWNER=? AND $_ID=?" + val whereArgs = arrayOf(account!!.name, share.id.toString()) if (contentProviderClient != null) { try { - contentProviderClient!!.delete(share_uri, where, whereArgs) + contentProviderClient!!.delete(shareUri, where, whereArgs) } catch (e: RemoteException) { e.printStackTrace() } - } else { - contentResolver!!.delete(share_uri, where, whereArgs) + contentResolver!!.delete(shareUri, where, whereArgs) } } @@ -1585,41 +1385,35 @@ class FileDataStorageManager { * @return */ private fun prepareInsertShares( - shares: List?, operations: ArrayList + shares: List?, + operations: ArrayList ): ArrayList { if (shares != null) { // prepare operations to insert or update files to save in the given folder for (remoteShare in shares) { - val cv = ContentValues() - cv.put(ProviderTableMeta.OCSHARES_FILE_SOURCE, remoteShare.fileSource) - cv.put(ProviderTableMeta.OCSHARES_ITEM_SOURCE, remoteShare.itemSource) - cv.put(ProviderTableMeta.OCSHARES_SHARE_TYPE, remoteShare.shareType!!.value) - cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH, remoteShare.shareWith) - cv.put(ProviderTableMeta.OCSHARES_PATH, remoteShare.path) - cv.put(ProviderTableMeta.OCSHARES_PERMISSIONS, remoteShare.permissions) - cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, remoteShare.sharedDate) - cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, remoteShare.expirationDate) - cv.put(ProviderTableMeta.OCSHARES_TOKEN, remoteShare.token) - cv.put( - ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME, - remoteShare.sharedWithDisplayName - ) - cv.put( - ProviderTableMeta.OCSHARES_SHARE_WITH_ADDITIONAL_INFO, - remoteShare.sharedWithAdditionalInfo - ) - cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, if (remoteShare.isFolder) 1 else 0) - cv.put(ProviderTableMeta.OCSHARES_USER_ID, remoteShare.userId) - cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, remoteShare.id) - cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, account!!.name) - cv.put(ProviderTableMeta.OCSHARES_NAME, remoteShare.name) - cv.put(ProviderTableMeta.OCSHARES_URL, remoteShare.shareLink) + val cv = ContentValues().apply { + put(OCSHARES_FILE_SOURCE, remoteShare.fileSource) + put(OCSHARES_ITEM_SOURCE, remoteShare.itemSource) + put(OCSHARES_SHARE_TYPE, remoteShare.shareType!!.value) + put(OCSHARES_SHARE_WITH, remoteShare.shareWith) + put(OCSHARES_PATH, remoteShare.path) + put(OCSHARES_PERMISSIONS, remoteShare.permissions) + put(OCSHARES_SHARED_DATE, remoteShare.sharedDate) + put(OCSHARES_EXPIRATION_DATE, remoteShare.expirationDate) + put(OCSHARES_TOKEN, remoteShare.token) + put(OCSHARES_SHARE_WITH_DISPLAY_NAME, remoteShare.sharedWithDisplayName) + put(OCSHARES_SHARE_WITH_ADDITIONAL_INFO, remoteShare.sharedWithAdditionalInfo) + put(OCSHARES_IS_DIRECTORY, if (remoteShare.isFolder) 1 else 0) + put(OCSHARES_USER_ID, remoteShare.userId) + put(OCSHARES_ID_REMOTE_SHARED, remoteShare.id) + put(OCSHARES_ACCOUNT_OWNER, account!!.name) + put(OCSHARES_NAME, remoteShare.name) + put(OCSHARES_URL, remoteShare.shareLink) + } // adding a new share resource - operations.add( - ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).withValues(cv).build() - ) + operations.add(ContentProviderOperation.newInsert(CONTENT_URI_SHARE).withValues(cv).build()) } } return operations @@ -1629,8 +1423,7 @@ class FileDataStorageManager { folder: OCFile?, preparedOperations: ArrayList ): ArrayList { if (folder != null) { - val where = (ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " - + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?") + val where = ("$OCSHARES_PATH=? AND $OCSHARES_ACCOUNT_OWNER=?") val whereArgs = arrayOf("", account!!.name) val files = getFolderContent(folder, false) @@ -1638,7 +1431,7 @@ class FileDataStorageManager { for (file in files) { whereArgs[0] = file.remotePath preparedOperations.add( - ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).withSelection( + ContentProviderOperation.newDelete(CONTENT_URI_SHARE).withSelection( where, whereArgs ).build() @@ -1646,19 +1439,17 @@ class FileDataStorageManager { } } return preparedOperations - } private fun prepareRemoveSharesInFile( filePath: String, preparedOperations: ArrayList ): ArrayList { - val where = (ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " - + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?") + val where = ("$OCSHARES_PATH=? AND $OCSHARES_ACCOUNT_OWNER=?") val whereArgs = arrayOf(filePath, account!!.name) preparedOperations.add( - ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).withSelection( + ContentProviderOperation.newDelete(CONTENT_URI_SHARE).withSelection( where, whereArgs ).build() @@ -1670,33 +1461,26 @@ class FileDataStorageManager { fun getPrivateSharesForAFile(filePath: String, accountName: String): ArrayList { // Condition - val where = (ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " - + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + "AND" - + " (" + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR " - + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR " - + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? ) ") + val where = + ("$OCSHARES_PATH=? AND $OCSHARES_ACCOUNT_OWNER=?AND ($OCSHARES_SHARE_TYPE=? OR $OCSHARES_SHARE_TYPE=? OR $OCSHARES_SHARE_TYPE=? ) ") val whereArgs = arrayOf( filePath, accountName, - Integer.toString(ShareType.USER.value), - Integer.toString(ShareType.GROUP.value), - Integer.toString(ShareType.FEDERATED.value) + ShareType.USER.value.toString(), + ShareType.GROUP.value.toString(), + ShareType.FEDERATED.value.toString() ) var c: Cursor? - if (contentResolver != null) { - c = contentResolver!!.query( - ProviderTableMeta.CONTENT_URI_SHARE, null, where, whereArgs, null - ) + c = if (contentResolver != null) { + contentResolver!!.query(CONTENT_URI_SHARE, null, where, whereArgs, null) } else { try { - c = contentProviderClient!!.query( - ProviderTableMeta.CONTENT_URI_SHARE, null, where, whereArgs, null - ) + contentProviderClient!!.query(CONTENT_URI_SHARE, null, where, whereArgs, null) } catch (e: RemoteException) { - Log_OC.e(TAG, "Could not get list of shares with: " + e.message) - c = null + Log_OC.e(TAG, "Could not get list of shares with: ${e.message}", e) + null } } @@ -1717,27 +1501,19 @@ class FileDataStorageManager { fun getPublicSharesForAFile(filePath: String, accountName: String): ArrayList { // Condition - val where = (ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " - + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + "AND " - + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? ") - val whereArgs = arrayOf(filePath, accountName, Integer.toString(ShareType.PUBLIC_LINK.value)) + val where = ("$OCSHARES_PATH=? AND $OCSHARES_ACCOUNT_OWNER=?AND $OCSHARES_SHARE_TYPE=? ") + val whereArgs = arrayOf(filePath, accountName, ShareType.PUBLIC_LINK.value.toString()) - var c: Cursor? - if (contentResolver != null) { - c = contentResolver!!.query( - ProviderTableMeta.CONTENT_URI_SHARE, null, where, whereArgs, null - ) + val c: Cursor? = if (contentResolver != null) { + contentResolver!!.query(CONTENT_URI_SHARE, null, where, whereArgs, null) } else { try { - c = contentProviderClient!!.query( - ProviderTableMeta.CONTENT_URI_SHARE, null, where, whereArgs, null - ) + contentProviderClient!!.query(CONTENT_URI_SHARE, null, where, whereArgs, null) } catch (e: RemoteException) { - Log_OC.e(TAG, "Could not get list of shares with: " + e.message) - c = null + Log_OC.e(TAG, "Could not get list of shares with: ${e.message}", e) + null } - } val publicShares = ArrayList() var publicShare: OCShareEntity? @@ -1781,106 +1557,106 @@ class FileDataStorageManager { } } + @Suppress("DEPRECATION") fun deleteFileInMediaScan(path: String) { - val mimetypeString = FileStorageUtils.getMimeTypeFromName(path) + val mimeTypeString = FileStorageUtils.getMimeTypeFromName(path) val contentResolver = contentResolver if (contentResolver != null) { - if (mimetypeString.startsWith("image/")) { - // Images - contentResolver.delete( - MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - MediaStore.Images.Media.DATA + "=?", arrayOf(path) - ) - } else if (mimetypeString.startsWith("audio/")) { - // Audio - contentResolver.delete( - MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, - MediaStore.Audio.Media.DATA + "=?", arrayOf(path) - ) - } else if (mimetypeString.startsWith("video/")) { - // Video - contentResolver.delete( - MediaStore.Video.Media.EXTERNAL_CONTENT_URI, - MediaStore.Video.Media.DATA + "=?", arrayOf(path) - ) - } - } else { - val contentProviderClient = contentProviderClient - try { - if (mimetypeString.startsWith("image/")) { - // Images - contentProviderClient!!.delete( + when { + mimeTypeString.startsWith(pathImage) -> // Images + contentResolver.delete( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - MediaStore.Images.Media.DATA + "=?", arrayOf(path) + MediaStore.Images.Media.DATA + "=?", + arrayOf(path) ) - } else if (mimetypeString.startsWith("audio/")) { - // Audio - contentProviderClient!!.delete( + mimeTypeString.startsWith(pathAudio) -> // Audio + contentResolver.delete( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, - MediaStore.Audio.Media.DATA + "=?", arrayOf(path) + "${MediaStore.Audio.Media.DATA}=?", + arrayOf(path) ) - } else if (mimetypeString.startsWith("video/")) { - // Video - contentProviderClient!!.delete( + mimeTypeString.startsWith(pathVideo) -> // Video + contentResolver.delete( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, - MediaStore.Video.Media.DATA + "=?", arrayOf(path) + "${MediaStore.Video.Media.DATA}=?", + arrayOf(path) ) + } + } else { + val contentProviderClient = contentProviderClient + try { + when { + mimeTypeString.startsWith(pathImage) -> // Images + contentProviderClient!!.delete( + MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + "${MediaStore.Images.Media.DATA}=?", + arrayOf(path) + ) + mimeTypeString.startsWith(pathAudio) -> // Audio + contentProviderClient!!.delete( + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, + "${MediaStore.Audio.Media.DATA}=?", + arrayOf(path) + ) + mimeTypeString.startsWith(pathVideo) -> // Video + contentProviderClient!!.delete( + MediaStore.Video.Media.EXTERNAL_CONTENT_URI, + "${MediaStore.Video.Media.DATA}=?", + arrayOf(path) + ) } } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception deleting media file in MediaStore " + e.message) + Log_OC.e(TAG, "Exception deleting media file in MediaStore ${e.message}", e) } - } - } - fun saveConflict(file: OCFile, etagInConflict: String?) { - var etagInConflict = etagInConflict + fun saveConflict(file: OCFile, eTagInConflictFromParameter: String?) { + var eTagInConflict = eTagInConflictFromParameter if (!file.isDown) { - etagInConflict = null + eTagInConflict = null } val cv = ContentValues() - cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, etagInConflict) + cv.put(FILE_ETAG_IN_CONFLICT, eTagInConflict) var updated = 0 if (contentResolver != null) { updated = contentResolver!!.update( - ProviderTableMeta.CONTENT_URI_FILE, + CONTENT_URI_FILE, cv, - ProviderTableMeta._ID + "=?", + "$_ID=?", arrayOf(file.fileId.toString()) ) } else { try { updated = contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI_FILE, + CONTENT_URI_FILE, cv, - ProviderTableMeta._ID + "=?", + "$_ID=?", arrayOf(file.fileId.toString()) ) } catch (e: RemoteException) { - Log_OC.e(TAG, "Failed saving conflict in database " + e.message) + Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) } - } Log_OC.d(TAG, "Number of files updated with CONFLICT: $updated") if (updated > 0) { - if (etagInConflict != null) { + if (eTagInConflict != null) { /// set conflict in all ancestor folders var parentId = file.parentId val ancestorIds = HashSet() - while (parentId != FileDataStorageManager.ROOT_PARENT_ID.toLong()) { - ancestorIds.add(java.lang.Long.toString(parentId)) + while (parentId != ROOT_PARENT_ID.toLong()) { + ancestorIds.add(parentId.toString()) parentId = getFileById(parentId)!!.parentId } if (ancestorIds.size > 0) { val whereBuffer = StringBuffer() - whereBuffer.append(ProviderTableMeta._ID).append(" IN (") + whereBuffer.append(_ID).append(" IN (") for (i in 0 until ancestorIds.size - 1) { whereBuffer.append("?,") } @@ -1889,7 +1665,7 @@ class FileDataStorageManager { if (contentResolver != null) { updated = contentResolver!!.update( - ProviderTableMeta.CONTENT_URI_FILE, + CONTENT_URI_FILE, cv, whereBuffer.toString(), ancestorIds.toTypedArray() @@ -1897,15 +1673,14 @@ class FileDataStorageManager { } else { try { updated = contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI_FILE, + CONTENT_URI_FILE, cv, whereBuffer.toString(), ancestorIds.toTypedArray() ) } catch (e: RemoteException) { - Log_OC.e(TAG, "Failed saving conflict in database " + e.message) + Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) } - } } // else file is ROOT folder, no parent to set in conflict @@ -1913,36 +1688,38 @@ class FileDataStorageManager { /// update conflict in ancestor folders // (not directly unset; maybe there are more conflicts below them) var parentPath = file.remotePath - if (parentPath.endsWith(OCFile.PATH_SEPARATOR)) { + if (parentPath.endsWith(PATH_SEPARATOR)) { parentPath = parentPath.substring(0, parentPath.length - 1) } - parentPath = parentPath.substring(0, parentPath.lastIndexOf(OCFile.PATH_SEPARATOR) + 1) + parentPath = parentPath.substring(0, parentPath.lastIndexOf(PATH_SEPARATOR) + 1) Log_OC.d(TAG, "checking parents to remove conflict; STARTING with $parentPath") - while (parentPath.length > 0) { + while (parentPath.isNotEmpty()) { - val whereForDescencentsInConflict = ProviderTableMeta.FILE_ETAG_IN_CONFLICT + " IS NOT NULL AND " + - ProviderTableMeta.FILE_CONTENT_TYPE + " != 'DIR' AND " + - ProviderTableMeta.FILE_ACCOUNT_OWNER + " = ? AND " + - ProviderTableMeta.FILE_PATH + " LIKE ?" + val whereForDescendantsInConflict = FILE_ETAG_IN_CONFLICT + " IS NOT NULL AND " + + FILE_CONTENT_TYPE + " != 'DIR' AND " + + FILE_ACCOUNT_OWNER + " = ? AND " + + FILE_PATH + " LIKE ?" var descendantsInConflict: Cursor? = null if (contentResolver != null) { descendantsInConflict = contentResolver!!.query( - ProviderTableMeta.CONTENT_URI_FILE, - arrayOf(ProviderTableMeta._ID), - whereForDescencentsInConflict, - arrayOf(account!!.name, "$parentPath%"), null + CONTENT_URI_FILE, + arrayOf(_ID), + whereForDescendantsInConflict, + arrayOf(account!!.name, "$parentPath%"), + null ) } else { try { descendantsInConflict = contentProviderClient!!.query( - ProviderTableMeta.CONTENT_URI_FILE, - arrayOf(ProviderTableMeta._ID), - whereForDescencentsInConflict, - arrayOf(account!!.name, "$parentPath%"), null + CONTENT_URI_FILE, + arrayOf(_ID), + whereForDescendantsInConflict, + arrayOf(account!!.name, "$parentPath%"), + null ) } catch (e: RemoteException) { - Log_OC.e(TAG, "Failed querying for descendants in conflict " + e.message) + Log_OC.e(TAG, "Failed querying for descendants in conflict ${e.message}", e) } } @@ -1950,150 +1727,111 @@ class FileDataStorageManager { Log_OC.d(TAG, "NO MORE conflicts in $parentPath") if (contentResolver != null) { updated = contentResolver!!.update( - ProviderTableMeta.CONTENT_URI_FILE, + CONTENT_URI_FILE, cv, - ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + - ProviderTableMeta.FILE_PATH + "=?", + "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?", arrayOf(account!!.name, parentPath) ) } else { try { updated = contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI_FILE, + CONTENT_URI_FILE, cv, - ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + - ProviderTableMeta.FILE_PATH + "=?", arrayOf(account!!.name, parentPath) + "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?", + arrayOf(account!!.name, parentPath) ) } catch (e: RemoteException) { - Log_OC.e(TAG, "Failed saving conflict in database " + e.message) + Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) } - } } else { - Log_OC.d(TAG, "STILL " + descendantsInConflict.count + " in " + parentPath) + Log_OC.d(TAG, "STILL ${descendantsInConflict.count} in $parentPath") } descendantsInConflict?.close() parentPath = parentPath.substring(0, parentPath.length - 1) // trim last / - parentPath = parentPath.substring(0, parentPath.lastIndexOf(OCFile.PATH_SEPARATOR) + 1) + parentPath = parentPath.substring(0, parentPath.lastIndexOf(PATH_SEPARATOR) + 1) Log_OC.d(TAG, "checking parents to remove conflict; NEXT $parentPath") } } } - } fun saveCapabilities(capability: RemoteCapability): RemoteCapability { // Prepare capabilities data - val cv = ContentValues() - cv.put(ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME, account!!.name) - cv.put(ProviderTableMeta.CAPABILITIES_VERSION_MAYOR, capability.versionMayor) - cv.put(ProviderTableMeta.CAPABILITIES_VERSION_MINOR, capability.versionMinor) - cv.put(ProviderTableMeta.CAPABILITIES_VERSION_MICRO, capability.versionMicro) - cv.put(ProviderTableMeta.CAPABILITIES_VERSION_STRING, capability.versionString) - cv.put(ProviderTableMeta.CAPABILITIES_VERSION_EDITION, capability.versionEdition) - cv.put(ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL, capability.corePollinterval) - cv.put(ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED, capability.filesSharingApiEnabled.value) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED, - capability.filesSharingPublicEnabled.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED, - capability.filesSharingPublicPasswordEnforced.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY, - capability.filesSharingPublicPasswordEnforcedReadOnly.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE, - capability.filesSharingPublicPasswordEnforcedReadWrite.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY, - capability.filesSharingPublicPasswordEnforcedUploadOnly.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED, - capability.filesSharingPublicExpireDateEnabled.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS, - capability.filesSharingPublicExpireDateDays - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED, - capability.filesSharingPublicExpireDateEnforced.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL, - capability.filesSharingPublicSendMail.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD, - capability.filesSharingPublicUpload.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE, - capability.filesSharingPublicMultiple.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY, - capability.filesSharingPublicSupportsUploadOnly.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL, - capability.filesSharingUserSendMail.value - ) - cv.put(ProviderTableMeta.CAPABILITIES_SHARING_RESHARING, capability.filesSharingResharing.value) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING, - capability.filesSharingFederationOutgoing.value - ) - cv.put( - ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING, - capability.filesSharingFederationIncoming.value - ) - cv.put(ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING, capability.filesBigFileChunking.value) - cv.put(ProviderTableMeta.CAPABILITIES_FILES_UNDELETE, capability.filesUndelete.value) - cv.put(ProviderTableMeta.CAPABILITIES_FILES_VERSIONING, capability.filesVersioning.value) + val cv = ContentValues().apply { + put(CAPABILITIES_ACCOUNT_NAME, account!!.name) + put(CAPABILITIES_VERSION_MAYOR, capability.versionMayor) + put(CAPABILITIES_VERSION_MINOR, capability.versionMinor) + put(CAPABILITIES_VERSION_MICRO, capability.versionMicro) + put(CAPABILITIES_VERSION_STRING, capability.versionString) + put(CAPABILITIES_VERSION_EDITION, capability.versionEdition) + put(CAPABILITIES_CORE_POLLINTERVAL, capability.corePollinterval) + put(CAPABILITIES_SHARING_API_ENABLED, capability.filesSharingApiEnabled.value) + put(CAPABILITIES_SHARING_PUBLIC_ENABLED, capability.filesSharingPublicEnabled.value) + put(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED, capability.filesSharingPublicPasswordEnforced.value) + put( + CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY, + capability.filesSharingPublicPasswordEnforcedReadOnly.value + ) + put( + CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE, + capability.filesSharingPublicPasswordEnforcedReadWrite.value + ) + put( + CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY, + capability.filesSharingPublicPasswordEnforcedUploadOnly.value + ) + put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED, capability.filesSharingPublicExpireDateEnabled.value) + put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS, capability.filesSharingPublicExpireDateDays) + put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED, capability.filesSharingPublicExpireDateEnforced.value) + put(CAPABILITIES_SHARING_PUBLIC_SEND_MAIL, capability.filesSharingPublicSendMail.value) + put(CAPABILITIES_SHARING_PUBLIC_UPLOAD, capability.filesSharingPublicUpload.value) + put(CAPABILITIES_SHARING_PUBLIC_MULTIPLE, capability.filesSharingPublicMultiple.value) + put(CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY, capability.filesSharingPublicSupportsUploadOnly.value) + put(CAPABILITIES_SHARING_USER_SEND_MAIL, capability.filesSharingUserSendMail.value) + put(CAPABILITIES_SHARING_RESHARING, capability.filesSharingResharing.value) + put(CAPABILITIES_SHARING_FEDERATION_OUTGOING, capability.filesSharingFederationOutgoing.value) + put(CAPABILITIES_SHARING_FEDERATION_INCOMING, capability.filesSharingFederationIncoming.value) + put(CAPABILITIES_FILES_BIGFILECHUNKING, capability.filesBigFileChunking.value) + put(CAPABILITIES_FILES_UNDELETE, capability.filesUndelete.value) + put(CAPABILITIES_FILES_VERSIONING, capability.filesVersioning.value) + } if (capabilityExists(account!!.name)) { if (contentResolver != null) { contentResolver!!.update( - ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv, - ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=?", + CONTENT_URI_CAPABILITIES, + cv, + "$CAPABILITIES_ACCOUNT_NAME=?", arrayOf(account!!.name) ) } else { try { contentProviderClient!!.update( - ProviderTableMeta.CONTENT_URI_CAPABILITIES, - cv, ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=?", + CONTENT_URI_CAPABILITIES, + cv, + "$CAPABILITIES_ACCOUNT_NAME=?", arrayOf(account!!.name) ) } catch (e: RemoteException) { - Log_OC.e( - TAG, - "Fail to insert insert file to database " + e.message - ) + Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}") } } } else { - var result_uri: Uri? = null + var resultUri: Uri? = null if (contentResolver != null) { - result_uri = contentResolver!!.insert( - ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv + resultUri = contentResolver!!.insert( + CONTENT_URI_CAPABILITIES, cv ) } else { try { - result_uri = contentProviderClient!!.insert( - ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv + resultUri = contentProviderClient!!.insert( + CONTENT_URI_CAPABILITIES, cv ) } catch (e: RemoteException) { Log_OC.e( @@ -2101,10 +1839,9 @@ class FileDataStorageManager { "Fail to insert insert capability to database " + e.message ) } - } - if (result_uri != null) { - val new_id = java.lang.Long.parseLong(result_uri.pathSegments[1]) + if (resultUri != null) { + val new_id = parseLong(resultUri.pathSegments[1]) capability.accountName = account!!.name } } @@ -2125,26 +1862,23 @@ class FileDataStorageManager { private fun getCapabilityCursorForAccount(accountName: String): Cursor? { var c: Cursor? = null if (contentResolver != null) { - c = contentResolver!! - .query( - ProviderTableMeta.CONTENT_URI_CAPABILITIES, null, - ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=? ", - arrayOf(accountName), null - ) + c = contentResolver!!.query( + CONTENT_URI_CAPABILITIES, null, + "$CAPABILITIES_ACCOUNT_NAME=? ", + arrayOf(accountName), + null + ) } else { try { c = contentProviderClient!!.query( - ProviderTableMeta.CONTENT_URI_CAPABILITIES, null, - ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=? ", - arrayOf(accountName), null + CONTENT_URI_CAPABILITIES, null, + "$CAPABILITIES_ACCOUNT_NAME=? ", + arrayOf(accountName), + null ) } catch (e: RemoteException) { - Log_OC.e( - TAG, - "Couldn't determine capability existance, assuming non existance: " + e.message - ) + Log_OC.e(TAG, "Couldn't determine capability existence, assuming non existence: ${e.message}") } - } return c } @@ -2167,72 +1901,70 @@ class FileDataStorageManager { var capability: OCCapability? = null if (c != null) { capability = OCCapability( - accountName = c.getString(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME)), - versionMayor = c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_MAYOR)), - versionMinor = c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_MINOR)), - versionMicro = c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_MICRO)), - versionString = c.getString(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_STRING)), - versionEdition = c.getString(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_EDITION)), - corePollInterval = c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL)), + accountName = c.getString(c.getColumnIndex(CAPABILITIES_ACCOUNT_NAME)), + versionMayor = c.getInt(c.getColumnIndex(CAPABILITIES_VERSION_MAYOR)), + versionMinor = c.getInt(c.getColumnIndex(CAPABILITIES_VERSION_MINOR)), + versionMicro = c.getInt(c.getColumnIndex(CAPABILITIES_VERSION_MICRO)), + versionString = c.getString(c.getColumnIndex(CAPABILITIES_VERSION_STRING)), + versionEdition = c.getString(c.getColumnIndex(CAPABILITIES_VERSION_EDITION)), + corePollInterval = c.getInt(c.getColumnIndex(CAPABILITIES_CORE_POLLINTERVAL)), filesSharingApiEnabled = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_API_ENABLED)) )!!, filesSharingPublicEnabled = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_ENABLED)) )!!, filesSharingPublicPasswordEnforced = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED)) )!!, filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY)) )!!, filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE)) )!!, filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY)) )!!, filesSharingPublicExpireDateEnabled = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED)) )!!, filesSharingPublicExpireDateDays = c.getInt( - c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS) + c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS) ), filesSharingPublicExpireDateEnforced = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED)) )!!, filesSharingPublicSendMail = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_SEND_MAIL)) )!!, filesSharingPublicUpload = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_UPLOAD)) )!!, filesSharingPublicMultiple = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_MULTIPLE)) )!!, filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY)) )!!, filesSharingUserSendMail = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_USER_SEND_MAIL)) )!!, filesSharingResharing = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_RESHARING)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_RESHARING)) )!!, filesSharingFederationOutgoing = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_FEDERATION_OUTGOING)) )!!, filesSharingFederationIncoming = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING)) + c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_FEDERATION_INCOMING)) )!!, filesBigFileChunking = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING)) - )!!, - filesUndelete = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_FILES_UNDELETE)) + c.getInt(c.getColumnIndex(CAPABILITIES_FILES_BIGFILECHUNKING)) )!!, + filesUndelete = CapabilityBooleanType.fromValue(c.getInt(c.getColumnIndex(CAPABILITIES_FILES_UNDELETE)))!!, filesVersioning = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(ProviderTableMeta.CAPABILITIES_FILES_VERSIONING)) + c.getInt(c.getColumnIndex(CAPABILITIES_FILES_VERSIONING)) )!! ) } @@ -2240,19 +1972,16 @@ class FileDataStorageManager { } private fun selectionForAllDescendantsOf(file: OCFile): Pair> { - val selection = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + - ProviderTableMeta.FILE_PATH + " LIKE ? " - val selectionArgs = arrayOf( - account!!.name, file.remotePath + "_%" // one or more characters after remote path - ) - return Pair( - selection, - selectionArgs - ) + val selection = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH LIKE ? " + val selectionArgs = arrayOf(account!!.name, "${file.remotePath}_%") // one or more characters after remote path + return Pair(selection, selectionArgs) } companion object { - val ROOT_PARENT_ID = 0 private val TAG = FileDataStorageManager::class.java.simpleName + const val ROOT_PARENT_ID = 0 + private const val pathAudio = "audio/" + private const val pathVideo = "video/" + private const val pathImage = "image/" } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/ToolbarActivity.java b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/ToolbarActivity.java index 4ee9f39c67e..d32d7b7c1ff 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/activity/ToolbarActivity.java +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/activity/ToolbarActivity.java @@ -58,7 +58,7 @@ protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) { // choose the appropriate title inRoot = ( chosenFile == null || - (chosenFile.isFolder() && chosenFile.getParentId() == FileDataStorageManager.Companion.getROOT_PARENT_ID()) + (chosenFile.isFolder() && chosenFile.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) ); if (!inRoot) { title = chosenFile.getFileName(); @@ -103,7 +103,7 @@ protected void updateActionBarTitleAndHomeButtonByString(String title) { */ public boolean isRoot(OCFile file) { return file == null || - (file.isFolder() && file.getParentId() == FileDataStorageManager.Companion.getROOT_PARENT_ID()); + (file.isFolder() && file.getParentId() == FileDataStorageManager.ROOT_PARENT_ID); } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java b/owncloudApp/src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java index 847ae8a3d28..30794780383 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java @@ -678,7 +678,7 @@ public int onBrowseUp() { FileDataStorageManager storageManager = mContainerActivity.getStorageManager(); String parentPath = null; - if (mFile.getParentId() != FileDataStorageManager.Companion.getROOT_PARENT_ID()) { + if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) { parentPath = new File(mFile.getRemotePath()).getParent(); parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR; @@ -1126,7 +1126,7 @@ public boolean isGridViewPreferred(OCFile file) { return setting.getBoolean(String.valueOf(fileToTest.getFileId()), false); } else { do { - if (fileToTest.getParentId() != FileDataStorageManager.Companion.getROOT_PARENT_ID()) { + if (fileToTest.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) { parentPath = new File(fileToTest.getRemotePath()).getParent(); parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR; diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java index 4b4c7e37c69..81cab266e19 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java @@ -434,7 +434,7 @@ protected void onAccountSet(boolean stateWasRecovered) { } // Update file according to DB file, if it is possible - if (file.getFileId() > FileDataStorageManager.Companion.getROOT_PARENT_ID()) { + if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID) { file = getStorageManager().getFileById(file.getFileId()); } From 2cae8deaffcc58591b706ef3c6d87c0816f00a20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Fri, 15 Nov 2019 11:52:22 +0100 Subject: [PATCH 02/41] Remove already implemented functions in usecases from FileDataStorageManager --- .../datamodel/FileDataStorageManager.kt | 427 ------------------ 1 file changed, 427 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt index 1ddf67149c5..0852e80b052 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt @@ -46,15 +46,12 @@ import androidx.core.util.Pair import com.owncloud.android.MainApp import com.owncloud.android.R import com.owncloud.android.authentication.AccountUtils -import com.owncloud.android.data.sharing.shares.db.OCShareEntity import com.owncloud.android.datamodel.OCFile.* import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.* import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.datamodel.OCFile.AvailableOfflineStatus.* -import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.common.utils.Log_OC -import com.owncloud.android.lib.resources.shares.RemoteShare import com.owncloud.android.lib.resources.status.RemoteCapability import com.owncloud.android.utils.FileStorageUtils @@ -1107,430 +1104,6 @@ class FileDataStorageManager { } } - // Methods for Shares - fun saveShare(remoteShare: RemoteShare): Boolean { - var overriden = false - val cv = ContentValues().apply { - put(OCSHARES_FILE_SOURCE, remoteShare.fileSource) - put(OCSHARES_ITEM_SOURCE, remoteShare.itemSource) - put(OCSHARES_SHARE_TYPE, remoteShare.shareType!!.value) - put(OCSHARES_SHARE_WITH, remoteShare.shareWith) - put(OCSHARES_PATH, remoteShare.path) - put(OCSHARES_PERMISSIONS, remoteShare.permissions) - put(OCSHARES_SHARED_DATE, remoteShare.sharedDate) - put(OCSHARES_EXPIRATION_DATE, remoteShare.expirationDate) - put(OCSHARES_TOKEN, remoteShare.token) - put(OCSHARES_SHARE_WITH_DISPLAY_NAME, remoteShare.sharedWithDisplayName) - put(OCSHARES_SHARE_WITH_ADDITIONAL_INFO, remoteShare.sharedWithAdditionalInfo) - put(OCSHARES_IS_DIRECTORY, if (remoteShare.isFolder) 1 else 0) - put(OCSHARES_USER_ID, remoteShare.userId) - put(OCSHARES_ID_REMOTE_SHARED, remoteShare.id) - put(OCSHARES_NAME, remoteShare.name) - put(OCSHARES_URL, remoteShare.shareLink) - put(OCSHARES_ACCOUNT_OWNER, account!!.name) - } - - if (shareExistsForRemoteId(remoteShare.id)) {// for renamed files; no more delete and create - overriden = true - if (contentResolver != null) { - contentResolver!!.update( - CONTENT_URI_SHARE, - cv, - "$OCSHARES_ID_REMOTE_SHARED=?", - arrayOf(remoteShare.id.toString()) - ) - } else { - try { - contentProviderClient!!.update( - CONTENT_URI_SHARE, - cv, - "$OCSHARES_ID_REMOTE_SHARED=?", - arrayOf(remoteShare.id.toString()) - ) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}", e) - } - } - } else { - var resultUri: Uri? = null - if (contentResolver != null) { - resultUri = contentResolver!!.insert(CONTENT_URI_SHARE, cv) - } else { - try { - resultUri = contentProviderClient!!.insert(CONTENT_URI_SHARE, cv) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}", e) - } - } - } - - return overriden - } - - /** - * Retrieves an stored [OCShareEntity] given its id. - * - * @param id Identifier. - * @return Stored [OCShareEntity] given its id. - */ - fun getShareById(id: Long): OCShareEntity? { - var share: OCShareEntity? = null - val c = getShareCursorForValue(_ID, id.toString()) - if (c != null) { - if (c.moveToFirst()) { - share = createShareInstance(c) - } - c.close() - } - return share - } - - /** - * Retrieves an stored [OCShareEntity] given its id. - * - * @param id Identifier of the share in OC server. - * @return Stored [OCShareEntity] given its remote id. - */ - fun getShareByRemoteId(id: Long): OCShareEntity? { - var share: OCShareEntity? = null - val c = getShareCursorForValue(OCSHARES_ID_REMOTE_SHARED, id.toString()) - if (c != null) { - if (c.moveToFirst()) { - share = createShareInstance(c) - } - c.close() - } - return share - } - - /** - * Checks the existance of an stored [RemoteShare] matching the given remote id (not to be confused with - * the local id) in the current account. - * - * @param remoteId Remote of the share in the server. - * @return 'True' if a matching [RemoteShare] is stored in the current account. - */ - private fun shareExistsForRemoteId(remoteId: Long): Boolean { - return shareExistsForValue(OCSHARES_ID_REMOTE_SHARED, remoteId.toString()) - } - - /** - * Checks the existance of an stored [RemoteShare] in the current account - * matching a given column and a value for that column - * - * @param key Name of the column to match. - * @param value Value of the column to match. - * @return 'True' if a matching [RemoteShare] is stored in the current account. - */ - private fun shareExistsForValue(key: String, value: String): Boolean { - val c = getShareCursorForValue(key, value) - var retval = false - if (c != null) { - retval = c.moveToFirst() - c.close() - } - return retval - } - - /** - * Gets a [Cursor] for an stored [RemoteShare] in the current account - * matching a given column and a value for that column - * - * @param key Name of the column to match. - * @param value Value of the column to match. - * @return 'True' if a matching [RemoteShare] is stored in the current account. - */ - private fun getShareCursorForValue(key: String, value: String): Cursor? { - return if (contentResolver != null) { - contentResolver!!.query( - CONTENT_URI_SHARE, - null, - "$key=? AND $OCSHARES_ACCOUNT_OWNER=?", - arrayOf(value, account!!.name), - null - ) - } else { - try { - contentProviderClient!!.query( - CONTENT_URI_SHARE, - null, - "$key=? AND $OCSHARES_ACCOUNT_OWNER=?", - arrayOf(value, account!!.name), - null - ) - } catch (e: RemoteException) { - Log_OC.w(TAG, "Could not get details, assuming share does not exist: ${e.message}") - null - } - } - } - - private fun createShareInstance(c: Cursor?) = c?.let { - OCShareEntity( - it.getLong(it.getColumnIndex(OCSHARES_FILE_SOURCE)), - it.getLong(it.getColumnIndex(OCSHARES_ITEM_SOURCE)), - it.getInt(it.getColumnIndex(OCSHARES_SHARE_TYPE)), - it.getString(it.getColumnIndex(OCSHARES_SHARE_WITH)), - it.getString(it.getColumnIndex(OCSHARES_PATH)), - it.getInt(it.getColumnIndex(OCSHARES_PERMISSIONS)), - it.getLong(it.getColumnIndex(OCSHARES_SHARED_DATE)), - it.getLong(it.getColumnIndex(OCSHARES_EXPIRATION_DATE)), - it.getString(it.getColumnIndex(OCSHARES_TOKEN)), - it.getString(it.getColumnIndex(OCSHARES_SHARE_WITH_DISPLAY_NAME)), - it.getString(it.getColumnIndex(OCSHARES_SHARE_WITH_ADDITIONAL_INFO)), - it.getInt(it.getColumnIndex(OCSHARES_IS_DIRECTORY)) == 1, - it.getLong(it.getColumnIndex(OCSHARES_USER_ID)), - it.getLong(it.getColumnIndex(OCSHARES_ID_REMOTE_SHARED)), - it.getString(it.getColumnIndex(OCSHARES_ACCOUNT_OWNER)), - it.getString(it.getColumnIndex(OCSHARES_NAME)), - it.getString(it.getColumnIndex(OCSHARES_URL)) - ) - } - - private fun resetShareFlagsInAllFiles() { - val cv = ContentValues() - cv.put(FILE_SHARED_VIA_LINK, false) - cv.put(FILE_SHARED_WITH_SHAREE, false) - cv.put(FILE_PUBLIC_LINK, "") - val where = "$FILE_ACCOUNT_OWNER=?" - val whereArgs = arrayOf(account!!.name) - - if (contentResolver != null) { - contentResolver!!.update(CONTENT_URI, cv, where, whereArgs) - - } else { - try { - contentProviderClient!!.update(CONTENT_URI, cv, where, whereArgs) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception in resetShareFlagsInAllFiles ${e.message}", e) - } - } - } - - private fun resetShareFlagsInFolder(folder: OCFile) { - val cv = ContentValues() - cv.put(FILE_SHARED_VIA_LINK, false) - cv.put(FILE_SHARED_WITH_SHAREE, false) - cv.put(FILE_PUBLIC_LINK, "") - val where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PARENT=?" - val whereArgs = arrayOf(account!!.name, folder.fileId.toString()) - - if (contentResolver != null) { - contentResolver!!.update(CONTENT_URI, cv, where, whereArgs) - - } else { - try { - contentProviderClient!!.update(CONTENT_URI, cv, where, whereArgs) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception in resetShareFlagsInFolder ${e.message}", e) - } - } - } - - private fun resetShareFlagInAFile(filePath: String) { - val cv = ContentValues() - cv.put(FILE_SHARED_VIA_LINK, false) - cv.put(FILE_SHARED_WITH_SHAREE, false) - cv.put(FILE_PUBLIC_LINK, "") - val where = FILE_ACCOUNT_OWNER + "=? AND " + FILE_PATH + "=?" - val whereArgs = arrayOf(account!!.name, filePath) - - if (contentResolver != null) { - contentResolver!!.update(CONTENT_URI, cv, where, whereArgs) - } else { - try { - contentProviderClient!!.update(CONTENT_URI, cv, where, whereArgs) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception in resetShareFlagsInFolder ${e.message}", e) - } - } - } - - private fun cleanShares() { - val where = "$OCSHARES_ACCOUNT_OWNER=?" - val whereArgs = arrayOf(account!!.name) - - if (contentResolver != null) { - contentResolver!!.delete(CONTENT_URI_SHARE, where, whereArgs) - - } else { - try { - contentProviderClient!!.delete(CONTENT_URI_SHARE, where, whereArgs) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception in cleanShares ${e.message}", e) - } - } - } - - fun removeShare(share: OCShareEntity) { - val shareUri = CONTENT_URI_SHARE - val where = "$OCSHARES_ACCOUNT_OWNER=? AND $_ID=?" - val whereArgs = arrayOf(account!!.name, share.id.toString()) - if (contentProviderClient != null) { - try { - contentProviderClient!!.delete(shareUri, where, whereArgs) - } catch (e: RemoteException) { - e.printStackTrace() - } - } else { - contentResolver!!.delete(shareUri, where, whereArgs) - } - } - - /** - * Prepare operations to insert or update files to save in the given folder - * - * @param shares List of shares to insert - * @param operations List of operations - * @return - */ - private fun prepareInsertShares( - shares: List?, - operations: ArrayList - ): ArrayList { - - if (shares != null) { - // prepare operations to insert or update files to save in the given folder - for (remoteShare in shares) { - val cv = ContentValues().apply { - put(OCSHARES_FILE_SOURCE, remoteShare.fileSource) - put(OCSHARES_ITEM_SOURCE, remoteShare.itemSource) - put(OCSHARES_SHARE_TYPE, remoteShare.shareType!!.value) - put(OCSHARES_SHARE_WITH, remoteShare.shareWith) - put(OCSHARES_PATH, remoteShare.path) - put(OCSHARES_PERMISSIONS, remoteShare.permissions) - put(OCSHARES_SHARED_DATE, remoteShare.sharedDate) - put(OCSHARES_EXPIRATION_DATE, remoteShare.expirationDate) - put(OCSHARES_TOKEN, remoteShare.token) - put(OCSHARES_SHARE_WITH_DISPLAY_NAME, remoteShare.sharedWithDisplayName) - put(OCSHARES_SHARE_WITH_ADDITIONAL_INFO, remoteShare.sharedWithAdditionalInfo) - put(OCSHARES_IS_DIRECTORY, if (remoteShare.isFolder) 1 else 0) - put(OCSHARES_USER_ID, remoteShare.userId) - put(OCSHARES_ID_REMOTE_SHARED, remoteShare.id) - put(OCSHARES_ACCOUNT_OWNER, account!!.name) - put(OCSHARES_NAME, remoteShare.name) - put(OCSHARES_URL, remoteShare.shareLink) - } - - // adding a new share resource - operations.add(ContentProviderOperation.newInsert(CONTENT_URI_SHARE).withValues(cv).build()) - } - } - return operations - } - - private fun prepareRemoveSharesInFolder( - folder: OCFile?, preparedOperations: ArrayList - ): ArrayList { - if (folder != null) { - val where = ("$OCSHARES_PATH=? AND $OCSHARES_ACCOUNT_OWNER=?") - val whereArgs = arrayOf("", account!!.name) - - val files = getFolderContent(folder, false) - - for (file in files) { - whereArgs[0] = file.remotePath - preparedOperations.add( - ContentProviderOperation.newDelete(CONTENT_URI_SHARE).withSelection( - where, - whereArgs - ).build() - ) - } - } - return preparedOperations - } - - private fun prepareRemoveSharesInFile( - filePath: String, preparedOperations: ArrayList - ): ArrayList { - - val where = ("$OCSHARES_PATH=? AND $OCSHARES_ACCOUNT_OWNER=?") - val whereArgs = arrayOf(filePath, account!!.name) - - preparedOperations.add( - ContentProviderOperation.newDelete(CONTENT_URI_SHARE).withSelection( - where, - whereArgs - ).build() - ) - - return preparedOperations - - } - - fun getPrivateSharesForAFile(filePath: String, accountName: String): ArrayList { - // Condition - val where = - ("$OCSHARES_PATH=? AND $OCSHARES_ACCOUNT_OWNER=?AND ($OCSHARES_SHARE_TYPE=? OR $OCSHARES_SHARE_TYPE=? OR $OCSHARES_SHARE_TYPE=? ) ") - val whereArgs = arrayOf( - filePath, - accountName, - ShareType.USER.value.toString(), - ShareType.GROUP.value.toString(), - ShareType.FEDERATED.value.toString() - ) - - var c: Cursor? - c = if (contentResolver != null) { - contentResolver!!.query(CONTENT_URI_SHARE, null, where, whereArgs, null) - } else { - try { - contentProviderClient!!.query(CONTENT_URI_SHARE, null, where, whereArgs, null) - - } catch (e: RemoteException) { - Log_OC.e(TAG, "Could not get list of shares with: ${e.message}", e) - null - } - - } - val privateShares = ArrayList() - var privateShare: OCShareEntity? - if (c != null) { - if (c.moveToFirst()) { - do { - privateShare = createShareInstance(c) - privateShares.add(privateShare!!) - } while (c.moveToNext()) - } - c.close() - } - - return privateShares - } - - fun getPublicSharesForAFile(filePath: String, accountName: String): ArrayList { - // Condition - val where = ("$OCSHARES_PATH=? AND $OCSHARES_ACCOUNT_OWNER=?AND $OCSHARES_SHARE_TYPE=? ") - val whereArgs = arrayOf(filePath, accountName, ShareType.PUBLIC_LINK.value.toString()) - - val c: Cursor? = if (contentResolver != null) { - contentResolver!!.query(CONTENT_URI_SHARE, null, where, whereArgs, null) - } else { - try { - contentProviderClient!!.query(CONTENT_URI_SHARE, null, where, whereArgs, null) - - } catch (e: RemoteException) { - Log_OC.e(TAG, "Could not get list of shares with: ${e.message}", e) - null - } - } - val publicShares = ArrayList() - var publicShare: OCShareEntity? - if (c != null) { - if (c.moveToFirst()) { - do { - publicShare = createShareInstance(c) - publicShares.add(publicShare!!) - // } - } while (c.moveToNext()) - } - c.close() - } - - return publicShares - } - fun triggerMediaScan(path: String?) { if (path != null) { val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) From 26cfd47d4adcceb177f1ecabba58051c7462e296 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Mon, 18 Nov 2019 10:11:59 +0100 Subject: [PATCH 03/41] Keep polishing FileDataStorageManager --- .../datamodel/FileDataStorageManager.kt | 700 ++++++++---------- 1 file changed, 295 insertions(+), 405 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt index 0852e80b052..1d17c4e4bef 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt @@ -61,7 +61,6 @@ import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream -import java.lang.Long.parseLong import java.util.ArrayList import java.util.HashSet import java.util.Vector @@ -70,11 +69,25 @@ class FileDataStorageManager { var contentResolver: ContentResolver? = null private set - var contentProviderClient: ContentProviderClient? = null + private var contentProviderClient: ContentProviderClient? = null private set - var account: Account? = null + var account: Account private var mContext: Context? = null + constructor(activity: Context, account: Account, cr: ContentResolver) { + contentProviderClient = null + contentResolver = cr + this.account = account + mContext = activity + } + + constructor(activity: Context, account: Account, cp: ContentProviderClient) { + contentProviderClient = cp + contentResolver = null + this.account = account + mContext = activity + } + /** * Get a collection with all the files set by the user as available offline, from all the accounts * in the device, putting away the folders @@ -84,71 +97,67 @@ class FileDataStorageManager { * * @return List with all the files set by the user as available offline. */ - // query for any favorite file in any OC account - val availableOfflineFilesFromEveryAccount: List> - get() { - val result = ArrayList>() - - var cursorOnKeptInSync: Cursor? = null - try { - cursorOnKeptInSync = contentResolver!!.query( - CONTENT_URI, - null, - "$FILE_KEEP_IN_SYNC = ? OR $FILE_KEEP_IN_SYNC = ?", - arrayOf( - AVAILABLE_OFFLINE.value.toString(), - AVAILABLE_OFFLINE_PARENT.value.toString() - ), - null - ) - - if (cursorOnKeptInSync != null && cursorOnKeptInSync.moveToFirst()) { - var file: OCFile? - var accountName: String - do { - file = createFileInstance(cursorOnKeptInSync) - accountName = cursorOnKeptInSync.getString( - cursorOnKeptInSync.getColumnIndex(FILE_ACCOUNT_OWNER) - ) - if (!file!!.isFolder && AccountUtils.exists(accountName, mContext)) { - result.add(Pair(file, accountName)) - } - } while (cursorOnKeptInSync.moveToNext()) - } - - } catch (e: Exception) { - Log_OC.e(TAG, "Exception retrieving all the available offline files", e) + fun getAvailableOfflineFilesFromEveryAccount(): List> { + val result = ArrayList>() + var cursorOnKeptInSync: Cursor? = null + try { + cursorOnKeptInSync = performQuery( + uri = CONTENT_URI, + projection = null, + selection = "$FILE_KEEP_IN_SYNC = ? OR $FILE_KEEP_IN_SYNC = ?", + selectionArgs = arrayOf(AVAILABLE_OFFLINE.value.toString(), AVAILABLE_OFFLINE_PARENT.value.toString()), + sortOrder = null, + performWithContentProviderClient = false + ) - } finally { - cursorOnKeptInSync?.close() + if (cursorOnKeptInSync != null && cursorOnKeptInSync.moveToFirst()) { + var file: OCFile? + var accountName: String + do { + file = createFileInstance(cursorOnKeptInSync) + accountName = + cursorOnKeptInSync.getString(cursorOnKeptInSync.getColumnIndex(FILE_ACCOUNT_OWNER)) + if (!file!!.isFolder && AccountUtils.exists(accountName, mContext)) { + result.add(Pair(file, accountName)) + } + } while (cursorOnKeptInSync.moveToNext()) + } else { + Log_OC.d(TAG, "No available offline files found") } - return result + } catch (e: Exception) { + Log_OC.e(TAG, "Exception retrieving all the available offline files", e) + + } finally { + cursorOnKeptInSync?.close() } + return result + } + /** * Get a collection with all the files set by the user as available offline, from current account * putting away files whose parent is also available offline * * @return List with all the files set by current user as available offline. */ - // query for available offline files in current account and whose parent is not. val availableOfflineFilesFromCurrentAccount: Vector get() { val result = Vector() var cursorOnKeptInSync: Cursor? = null try { - cursorOnKeptInSync = contentResolver!!.query( - CONTENT_URI, - null, - "($FILE_KEEP_IN_SYNC = ? AND NOT $FILE_KEEP_IN_SYNC = ? ) AND $FILE_ACCOUNT_OWNER = ? ", - arrayOf( + cursorOnKeptInSync = performQuery( + uri = CONTENT_URI, + projection = null, + selection = "($FILE_KEEP_IN_SYNC = ? AND NOT $FILE_KEEP_IN_SYNC = ? ) AND $FILE_ACCOUNT_OWNER = ? ", + selectionArgs = arrayOf( AVAILABLE_OFFLINE.value.toString(), AVAILABLE_OFFLINE_PARENT.value.toString(), - account!!.name + account.name ), - null + sortOrder = null, + performWithContentProviderClient = false ) if (cursorOnKeptInSync != null && cursorOnKeptInSync.moveToFirst()) { @@ -157,6 +166,8 @@ class FileDataStorageManager { file = createFileInstance(cursorOnKeptInSync) result.add(file) } while (cursorOnKeptInSync.moveToNext()) + } else { + Log_OC.d(TAG, "No available offline files found") } } catch (e: Exception) { @@ -166,24 +177,9 @@ class FileDataStorageManager { cursorOnKeptInSync?.close() } - result.sort() - return result + return result.apply { sort() } } - constructor(activity: Context, account: Account, cr: ContentResolver) { - contentProviderClient = null - contentResolver = cr - this.account = account - mContext = activity - } - - constructor(activity: Context, account: Account, cp: ContentProviderClient) { - contentProviderClient = cp - contentResolver = null - this.account = account - mContext = activity - } - fun getFileByPath(path: String): OCFile? { val c = getFileCursorForValue(FILE_PATH, path) var file: OCFile? = null @@ -248,21 +244,15 @@ class FileDataStorageManager { } } - fun getFolderImages(folder: OCFile?): Vector { - val ret = Vector() - if (folder != null) { + fun getFolderImages(folder: OCFile?): Vector = + folder?.let { // TODO better implementation, filtering in the access to database instead of here - val tmp = getFolderContent(folder, false) - var current: OCFile - for (i in tmp.indices) { - current = tmp[i] - if (current.isImage) { - ret.add(current) - } + val folderImages = Vector() + for (file in getFolderContent(it, false)) { + if (file.isImage) folderImages.add(file) } - } - return ret - } + folderImages + } ?: Vector() fun saveFile(file: OCFile): Boolean { var overriden = false @@ -276,7 +266,7 @@ class FileDataStorageManager { put(FILE_PARENT, file.parentId) put(FILE_PATH, file.remotePath) if (!file.isFolder) put(FILE_STORAGE_PATH, file.storagePath) - put(FILE_ACCOUNT_OWNER, account!!.name) + put(FILE_ACCOUNT_OWNER, account.name) put(FILE_LAST_SYNC_DATE, file.lastSyncDateForProperties) put(FILE_LAST_SYNC_DATE_FOR_DATA, file.lastSyncDateForData) put(FILE_ETAG, file.etag) @@ -303,30 +293,28 @@ class FileDataStorageManager { } overriden = true - if (contentResolver != null) { - contentResolver!!.update(CONTENT_URI, cv, "$_ID=?", arrayOf(file.fileId.toString())) - } else { - try { - contentProviderClient!!.update(CONTENT_URI, cv, "$_ID=?", arrayOf(file.fileId.toString())) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}", e) - } + try { + performUpdate( + uri = CONTENT_URI, + contentValues = cv, + where = "$_ID=?", + selectionArgs = arrayOf(file.fileId.toString()) + ).let { Log_OC.d(TAG, "Rows updated: $it") } + } catch (e: Exception) { + Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}", e) } } else { // new file setInitialAvailableOfflineStatus(file, cv) - var resultUri: Uri? = null - if (contentResolver != null) { - resultUri = contentResolver!!.insert(CONTENT_URI_FILE, cv) - } else { + val resultUri: Uri? = try { - resultUri = contentProviderClient!!.insert(CONTENT_URI_FILE, cv) + performInsert(CONTENT_URI_FILE, cv) } catch (e: RemoteException) { Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}", e) + null } - } resultUri?.let { file.fileId = it.pathSegments[1].toLong() } @@ -368,7 +356,7 @@ class FileDataStorageManager { put(FILE_PARENT, folder.fileId) put(FILE_PATH, file.remotePath) if (!file.isFolder) put(FILE_STORAGE_PATH, file.storagePath) - put(FILE_ACCOUNT_OWNER, account!!.name) + put(FILE_ACCOUNT_OWNER, account.name) put(FILE_LAST_SYNC_DATE, file.lastSyncDateForProperties) put(FILE_LAST_SYNC_DATE_FOR_DATA, file.lastSyncDateForData) put(FILE_ETAG, file.etag) @@ -405,7 +393,7 @@ class FileDataStorageManager { var whereArgs: Array? for (file in filesToRemove) { if (file.parentId == folder.fileId) { - whereArgs = arrayOf(account!!.name, file.remotePath) + whereArgs = arrayOf(account.name, file.remotePath) if (file.isFolder) { operations.add( ContentProviderOperation.newDelete( @@ -413,7 +401,7 @@ class FileDataStorageManager { ).withSelection(where, whereArgs).build() ) - val localFolder = File(FileStorageUtils.getDefaultSavePathFor(account!!.name, file)) + val localFolder = File(FileStorageUtils.getDefaultSavePathFor(account.name, file)) if (localFolder.exists()) { removeLocalFolder(localFolder) } @@ -443,7 +431,7 @@ class FileDataStorageManager { put(FILE_NAME, folder.fileName) put(FILE_PARENT, folder.parentId) put(FILE_PATH, folder.remotePath) - put(FILE_ACCOUNT_OWNER, account!!.name) + put(FILE_ACCOUNT_OWNER, account.name) put(FILE_LAST_SYNC_DATE, folder.lastSyncDateForProperties) put(FILE_LAST_SYNC_DATE_FOR_DATA, folder.lastSyncDateForData) put(FILE_ETAG, folder.etag) @@ -482,7 +470,6 @@ class FileDataStorageManager { // update new id in file objects for insertions if (results != null) { - var newId: Long val filesIt = updatedFiles.iterator() var file: OCFile? for (i in results.indices) { @@ -491,12 +478,8 @@ class FileDataStorageManager { } else { null } - if (results[i].uri != null) { - newId = parseLong(results[i].uri.pathSegments[1]) - //updatedFiles.get(i).setFileId(newId); - if (file != null) { - file.fileId = newId - } + results[i].uri?.let { newId -> + file?.fileId = newId.pathSegments[1].toLong() } } } @@ -545,8 +528,13 @@ class FileDataStorageManager { cv.put(FILE_KEEP_IN_SYNC, file.availableOfflineStatus.value) var updatedCount: Int - if (contentResolver != null) { - updatedCount = contentResolver!!.update(CONTENT_URI, cv, "$_ID=?", arrayOf(file.fileId.toString())) + try { + updatedCount = performUpdate( + uri = CONTENT_URI, + contentValues = cv, + where = "$_ID=?", + selectionArgs = arrayOf(file.fileId.toString()) + ) // Update descendants if (file.isFolder && updatedCount > 0) { @@ -559,37 +547,17 @@ class FileDataStorageManager { descendantsCv.put(FILE_KEEP_IN_SYNC, NOT_AVAILABLE_OFFLINE.value) } val selectDescendants = selectionForAllDescendantsOf(file) - updatedCount += contentResolver!!.update( - CONTENT_URI, - descendantsCv, - selectDescendants.first, - selectDescendants.second + updatedCount += performUpdate( + uri = CONTENT_URI, + contentValues = descendantsCv, + where = selectDescendants.first, + selectionArgs = selectDescendants.second ) } - } else { - try { - updatedCount = - contentProviderClient!!.update(CONTENT_URI, cv, "$_ID=?", arrayOf(file.fileId.toString())) - - // If file is a folder, all children files that were available offline must be unset - if (file.isFolder && updatedCount > 0) { - val descendantsCv = ContentValues() - descendantsCv.put(FILE_KEEP_IN_SYNC, NOT_AVAILABLE_OFFLINE.value) - val selectDescendants = selectionForAllDescendantsOf(file) - updatedCount += contentProviderClient!!.update( - CONTENT_URI, - descendantsCv, - selectDescendants.first, - selectDescendants.second - ) - } - - } catch (e: RemoteException) { - Log_OC.e(TAG, "Fail updating available offline status", e) - return false - } - + } catch (e: RemoteException) { + Log_OC.e(TAG, "Fail updating available offline status", e) + return false } return updatedCount > 0 @@ -605,18 +573,14 @@ class FileDataStorageManager { if (removeDBData) { val fileUri = ContentUris.withAppendedId(CONTENT_URI_FILE, file.fileId) val where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?" - val whereArgs = arrayOf(account!!.name, file.remotePath) - var deleted = 0 - if (contentProviderClient != null) { + val whereArgs = arrayOf(account.name, file.remotePath) + val deleted = try { - deleted = contentProviderClient!!.delete(fileUri, where, whereArgs) + performDelete(fileUri, where, whereArgs) } catch (e: RemoteException) { e.printStackTrace() + 0 } - - } else { - deleted = contentResolver!!.delete(fileUri, where, whereArgs) - } success = success and (deleted > 0) } val localPath = file.storagePath @@ -656,24 +620,18 @@ class FileDataStorageManager { val folderUri = Uri.withAppendedPath(CONTENT_URI_DIR, "" + folder.fileId) // URI for recursive deletion val where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?" - val whereArgs = arrayOf(account!!.name, folder.remotePath) - var deleted = 0 - if (contentProviderClient != null) { - try { - deleted = contentProviderClient!!.delete(folderUri, where, whereArgs) - } catch (e: RemoteException) { - e.printStackTrace() - } - - } else { - deleted = contentResolver!!.delete(folderUri, where, whereArgs) + val whereArgs = arrayOf(account.name, folder.remotePath) + return try { + performDelete(url = folderUri, where = where, selectionArgs = whereArgs) > 0 + } catch (e: RemoteException) { + e.printStackTrace() + false } - return deleted > 0 } private fun removeLocalFolder(folder: OCFile): Boolean { var success = true - val localFolderPath = FileStorageUtils.getDefaultSavePathFor(account!!.name, folder) + val localFolderPath = FileStorageUtils.getDefaultSavePathFor(account.name, folder) val localFolder = File(localFolderPath) if (localFolder.exists()) { // stage 1: remove the local files already registered in the files database @@ -710,7 +668,6 @@ class FileDataStorageManager { success = if (localFile.isDirectory) { success and removeLocalFolder(localFile) } else { - val path = localFile.absolutePath success and localFile.delete() } } @@ -735,33 +692,23 @@ class FileDataStorageManager { ) /// 1. get all the descendants of the moved element in a single QUERY - var c: Cursor? = null - if (contentProviderClient != null) { + val c: Cursor? = try { - c = contentProviderClient!!.query( - CONTENT_URI, - null, - "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH LIKE ? ", - arrayOf(account!!.name, "${file.remotePath}%"), - "$FILE_PATH ASC " + performQuery( + uri = CONTENT_URI, + projection = null, + selection = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH LIKE ? ", + selectionArgs = arrayOf(account.name, "${file.remotePath}%"), + sortOrder = "$FILE_PATH ASC " ) } catch (e: RemoteException) { Log_OC.e(TAG, e.message) + null } - } else { - c = contentResolver!!.query( - CONTENT_URI, - null, - "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH LIKE ? ", - arrayOf(account!!.name, file.remotePath + "%"), - "$FILE_PATH ASC " - ) - } - val originalPathsToTriggerMediaScan = ArrayList() val newPathsToTriggerMediaScan = ArrayList() - val defaultSavePath = FileStorageUtils.getSavePath(account!!.name) + val defaultSavePath = FileStorageUtils.getSavePath(account.name) /// 2. prepare a batch of update operations to change all the descendants if (c != null) { @@ -825,14 +772,14 @@ class FileDataStorageManager { } /// 4. move in local file system - val originalLocalPath = FileStorageUtils.getDefaultSavePathFor(account!!.name, file) + val originalLocalPath = FileStorageUtils.getDefaultSavePathFor(account.name, file) val targetLocalPath = defaultSavePath + targetPath val localFile = File(originalLocalPath) var renamed = false if (localFile.exists()) { val targetFile = File(targetLocalPath) val targetFolder = targetFile.parentFile - if (!targetFolder.exists()) { + if (targetFolder != null && !targetFolder.exists()) { targetFolder.mkdirs() } renamed = localFile.renameTo(targetFile) @@ -867,13 +814,13 @@ class FileDataStorageManager { // 2. Copy in local file system var copied = false - val localPath = FileStorageUtils.getDefaultSavePathFor(account!!.name, originalFile) + val localPath = FileStorageUtils.getDefaultSavePathFor(account.name, originalFile) val localFile = File(localPath) - val defaultSavePath = FileStorageUtils.getSavePath(account!!.name) + val defaultSavePath = FileStorageUtils.getSavePath(account.name) if (localFile.exists()) { val targetFile = File(defaultSavePath + targetPath) val targetFolder = targetFile.parentFile - if (!targetFolder.exists()) { + if (targetFolder != null && !targetFolder.exists()) { targetFolder.mkdirs() } copied = copyFile(localFile, targetFile) @@ -926,7 +873,6 @@ class FileDataStorageManager { val ret = Vector() val reqUri = Uri.withAppendedPath(CONTENT_URI_DIR, parentId.toString()) - var c: Cursor? val selection: String val selectionArgs: Array @@ -943,24 +889,25 @@ class FileDataStorageManager { ) } - c = if (contentProviderClient != null) { - try { - contentProviderClient!!.query(reqUri, null, selection, selectionArgs, null) - } catch (e: RemoteException) { - Log_OC.e(TAG, e.message) - return ret - } - - } else { - contentResolver!!.query(reqUri, null, selection, selectionArgs, null) + val c: Cursor? = try { + performQuery( + uri = reqUri, + projection = null, + selection = selection, + selectionArgs = selectionArgs, + sortOrder = null + ) + } catch (e: RemoteException) { + Log_OC.e(TAG, e.message) + return ret } - if (c != null) { - if (c.moveToFirst()) { + c?.let { + if (it.moveToFirst()) { do { - val child = createFileInstance(c) + val child = createFileInstance(it) ret.add(child) - } while (c.moveToNext()) + } while (it.moveToNext()) } c.close() } @@ -996,75 +943,47 @@ class FileDataStorageManager { return avOffAncestor } - private fun createRootDir(): OCFile { - val file = OCFile(ROOT_PATH) - file.mimetype = "DIR" - file.parentId = ROOT_PARENT_ID.toLong() - saveFile(file) - return file - } + private fun createRootDir(): OCFile = + OCFile(ROOT_PATH).apply { + mimetype = mimeTypeDir + parentId = ROOT_PARENT_ID.toLong() + saveFile(this) + } private fun fileExists(cmp_key: String, value: String): Boolean { - val c: Cursor? - if (contentResolver != null) { - c = contentResolver!! - .query( - CONTENT_URI, - null, - "$cmp_key=? AND $FILE_ACCOUNT_OWNER=?", - arrayOf(value, account!!.name), - null - ) - } else { + val c: Cursor? = try { - c = contentProviderClient!!.query( - CONTENT_URI, - null, - "$cmp_key=? AND $FILE_ACCOUNT_OWNER=?", - arrayOf(value, account!!.name), - null + performQuery( + uri = CONTENT_URI, + projection = null, + selection = "$cmp_key=? AND $FILE_ACCOUNT_OWNER=?", + selectionArgs = arrayOf(value, account.name), + sortOrder = null ) } catch (e: RemoteException) { Log_OC.e(TAG, "Couldn't determine file existence, assuming non existence: ${e.message}", e) return false } - - } - var retval = false - if (c != null) { - retval = c.moveToFirst() - c.close() - } - return retval + return c?.let { + val toReturn = it.moveToFirst() + it.close() + toReturn + } ?: false } - private fun getFileCursorForValue(key: String, value: String): Cursor? { - var c: Cursor? = null - if (contentResolver != null) { - c = contentResolver!! - .query( - CONTENT_URI, - null, - "$key=? AND $FILE_ACCOUNT_OWNER=?", - arrayOf(value, account!!.name), - null - ) - } else { - c = try { - contentProviderClient!!.query( - CONTENT_URI, - null, - "$key=? AND $FILE_ACCOUNT_OWNER=?", - arrayOf(value, account!!.name), - null - ) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Could not get file details: ${e.message}", e) - null - } + private fun getFileCursorForValue(key: String, value: String): Cursor? = + try { + performQuery( + uri = CONTENT_URI, + projection = null, + selection = "$key=? AND $FILE_ACCOUNT_OWNER=?", + selectionArgs = arrayOf(value, account.name), + sortOrder = null + ) + } catch (e: RemoteException) { + Log_OC.e(TAG, "Could not get file details: ${e.message}", e) + null } - return c - } private fun createFileInstance(c: Cursor?): OCFile? = c?.let { OCFile(it.getString(it.getColumnIndex(FILE_PATH))).apply { @@ -1077,7 +996,7 @@ class FileDataStorageManager { // try to find existing file and bind it with current account; // with the current update of SynchronizeFolderOperation, this won't be // necessary anymore after a full synchronization of the account - val f = File(FileStorageUtils.getDefaultSavePathFor(account!!.name, this)) + val f = File(FileStorageUtils.getDefaultSavePathFor(account.name, this)) if (f.exists()) { storagePath = f.absolutePath lastSyncDateForData = f.lastModified() @@ -1104,6 +1023,7 @@ class FileDataStorageManager { } } + @Suppress("DEPRECATION") fun triggerMediaScan(path: String?) { if (path != null) { val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) @@ -1134,55 +1054,29 @@ class FileDataStorageManager { fun deleteFileInMediaScan(path: String) { val mimeTypeString = FileStorageUtils.getMimeTypeFromName(path) - val contentResolver = contentResolver - - if (contentResolver != null) { + try { when { mimeTypeString.startsWith(pathImage) -> // Images - contentResolver.delete( + performDelete( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - MediaStore.Images.Media.DATA + "=?", + "${MediaStore.Images.Media.DATA}=?", arrayOf(path) ) mimeTypeString.startsWith(pathAudio) -> // Audio - contentResolver.delete( + performDelete( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, "${MediaStore.Audio.Media.DATA}=?", arrayOf(path) ) mimeTypeString.startsWith(pathVideo) -> // Video - contentResolver.delete( + performDelete( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "${MediaStore.Video.Media.DATA}=?", arrayOf(path) ) } - } else { - val contentProviderClient = contentProviderClient - try { - when { - mimeTypeString.startsWith(pathImage) -> // Images - contentProviderClient!!.delete( - MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - "${MediaStore.Images.Media.DATA}=?", - arrayOf(path) - ) - mimeTypeString.startsWith(pathAudio) -> // Audio - contentProviderClient!!.delete( - MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, - "${MediaStore.Audio.Media.DATA}=?", - arrayOf(path) - ) - mimeTypeString.startsWith(pathVideo) -> // Video - contentProviderClient!!.delete( - MediaStore.Video.Media.EXTERNAL_CONTENT_URI, - "${MediaStore.Video.Media.DATA}=?", - arrayOf(path) - ) - } - } catch (e: RemoteException) { - Log_OC.e(TAG, "Exception deleting media file in MediaStore ${e.message}", e) - } + } catch (e: RemoteException) { + Log_OC.e(TAG, "Exception deleting media file in MediaStore ${e.message}", e) } } @@ -1193,26 +1087,18 @@ class FileDataStorageManager { } val cv = ContentValues() cv.put(FILE_ETAG_IN_CONFLICT, eTagInConflict) - var updated = 0 - if (contentResolver != null) { - updated = contentResolver!!.update( - CONTENT_URI_FILE, - cv, - "$_ID=?", - arrayOf(file.fileId.toString()) - ) - } else { + val updated = try { - updated = contentProviderClient!!.update( - CONTENT_URI_FILE, - cv, - "$_ID=?", - arrayOf(file.fileId.toString()) + performUpdate( + uri = CONTENT_URI_FILE, + contentValues = cv, + where = "$_ID=?", + selectionArgs = arrayOf(file.fileId.toString()) ) } catch (e: RemoteException) { Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) + 0 } - } Log_OC.d(TAG, "Number of files updated with CONFLICT: $updated") @@ -1236,25 +1122,16 @@ class FileDataStorageManager { whereBuffer.append("?") whereBuffer.append(")") - if (contentResolver != null) { - updated = contentResolver!!.update( - CONTENT_URI_FILE, - cv, - whereBuffer.toString(), - ancestorIds.toTypedArray() - ) - } else { try { - updated = contentProviderClient!!.update( - CONTENT_URI_FILE, - cv, - whereBuffer.toString(), - ancestorIds.toTypedArray() + performUpdate( + uri = CONTENT_URI_FILE, + contentValues = cv, + where = whereBuffer.toString(), + selectionArgs = ancestorIds.toTypedArray() ) } catch (e: RemoteException) { Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) } - } } // else file is ROOT folder, no parent to set in conflict } else { @@ -1273,50 +1150,33 @@ class FileDataStorageManager { FILE_CONTENT_TYPE + " != 'DIR' AND " + FILE_ACCOUNT_OWNER + " = ? AND " + FILE_PATH + " LIKE ?" - var descendantsInConflict: Cursor? = null - if (contentResolver != null) { - descendantsInConflict = contentResolver!!.query( - CONTENT_URI_FILE, - arrayOf(_ID), - whereForDescendantsInConflict, - arrayOf(account!!.name, "$parentPath%"), - null - ) - } else { + val descendantsInConflict: Cursor? = try { - descendantsInConflict = contentProviderClient!!.query( - CONTENT_URI_FILE, - arrayOf(_ID), - whereForDescendantsInConflict, - arrayOf(account!!.name, "$parentPath%"), - null + performQuery( + uri = CONTENT_URI_FILE, + projection = arrayOf(_ID), + selection = whereForDescendantsInConflict, + selectionArgs = arrayOf(account.name, "$parentPath%"), + sortOrder = null ) } catch (e: RemoteException) { Log_OC.e(TAG, "Failed querying for descendants in conflict ${e.message}", e) + null } - } if (descendantsInConflict == null || descendantsInConflict.count == 0) { Log_OC.d(TAG, "NO MORE conflicts in $parentPath") - if (contentResolver != null) { - updated = contentResolver!!.update( - CONTENT_URI_FILE, - cv, - "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?", - arrayOf(account!!.name, parentPath) - ) - } else { + try { - updated = contentProviderClient!!.update( - CONTENT_URI_FILE, - cv, - "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?", - arrayOf(account!!.name, parentPath) + performUpdate( + uri = CONTENT_URI_FILE, + contentValues = cv, + where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?", + selectionArgs = arrayOf(account.name, parentPath) ) } catch (e: RemoteException) { Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) } - } } else { Log_OC.d(TAG, "STILL ${descendantsInConflict.count} in $parentPath") @@ -1336,7 +1196,7 @@ class FileDataStorageManager { // Prepare capabilities data val cv = ContentValues().apply { - put(CAPABILITIES_ACCOUNT_NAME, account!!.name) + put(CAPABILITIES_ACCOUNT_NAME, account.name) put(CAPABILITIES_VERSION_MAYOR, capability.versionMayor) put(CAPABILITIES_VERSION_MINOR, capability.versionMinor) put(CAPABILITIES_VERSION_MICRO, capability.versionMicro) @@ -1374,48 +1234,27 @@ class FileDataStorageManager { put(CAPABILITIES_FILES_VERSIONING, capability.filesVersioning.value) } - if (capabilityExists(account!!.name)) { - if (contentResolver != null) { - contentResolver!!.update( - CONTENT_URI_CAPABILITIES, - cv, - "$CAPABILITIES_ACCOUNT_NAME=?", - arrayOf(account!!.name) + if (capabilityExists(account.name)) { + try { + performUpdate( + uri = CONTENT_URI_CAPABILITIES, + contentValues = cv, + where = "$CAPABILITIES_ACCOUNT_NAME=?", + selectionArgs = arrayOf(account.name) ) - } else { - try { - contentProviderClient!!.update( - CONTENT_URI_CAPABILITIES, - cv, - "$CAPABILITIES_ACCOUNT_NAME=?", - arrayOf(account!!.name) - ) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}") - } - + } catch (e: RemoteException) { + Log_OC.e(TAG, "Fail to insert insert file to database ${e.message}") } } else { - var resultUri: Uri? = null - if (contentResolver != null) { - resultUri = contentResolver!!.insert( - CONTENT_URI_CAPABILITIES, cv - ) - } else { + val resultUri: Uri? = try { - resultUri = contentProviderClient!!.insert( - CONTENT_URI_CAPABILITIES, cv - ) + performInsert(CONTENT_URI_CAPABILITIES, cv) } catch (e: RemoteException) { - Log_OC.e( - TAG, - "Fail to insert insert capability to database " + e.message - ) + Log_OC.e(TAG, "Fail to insert insert capability to database ${e.message}") + null } - } - if (resultUri != null) { - val new_id = parseLong(resultUri.pathSegments[1]) - capability.accountName = account!!.name + resultUri?.let { + capability.accountName = account.name } } @@ -1432,29 +1271,19 @@ class FileDataStorageManager { return exists } - private fun getCapabilityCursorForAccount(accountName: String): Cursor? { - var c: Cursor? = null - if (contentResolver != null) { - c = contentResolver!!.query( - CONTENT_URI_CAPABILITIES, null, - "$CAPABILITIES_ACCOUNT_NAME=? ", - arrayOf(accountName), - null + private fun getCapabilityCursorForAccount(accountName: String): Cursor? = + try { + performQuery( + uri = CONTENT_URI_CAPABILITIES, + projection = null, + selection = "$CAPABILITIES_ACCOUNT_NAME=? ", + selectionArgs = arrayOf(accountName), + sortOrder = null ) - } else { - try { - c = contentProviderClient!!.query( - CONTENT_URI_CAPABILITIES, null, - "$CAPABILITIES_ACCOUNT_NAME=? ", - arrayOf(accountName), - null - ) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Couldn't determine capability existence, assuming non existence: ${e.message}") - } + } catch (e: RemoteException) { + Log_OC.e(TAG, "Couldn't determine capability existence, assuming non existence: ${e.message}") + null } - return c - } fun getCapability(accountName: String): OCCapability? { val capability: OCCapability? = null @@ -1546,15 +1375,76 @@ class FileDataStorageManager { private fun selectionForAllDescendantsOf(file: OCFile): Pair> { val selection = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH LIKE ? " - val selectionArgs = arrayOf(account!!.name, "${file.remotePath}_%") // one or more characters after remote path + val selectionArgs = arrayOf(account.name, "${file.remotePath}_%") // one or more characters after remote path return Pair(selection, selectionArgs) } + private fun performQuery( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String?, + performWithContentResolver: Boolean = true, + performWithContentProviderClient: Boolean = true + ): Cursor? { + val withContentResolver = contentResolver != null && performWithContentResolver + val withContentProvider = contentProviderClient != null && performWithContentProviderClient + return when { + withContentResolver -> contentResolver?.query(uri, projection, selection, selectionArgs, sortOrder) + withContentProvider -> contentProviderClient?.query(uri, projection, selection, selectionArgs, sortOrder) + else -> null + } + } + + private fun performUpdate( + uri: Uri, + contentValues: ContentValues?, + where: String?, + selectionArgs: Array? + ): Int { + val withContentResolver = contentResolver != null + val withContentProvider = contentProviderClient != null + return when { + withContentResolver -> contentResolver?.update(uri, contentValues, where, selectionArgs) ?: 0 + withContentProvider -> contentProviderClient?.update(uri, contentValues, where, selectionArgs) ?: 0 + else -> 0 + } + } + + private fun performInsert( + url: Uri, + contentValues: ContentValues? + ): Uri? { + val withContentResolver = contentResolver != null + val withContentProvider = contentProviderClient != null + return when { + withContentResolver -> contentResolver?.insert(url, contentValues) + withContentProvider -> contentProviderClient?.insert(url, contentValues) + else -> null + } + } + + private fun performDelete( + url: Uri, + where: String?, + selectionArgs: Array? + ): Int { + val withContentResolver = contentResolver != null + val withContentProvider = contentProviderClient != null + return when { + withContentResolver -> contentResolver?.delete(url, where, selectionArgs) ?: 0 + withContentProvider -> contentProviderClient?.delete(url, where, selectionArgs) ?: 0 + else -> 0 + } + } + companion object { private val TAG = FileDataStorageManager::class.java.simpleName const val ROOT_PARENT_ID = 0 private const val pathAudio = "audio/" private const val pathVideo = "video/" private const val pathImage = "image/" + private const val mimeTypeDir = "DIR" } } From b94ac18b333392e451d3a8b03a24d482d244169f Mon Sep 17 00:00:00 2001 From: davigonz Date: Mon, 18 Nov 2019 10:51:16 +0100 Subject: [PATCH 04/41] Data module: unit tests --- owncloud-android-library | 2 +- .../dependecyinjection/CommonModule.kt | 2 +- .../OCRemoteCapabilitiesDataSource.kt | 2 +- .../mapper/RemoteCapabilityMapper.kt | 4 +- .../android/data/utils/DataTestUtil.kt | 227 +++++--- .../android/data/NetworkBoundResourceTest.kt | 172 ------ .../OCCapabilityRepositoryTest.kt | 264 --------- .../OCLocalCapabilitiesDataSourceTest.kt | 14 +- .../OCRemoteCapabilitiesDataSourceTest.kt | 42 +- .../RemoteCapabilitiesDataSourceTest.kt | 31 -- .../mapper/OCCapabilityMapperTest.kt | 68 +++ .../mapper/OCRemoteCapabilityMapperTest.kt | 44 ++ .../capabilities/db/OCCapabilityEntityTest.kt | 234 ++++++++ .../repository/OCCapabilityRepositoryTest.kt | 129 +++++ .../repository/OCShareeRepositoryTest.kt | 64 +++ .../OCLocalSharesDataSourceTest.kt | 36 +- .../OCRemoteSharesDataSourceTest.kt | 278 +++++----- .../mapper/OCRemoteShareMapperTest.kt | 45 ++ .../datasources/mapper/OCShareMapperTest.kt | 79 +++ .../data/shares/db/OCShareEntityTest.kt | 169 ++++++ .../repository/OCShareRepositoryTest.kt | 517 ++++++++++++++++++ 21 files changed, 1686 insertions(+), 737 deletions(-) rename owncloudData/src/main/java/com/owncloud/android/data/{sharing/shares => capabilities}/datasources/mapper/RemoteCapabilityMapper.kt (97%) delete mode 100644 owncloudData/src/test/java/com/owncloud/android/data/NetworkBoundResourceTest.kt delete mode 100644 owncloudData/src/test/java/com/owncloud/android/data/capabilities/OCCapabilityRepositoryTest.kt delete mode 100644 owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/RemoteCapabilitiesDataSourceTest.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntityTest.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/data/sharees/repository/OCShareeRepositoryTest.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/data/shares/db/OCShareEntityTest.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt diff --git a/owncloud-android-library b/owncloud-android-library index 7bd599853cb..e1530716547 160000 --- a/owncloud-android-library +++ b/owncloud-android-library @@ -1 +1 @@ -Subproject commit 7bd599853cb80193626a56a869c9b5f2677f5bc7 +Subproject commit e1530716547b1ed3f4b8e1d72f8f1a832e925ea5 diff --git a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/CommonModule.kt b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/CommonModule.kt index 6058924b9ea..cb611cee2a5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/CommonModule.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/CommonModule.kt @@ -22,7 +22,7 @@ package com.owncloud.android.dependecyinjection import com.owncloud.android.data.capabilities.datasources.mapper.OCCapabilityMapper import com.owncloud.android.data.sharing.shares.datasources.mapper.OCShareMapper import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteShareMapper -import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteCapabilityMapper +import com.owncloud.android.data.capabilities.datasources.mapper.RemoteCapabilityMapper import org.koin.dsl.module val commonModule = module { diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/implementation/OCRemoteCapabilitiesDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/implementation/OCRemoteCapabilitiesDataSource.kt index d3f44936725..41534890fc8 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/implementation/OCRemoteCapabilitiesDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/implementation/OCRemoteCapabilitiesDataSource.kt @@ -21,7 +21,7 @@ package com.owncloud.android.data.capabilities.datasources.implementation import com.owncloud.android.data.capabilities.datasources.RemoteCapabilitiesDataSource import com.owncloud.android.data.executeRemoteOperation -import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteCapabilityMapper +import com.owncloud.android.data.capabilities.datasources.mapper.RemoteCapabilityMapper import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.lib.resources.status.CapabilityService diff --git a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/mapper/RemoteCapabilityMapper.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt similarity index 97% rename from owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/mapper/RemoteCapabilityMapper.kt rename to owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt index b82f93fcb19..ecbb0fc383b 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/mapper/RemoteCapabilityMapper.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.data.sharing.shares.datasources.mapper +package com.owncloud.android.data.capabilities.datasources.mapper import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability @@ -36,7 +36,7 @@ class RemoteCapabilityMapper : RemoteMapper { versionEdition = remote.versionEdition, corePollInterval = remote.corePollinterval, filesSharingApiEnabled = CapabilityBooleanType.fromValue(remote.filesSharingApiEnabled.value)!!, - filesSharingSearchMinLength = remote.filesSharingSearchMinLength.value, + filesSharingSearchMinLength = remote.filesSharingSearchMinLength, filesSharingPublicEnabled = CapabilityBooleanType.fromValue(remote.filesSharingPublicEnabled.value)!!, filesSharingPublicPasswordEnforced = CapabilityBooleanType.fromValue(remote.filesSharingPublicPasswordEnforced.value)!!, diff --git a/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt b/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt index 97d636f6f54..73c8a4d1481 100644 --- a/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt +++ b/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt @@ -2,6 +2,7 @@ * ownCloud Android client application * * @author David González Verdugo + * @author Abel García de Prada * Copyright (C) 2019 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify @@ -28,6 +29,8 @@ import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation import com.owncloud.android.lib.resources.shares.RemoteShare +import com.owncloud.android.lib.resources.shares.ShareType as RemoteShareType +import com.owncloud.android.lib.resources.status.CapabilityBooleanType as RemoteCapabilityBooleanType import com.owncloud.android.lib.resources.status.RemoteCapability import io.mockk.every import io.mockk.mockk @@ -37,7 +40,46 @@ object DataTestUtil { /** * Shares */ - private fun createShare( + val DUMMY_SHARE = OCShare( + fileSource = 7, + itemSource = 7, + shareType = ShareType.USER, // Public share by default + shareWith = "", + path = "/Photos/image.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "AnyToken", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = "", + shareLink = "" + ) + + val DUMMY_REMOTE_SHARE = + RemoteShare().apply { + fileSource = 7 + itemSource = 7 + shareType = RemoteShareType.USER + shareWith = "" + path = "/Photos/image.jpg" + permissions = 1 + sharedDate = 1542628397 + expirationDate = 0 + token = "AnyToken" + sharedWithDisplayName = "" + isFolder = false + userId = -1 + id = 1 + name = "" + shareLink = "" + } + + fun createShare( fileSource: Long = 7, itemSource: Long = 7, shareType: Int, // Public share by default @@ -76,7 +118,7 @@ object DataTestUtil { shareLink ) - private fun createShareEntity( + fun createShareEntity( fileSource: Long = 7, itemSource: Long = 7, shareType: Int, // Public share by default @@ -117,11 +159,11 @@ object DataTestUtil { fun createPrivateShare( remoteId: Long = 1, shareType: Int = 0, - shareWith: String, - path: String, + shareWith: String = "whoever", + path: String = "/Photos/image.jpg", permissions: Int = -1, - isFolder: Boolean, - sharedWithDisplayName: String, + isFolder: Boolean = false, + sharedWithDisplayName: String = "whatever", accountOwner: String = "admin@server" ) = createShare( remoteId = remoteId, @@ -156,14 +198,14 @@ object DataTestUtil { fun createPublicShare( shareWith: String = "", - path: String, + path: String = "/Photos/image.jpg", expirationDate: Long = 1000, - isFolder: Boolean, + isFolder: Boolean = false, permissions: Int = 1, remoteId: Long = 1, accountOwner: String = "admin@server", - name: String, - shareLink: String + name: String = "Image link", + shareLink: String = "link" ) = createShare( shareWith = shareWith, shareType = 3, @@ -216,26 +258,22 @@ object DataTestUtil { remoteId: Long = 1, name: String = "", shareLink: String = "" - ): RemoteShare { - val remoteShare = RemoteShare(); - - remoteShare.fileSource = fileSource - remoteShare.itemSource = itemSource - remoteShare.shareType = com.owncloud.android.lib.resources.shares.ShareType.fromValue(shareType) - remoteShare.shareWith = shareWith - remoteShare.path = path - remoteShare.permissions = permissions - remoteShare.sharedDate = sharedDate - remoteShare.expirationDate = expirationDate - remoteShare.token = token - remoteShare.sharedWithDisplayName = sharedWithDisplayName - remoteShare.isFolder = isFolder - remoteShare.userId = userId - remoteShare.id = remoteId - remoteShare.name = name - remoteShare.shareLink = shareLink - - return remoteShare + ): RemoteShare = RemoteShare().also { + it.fileSource = fileSource + it.itemSource = itemSource + it.shareType = RemoteShareType.fromValue(shareType) + it.shareWith = shareWith + it.path = path + it.permissions = permissions + it.sharedDate = sharedDate + it.expirationDate = expirationDate + it.token = token + it.sharedWithDisplayName = sharedWithDisplayName + it.isFolder = isFolder + it.userId = userId + it.id = remoteId + it.name = name + it.shareLink = shareLink } /** @@ -264,6 +302,70 @@ object DataTestUtil { /** * Capability */ + val DUMMY_CAPABILITY = + OCCapability( + accountName = "user@server", + versionMayor = 2, + versionMinor = 1, + versionMicro = 0, + versionString = "1.0.0", + versionEdition = "1.0.0", + corePollInterval = 0, + filesSharingApiEnabled = CapabilityBooleanType.TRUE, + filesSharingSearchMinLength = 3, + filesSharingPublicEnabled = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicExpireDateEnabled = CapabilityBooleanType.FALSE, + filesSharingPublicExpireDateDays = 0, + filesSharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE, + filesSharingPublicSendMail = CapabilityBooleanType.FALSE, + filesSharingPublicUpload = CapabilityBooleanType.FALSE, + filesSharingPublicMultiple = CapabilityBooleanType.FALSE, + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.FALSE, + filesSharingUserSendMail = CapabilityBooleanType.FALSE, + filesSharingResharing = CapabilityBooleanType.FALSE, + filesSharingFederationOutgoing = CapabilityBooleanType.FALSE, + filesSharingFederationIncoming = CapabilityBooleanType.FALSE, + filesBigFileChunking = CapabilityBooleanType.FALSE, + filesUndelete = CapabilityBooleanType.FALSE, + filesVersioning = CapabilityBooleanType.FALSE + ) + + val DUMMY_REMOTE_CAPABILITY = + RemoteCapability().apply { + accountName = "user@server" + versionMayor = 2 + versionMinor = 1 + versionMicro = 0 + versionString = "1.0.0" + versionEdition = "1.0.0" + corePollinterval = 0 + filesSharingApiEnabled = RemoteCapabilityBooleanType.TRUE + filesSharingSearchMinLength = 3 + filesSharingPublicEnabled = RemoteCapabilityBooleanType.TRUE + filesSharingPublicPasswordEnforced = RemoteCapabilityBooleanType.FALSE + filesSharingPublicPasswordEnforcedReadOnly = RemoteCapabilityBooleanType.FALSE + filesSharingPublicPasswordEnforcedReadWrite = RemoteCapabilityBooleanType.FALSE + filesSharingPublicPasswordEnforcedUploadOnly = RemoteCapabilityBooleanType.FALSE + filesSharingPublicExpireDateEnabled = RemoteCapabilityBooleanType.FALSE + filesSharingPublicExpireDateDays = 0 + filesSharingPublicExpireDateEnforced = RemoteCapabilityBooleanType.FALSE + filesSharingPublicSendMail = RemoteCapabilityBooleanType.FALSE + filesSharingPublicUpload = RemoteCapabilityBooleanType.FALSE + filesSharingPublicMultiple = RemoteCapabilityBooleanType.FALSE + filesSharingPublicSupportsUploadOnly = RemoteCapabilityBooleanType.FALSE + filesSharingUserSendMail = RemoteCapabilityBooleanType.FALSE + filesSharingResharing = RemoteCapabilityBooleanType.FALSE + filesSharingFederationOutgoing = RemoteCapabilityBooleanType.FALSE + filesSharingFederationIncoming = RemoteCapabilityBooleanType.FALSE + filesBigFileChunking = RemoteCapabilityBooleanType.FALSE + filesUndelete = RemoteCapabilityBooleanType.FALSE + filesVersioning = RemoteCapabilityBooleanType.FALSE + } + fun createCapability( accountName: String = "user@server", versionMayor: Int = 2, @@ -273,7 +375,7 @@ object DataTestUtil { versionEdition: String = "1.0.0", corePollinterval: Int = 0, sharingApiEnabled: CapabilityBooleanType = CapabilityBooleanType.TRUE, - sharingSearchMinLength: Int = 4, + sharingSearchMinLength: Int = 0, sharingPublicEnabled: CapabilityBooleanType = CapabilityBooleanType.TRUE, sharingPublicPasswordEnforced: CapabilityBooleanType = CapabilityBooleanType.FALSE, sharingPublicPasswordEnforcedReadOnly: CapabilityBooleanType = CapabilityBooleanType.FALSE, @@ -334,8 +436,8 @@ object DataTestUtil { versionEdition: String = "1.0.0", corePollinterval: Int = 0, sharingApiEnabled: Int = 1, + sharingSearchMinLength: Int = 0, sharingPublicEnabled: Int = 1, - filesSharingSearchMinLength: Int = 4, sharingPublicPasswordEnforced: Int = 0, sharingPublicPasswordEnforcedReadOnly: Int = 0, sharingPublicPasswordEnforcedReadWrite: Int = 0, @@ -363,7 +465,7 @@ object DataTestUtil { versionEdition, corePollinterval, sharingApiEnabled, - filesSharingSearchMinLength, + sharingSearchMinLength, sharingPublicEnabled, sharingPublicPasswordEnforced, sharingPublicPasswordEnforcedReadOnly, @@ -421,50 +523,29 @@ object DataTestUtil { this.versionString = versionString this.versionEdition = versionEdition this.corePollinterval = corePollinterval - filesSharingApiEnabled = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingApiEnabled)!! - filesSharingPublicEnabled = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingPublicEnabled)!! - filesSharingPublicPasswordEnforced = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingPublicPasswordEnforced)!! + filesSharingApiEnabled = RemoteCapabilityBooleanType.fromValue(sharingApiEnabled)!! + filesSharingPublicEnabled = RemoteCapabilityBooleanType.fromValue(sharingPublicEnabled)!! + filesSharingPublicPasswordEnforced = RemoteCapabilityBooleanType.fromValue(sharingPublicPasswordEnforced)!! filesSharingPublicPasswordEnforcedReadOnly = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue( - sharingPublicPasswordEnforcedReadOnly - )!! + RemoteCapabilityBooleanType.fromValue(sharingPublicPasswordEnforcedReadOnly)!! filesSharingPublicPasswordEnforcedReadWrite = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue( - sharingPublicPasswordEnforcedReadWrite - )!! + RemoteCapabilityBooleanType.fromValue(sharingPublicPasswordEnforcedReadWrite)!! filesSharingPublicPasswordEnforcedUploadOnly = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue( - sharingPublicPasswordEnforcedUploadOnly - )!! - filesSharingPublicExpireDateEnabled = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingPublicExpireDateEnabled)!! + RemoteCapabilityBooleanType.fromValue(sharingPublicPasswordEnforcedUploadOnly)!! + filesSharingPublicExpireDateEnabled = RemoteCapabilityBooleanType.fromValue(sharingPublicExpireDateEnabled)!! filesSharingPublicExpireDateDays = sharingPublicExpireDateDays - filesSharingPublicExpireDateEnforced = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingPublicExpireDateEnforced)!! - filesSharingPublicSendMail = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingPublicSendMail)!! - filesSharingPublicUpload = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingPublicUpload)!! - filesSharingPublicMultiple = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingPublicMultiple)!! - filesSharingPublicSupportsUploadOnly = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingPublicSupportsUploadOnly)!! - filesSharingUserSendMail = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingUserSendMail)!! - filesSharingResharing = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingResharing)!! - filesSharingFederationOutgoing = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingFederationOutgoing)!! - filesSharingFederationIncoming = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(sharingFederationIncoming)!! - this.filesBigFileChunking = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(filesBigFileChunking)!! - this.filesUndelete = com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(filesUndelete)!! - this.filesVersioning = - com.owncloud.android.lib.resources.status.CapabilityBooleanType.fromValue(filesVersioning)!! + filesSharingPublicExpireDateEnforced = RemoteCapabilityBooleanType.fromValue(sharingPublicExpireDateEnforced)!! + filesSharingPublicSendMail = RemoteCapabilityBooleanType.fromValue(sharingPublicSendMail)!! + filesSharingPublicUpload = RemoteCapabilityBooleanType.fromValue(sharingPublicUpload)!! + filesSharingPublicMultiple = RemoteCapabilityBooleanType.fromValue(sharingPublicMultiple)!! + filesSharingPublicSupportsUploadOnly = RemoteCapabilityBooleanType.fromValue(sharingPublicSupportsUploadOnly)!! + filesSharingUserSendMail = RemoteCapabilityBooleanType.fromValue(sharingUserSendMail)!! + filesSharingResharing = RemoteCapabilityBooleanType.fromValue(sharingResharing)!! + filesSharingFederationOutgoing = RemoteCapabilityBooleanType.fromValue(sharingFederationOutgoing)!! + filesSharingFederationIncoming = RemoteCapabilityBooleanType.fromValue(sharingFederationIncoming)!! + this.filesBigFileChunking = RemoteCapabilityBooleanType.fromValue(filesBigFileChunking)!! + this.filesUndelete = RemoteCapabilityBooleanType.fromValue(filesUndelete)!! + this.filesVersioning = RemoteCapabilityBooleanType.fromValue(filesVersioning)!! } fun createRemoteOperationResultMock( diff --git a/owncloudData/src/test/java/com/owncloud/android/data/NetworkBoundResourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/NetworkBoundResourceTest.kt deleted file mode 100644 index 648331da4e8..00000000000 --- a/owncloudData/src/test/java/com/owncloud/android/data/NetworkBoundResourceTest.kt +++ /dev/null @@ -1,172 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.data - -import androidx.arch.core.executor.testing.InstantTaskExecutorRule -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData -import androidx.lifecycle.Observer -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.data.utils.DataTestUtil -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.RemoteShare -import com.owncloud.android.lib.resources.shares.ShareParserResult -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.utils.InstantExecutors -import io.mockk.every -import io.mockk.mockk -import io.mockk.verify -import org.hamcrest.CoreMatchers.`is` -import org.hamcrest.MatcherAssert.assertThat -import org.junit.Rule -import org.junit.Test -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicReference - -class NetworkBoundResourceTest { - private val dbData = MutableLiveData>() - - @Rule - @JvmField - val instantExecutorRule = InstantTaskExecutorRule() - - @Test - fun basicFromNetwork() { - val saved = AtomicReference>() - - val fetchedDbValue = listOf( - DataTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = true, - name = "Photos 1 link", - shareLink = "http://server:port/s/1" - ) - ) - - val networkResult = arrayListOf( - DataTestUtil.createRemoteShare( - shareType = ShareType.PUBLIC_LINK.value, - path = "/Photos/image.jpg", - isFolder = true, - name = "Photos 1 link", - shareLink = "http://server:port/s/1" - ) - ) - - val networkBoundResource = - object : NetworkBoundResource, ShareParserResult>(InstantExecutors()) { - override fun saveCallResult(item: ShareParserResult) { - saved.set(item.shares.map { remoteShare -> - OCShareEntity.fromRemoteShare(remoteShare).also { it.accountOwner = "admin@server" } - }) - dbData.value = fetchedDbValue - } - - override fun shouldFetchFromNetwork(data: List?) = true - - override fun loadFromDb(): LiveData> = dbData - - override fun createCall(): RemoteOperationResult { - val remoteOperationResult = mockk>(relaxed = true) - every { remoteOperationResult.data } returns ShareParserResult(networkResult) - every { remoteOperationResult.isSuccess } returns true - return remoteOperationResult - } - } - - val observer = mockk>>>(relaxed = true) - networkBoundResource.asLiveData().observeForever(observer) - - dbData.postValue(null) - - assertThat(saved.get(), `is`(networkResult.map { remoteShare -> - OCShareEntity.fromRemoteShare(remoteShare).also { it.accountOwner = "admin@server" } - })) - - verify { observer.onChanged(DataResult.success(fetchedDbValue)) } - } - - @Test - fun failureFromNetwork() { - val saved = AtomicBoolean(false) - - val fetchedDbValue = listOf( - DataTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = true, - name = "Photos 1 link", - shareLink = "http://server:port/s/1" - ) - ) - - val networkResult: ArrayList = arrayListOf() - - val networkBoundResource = - object : NetworkBoundResource, ShareParserResult>(InstantExecutors()) { - override fun saveCallResult(item: ShareParserResult) { - saved.set(true) - } - - override fun shouldFetchFromNetwork(data: List?) = true - - override fun loadFromDb(): LiveData> = dbData.apply { value = fetchedDbValue } - - override fun createCall(): RemoteOperationResult { - val remoteOperationResult = mockk>(relaxed = true) - - every { - remoteOperationResult.isSuccess - } returns false - - every { - remoteOperationResult.code - } returns RemoteOperationResult.ResultCode.UNAUTHORIZED - - every { - remoteOperationResult.data - } returns ShareParserResult(networkResult) - - every { - remoteOperationResult.httpPhrase - } returns null - - every { - remoteOperationResult.exception - } returns null - - return remoteOperationResult - } - } - - val observer = mockk>>>(relaxed = true) - networkBoundResource.asLiveData().observeForever(observer) - - assertThat(saved.get(), `is`(false)) - - verify { - observer.onChanged( - DataResult.error( - RemoteOperationResult.ResultCode.UNAUTHORIZED, - data = dbData.value - ) - ) - } - } -} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/OCCapabilityRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/OCCapabilityRepositoryTest.kt deleted file mode 100644 index 39c4bcf732f..00000000000 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/OCCapabilityRepositoryTest.kt +++ /dev/null @@ -1,264 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.data.capabilities - -import androidx.arch.core.executor.testing.InstantTaskExecutorRule -import com.owncloud.android.data.capabilities.datasources.LocalCapabilitiesDataSource -import com.owncloud.android.data.utils.DataTestUtil -import com.owncloud.android.data.capabilities.datasources.RemoteCapabilitiesDataSourceTest -import com.owncloud.android.data.capabilities.repository.OCCapabilityRepository -import io.mockk.every -import io.mockk.mockk -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.junit.runners.JUnit4 - -@RunWith(JUnit4::class) -class OCCapabilityRepositoryTest { - @Rule - @JvmField - val instantExecutorRule = InstantTaskExecutorRule() - - private lateinit var ocCapabilityRepository: OCCapabilityRepository - private val localCapabilitiesDataSource = mockk(relaxed = true) - -// @Test -// fun loadCapabilityFromNetwork() { -// val dbData = MutableLiveData() -// val defaultAccountName = "admin@server" -// -// every { -// localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData( -// defaultAccountName -// ) -// } returns dbData -// -// val remoteCapability = DomainTestUtil.createRemoteCapability(defaultAccountName) -// val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock(remoteCapability, true) -// val remoteCapabilitiesDataSource = -// RemoteCapabilitiesDataSourceTest(remoteOperationResult) -// -// ocCapabilityRepository = -// OCCapabilityRepository.create( -// InstantExecutors(), localCapabilitiesDataSource, remoteCapabilitiesDataSource -// ) -// -// val data = ocCapabilityRepository.refreshCapabilitiesForAccount(defaultAccountName) -// -// val observer = mockk>>(relaxed = true) -// data.observeForever(observer) -// -// dbData.postValue(null) -// -// // Get capabilities from database to observe them, is called twice (one showing current db capabilities while -// // getting capabilities from server and another one with db capabilities already updated with server ones) -// verify(exactly = 2) { -// localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(defaultAccountName) -// } -// -// // Retrieving capabilities from server... -// -// // Capabilities are always retrieved from server and inserted in database if not empty list -// verify { -// localCapabilitiesDataSource.insert( -// listOf(OCCapabilityEntity.fromRemoteCapability(remoteCapability.apply { -// accountName = defaultAccountName -// })) -// ) -// } -// -// // Observe changes in database livedata when there's a new capability -// val newCapability = DomainTestUtil.createCapability("user@server") -// -// dbData.postValue( -// newCapability -// ) -// -// verify { observer.onChanged(DataResult.success(newCapability)) } -// } - - @Test - fun fetchCapabilityFromNetwork() { - val defaultAccountName = "admin@server" - - val capability = DataTestUtil.createCapability(defaultAccountName) - val remoteCapabilitiesDataSource = RemoteCapabilitiesDataSourceTest(capability) - - ocCapabilityRepository = OCCapabilityRepository( - localCapabilitiesDataSource, - remoteCapabilitiesDataSource - ) - -// every { -// remoteCapabilitiesDataSource.getCapabilities(defaultAccountName) -// } returns capability - - every { - localCapabilitiesDataSource.insert( - listOf(capability) - ) - } returns Unit - -// ocCapabilityRepository.refreshCapabilitiesForAccount(defaultAccountName) -// -// verify { -// remoteCapabilitiesDataSource.getCapabilities(defaultAccountName) -// } - - // Capabilities are always retrieved from server and inserted in database if not empty list -// verify { -// localCapabilitiesDataSource.insert(listOf(capability)) -// } - -// val observer = mockk>>(relaxed = true) -// data.observeForever(observer) -// -// dbData.postValue(null) -// -// // Get capabilities from database to observe them, is called twice (one showing current db capabilities while -// // getting capabilities from server and another one with db capabilities already updated with server ones) -// verify(exactly = 2) { -// localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(defaultAccountName) -// } -// -// // Retrieving capabilities from server... -// -// // Capabilities are always retrieved from server and inserted in database if not empty list -// verify { -// localCapabilitiesDataSource.insert( -// listOf(OCCapabilityEntity.fromRemoteCapability(capability.apply { -// accountName = defaultAccountName -// })) -// ) -// } -// -// // Observe changes in database livedata when there's a new capability -// val newCapability = DomainTestUtil.createCapability("user@server") -// -// dbData.postValue( -// newCapability -// ) -// -// verify { observer.onChanged(DataResult.success(newCapability)) } - } - -// @Test -// fun loadEmptyCapabilityForAccountFromNetwork() { -// val dbData = MutableLiveData() -// val defaultAccountName = "user@server" -// -// every { -// localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData( -// defaultAccountName -// ) -// } returns dbData -// -// val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock(RemoteCapability(), true) -// -// val remoteCapabilitiesDataSource = -// RemoteCapabilitiesDataSourceTest(remoteOperationResult) -// -// ocCapabilityRepository = -// OCCapabilityRepository.create( -// InstantExecutors(), -// localCapabilitiesDataSource, -// remoteCapabilitiesDataSource -// ) -// -// val data = ocCapabilityRepository.refreshCapabilitiesForAccount( -// defaultAccountName -// ) -// -// val observer = mockk>>(relaxed = true) -// data.observeForever(observer) -// -// dbData.postValue(null) -// -// // Get capabilities from database to observe them, is called twice (one showing current db capabilities while -// // getting capabilities from server and another one with db capabilities already updated with server ones) -// verify(exactly = 2) { -// localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(defaultAccountName) -// } -// -// // Retrieving capabilities from server... -// -// // Observe changes in database livedata when the list of capabilities is empty -// dbData.postValue(null) -// -// verify { observer.onChanged(DataResult.success(null)) } -// } - -// @Test -// fun loadCapabilitiesForAccountFromNetworkWithError() { -// val dbData = MutableLiveData() -// val defaultAccountName = "cfo@server" -// -// dbData.value = null // DB does not include capabilities yet -// -// every { -// localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(defaultAccountName) -// } returns dbData -// -// val exception = Exception("Error when retrieving capabilities") -// -// val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock( -// RemoteCapability(), -// false, -// resultCode = RemoteOperationResult.ResultCode.FORBIDDEN, -// exception = exception -// ) -// -// val remoteCapabilitiesDataSourceTest = -// RemoteCapabilitiesDataSourceTest(remoteOperationResult) -// -// ocCapabilityRepository = -// OCCapabilityRepository.create( -// InstantExecutors(), -// localCapabilitiesDataSource, -// remoteCapabilitiesDataSourceTest -// ) -// -// val data = ocCapabilityRepository.refreshCapabilitiesForAccount( -// defaultAccountName -// ) -// -// // Get capabilities from database to observe them -// verify { -// localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData( -// defaultAccountName -// ) -// } -// -// // Retrieving capabilities from server... -// -// // Observe changes in database livedata when there's an error from server -// val observer = mockk>>(relaxed = true) -// data.observeForever(observer) -// -// verify { -// observer.onChanged( -// DataResult.error( -// RemoteOperationResult.ResultCode.FORBIDDEN, dbData.value, exception = exception -// ) -// ) -// } -// } -} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt index d53ef1e6dcc..496241948e6 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt @@ -83,7 +83,7 @@ class OCLocalCapabilitiesDataSourceTest { } @Test - fun readLocalCapabilityAsLiveData() { + fun readLocalCapability() { val capability = getValue( ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData( "user@server1" @@ -95,18 +95,6 @@ class OCLocalCapabilitiesDataSourceTest { assertEquals(3, capability?.versionMicro) } - @Test - fun readLocalCapability() { - val capability = - ocLocalCapabilitiesDataSource.getCapabilityForAccount( - "user@server2" - ) - assertEquals("user@server2", capability?.accountName) - assertEquals(2, capability?.versionMayor) - assertEquals(1, capability?.versionMinor) - assertEquals(0, capability?.versionMicro) - } - @Test fun insertCapabilityAndRead() { ocLocalCapabilitiesDataSource.insert( diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt index aab564f1810..9a28392db7e 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt @@ -20,33 +20,40 @@ package com.owncloud.android.data.capabilities.datasources +import com.owncloud.android.data.capabilities.datasources.implementation.OCRemoteCapabilitiesDataSource +import com.owncloud.android.data.capabilities.network.OCCapabilityService +import com.owncloud.android.data.capabilities.datasources.mapper.RemoteCapabilityMapper import com.owncloud.android.data.utils.DataTestUtil -import com.owncloud.android.lib.common.OwnCloudClient -import com.owncloud.android.lib.resources.status.GetRemoteCapabilitiesOperation import io.mockk.every -import io.mockk.mockkClass -import junit.framework.Assert.assertEquals +import io.mockk.mockk import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat +import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class OCRemoteCapabilitiesDataSourceTest { private lateinit var ocRemoteCapabilitiesDataSource: OCRemoteCapabilitiesDataSource - private val ownCloudClient = mockkClass(OwnCloudClient::class) + + private val ocCapabilityService: OCCapabilityService = mockk() + private val remoteCapabilityMapper = + RemoteCapabilityMapper() @Before fun init() { ocRemoteCapabilitiesDataSource = - OCRemoteCapabilitiesDataSource(ownCloudClient) + OCRemoteCapabilitiesDataSource( + ocCapabilityService, + remoteCapabilityMapper + ) } @Test fun readRemoteCapabilities() { - val getRemoteCapabilitiesOperation = mockkClass(GetRemoteCapabilitiesOperation::class) + val accountName = "ceo@server" val remoteCapability = DataTestUtil.createRemoteCapability( - "ceo@server", 15, 14, 13 + accountName, 15, 14, 13 ) val getRemoteCapabilitiesOperationResult = DataTestUtil.createRemoteOperationResultMock( @@ -55,22 +62,17 @@ class OCRemoteCapabilitiesDataSourceTest { ) every { - getRemoteCapabilitiesOperation.execute(ownCloudClient) + ocCapabilityService.getCapabilities() } returns getRemoteCapabilitiesOperationResult // Get capability from remote datasource - val remoteOperationResult = ocRemoteCapabilitiesDataSource.getCapabilities( - getRemoteCapabilitiesOperation - ) - - assertThat(remoteOperationResult, notNullValue()) - assertThat(remoteOperationResult.data, notNullValue()) + val capabilities = ocRemoteCapabilitiesDataSource.getCapabilities(accountName) - val capability = remoteOperationResult.data + assertThat(capabilities, notNullValue()) - assertEquals("ceo@server", capability.accountName) - assertEquals(15, capability.versionMayor) - assertEquals(14, capability.versionMinor) - assertEquals(13, capability.versionMicro) + assertEquals("ceo@server", capabilities.accountName) + assertEquals(15, capabilities.versionMayor) + assertEquals(14, capabilities.versionMinor) + assertEquals(13, capabilities.versionMicro) } } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/RemoteCapabilitiesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/RemoteCapabilitiesDataSourceTest.kt deleted file mode 100644 index efcec5d666e..00000000000 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/RemoteCapabilitiesDataSourceTest.kt +++ /dev/null @@ -1,31 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.data.capabilities.datasources - -import com.owncloud.android.domain.capabilities.model.OCCapability - -class RemoteCapabilitiesDataSourceTest(private val capability: OCCapability) : RemoteCapabilitiesDataSource { - - override fun getCapabilities( - accountName: String - ): OCCapability { - return capability - } -} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt new file mode 100644 index 00000000000..060e256ed69 --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt @@ -0,0 +1,68 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.data.capabilities.datasources.mapper + +import com.owncloud.android.data.utils.DataTestUtil.createCapability +import com.owncloud.android.data.utils.DataTestUtil.createCapabilityEntity +import org.junit.Assert +import org.junit.Test + +class OCCapabilityMapperTest { + + private val ocCapabilityMapper = OCCapabilityMapper() + + private val ocCapability = createCapability() + private val ocCapabilityEntity = createCapabilityEntity() + + @Test + fun checkToModelNull() { + Assert.assertNull(ocCapabilityMapper.toModel(null)) + } + + @Test + fun checkToModelNotNull() { + Assert.assertNotNull(ocCapabilityEntity) + + val model = ocCapabilityMapper.toModel(ocCapabilityEntity) + Assert.assertNotNull(model) + Assert.assertEquals(ocCapability, model) + + val mappedEntity = ocCapabilityMapper.toEntity(model) + Assert.assertNotNull(mappedEntity) + + Assert.assertEquals(ocCapabilityEntity, mappedEntity) + } + + @Test + fun checkToEntityNull() { + Assert.assertNull(ocCapabilityMapper.toEntity(null)) + } + + @Test + fun checkToEntityNotNull() { + val entity = ocCapabilityMapper.toEntity(ocCapability) + Assert.assertNotNull(entity) + + val model = ocCapabilityMapper.toModel(entity) + Assert.assertNotNull(model) + + Assert.assertEquals(ocCapability, model) + } +} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt new file mode 100644 index 00000000000..72e5ec9dd2d --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt @@ -0,0 +1,44 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.data.capabilities.datasources.mapper + +import com.owncloud.android.data.utils.DataTestUtil.DUMMY_CAPABILITY +import com.owncloud.android.data.utils.DataTestUtil.DUMMY_REMOTE_CAPABILITY +import org.junit.Assert +import org.junit.Test + +class OCRemoteCapabilityMapperTest { + + private val ocRemoteCapabilityMapper = RemoteCapabilityMapper() + + @Test + fun checkToModelNull() { + Assert.assertNull(ocRemoteCapabilityMapper.toModel(null)) + } + + @Test + fun checkToModelNotNull() { + Assert.assertNotNull(DUMMY_REMOTE_CAPABILITY) + + val capability = ocRemoteCapabilityMapper.toModel(DUMMY_REMOTE_CAPABILITY) + Assert.assertNotNull(capability) + Assert.assertEquals(capability, DUMMY_CAPABILITY) + } +} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntityTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntityTest.kt new file mode 100644 index 00000000000..12365b2462d --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntityTest.kt @@ -0,0 +1,234 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.data.capabilities.db + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class OCCapabilityEntityTest { + @Test + fun testEqualsNamedParams() { + val item1 = OCCapabilityEntity( + accountName = "user@server", + versionMayor = 2, + versionMinor = 1, + versionMicro = 0, + versionString = "1.0.0", + versionEdition = "1.0.0", + corePollInterval = 0, + filesSharingApiEnabled = 0, + filesSharingSearchMinLength = 2, + filesSharingPublicEnabled = 1, + filesSharingPublicPasswordEnforced = 0, + filesSharingPublicPasswordEnforcedReadOnly = 0, + filesSharingPublicPasswordEnforcedReadWrite = 0, + filesSharingPublicPasswordEnforcedUploadOnly = 0, + filesSharingPublicExpireDateEnabled = 0, + filesSharingPublicExpireDateDays = 0, + filesSharingPublicExpireDateEnforced = 0, + filesSharingPublicSendMail = 0, + filesSharingPublicUpload = 0, + filesSharingPublicMultiple = 0, + filesSharingPublicSupportsUploadOnly = 0, + filesSharingUserSendMail = 0, + filesSharingResharing = 0, + filesSharingFederationOutgoing = 0, + filesSharingFederationIncoming = 0, + filesBigFileChunking = 0, + filesUndelete = 0, + filesVersioning = 0 + ) + + val item2 = OCCapabilityEntity( + "user@server", + 2, + 1, + 0, + "1.0.0", + "1.0.0", + 0, + 0, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ) + + // Autogenerate Id should differ but it is not generated at this moment + // Tested on DAO + assertTrue(item1 == item2) + assertFalse(item1 === item2) + } + + @Test + fun testEqualsNamedParamsNullValues() { + val item1 = OCCapabilityEntity( + accountName = null, + versionMayor = 2, + versionMinor = 1, + versionMicro = 0, + versionString = null, + versionEdition = null, + corePollInterval = 0, + filesSharingApiEnabled = 0, + filesSharingSearchMinLength = 3, + filesSharingPublicEnabled = 1, + filesSharingPublicPasswordEnforced = 0, + filesSharingPublicPasswordEnforcedReadOnly = 0, + filesSharingPublicPasswordEnforcedReadWrite = 0, + filesSharingPublicPasswordEnforcedUploadOnly = 0, + filesSharingPublicExpireDateEnabled = 0, + filesSharingPublicExpireDateDays = 0, + filesSharingPublicExpireDateEnforced = 0, + filesSharingPublicSendMail = 0, + filesSharingPublicUpload = 0, + filesSharingPublicMultiple = 0, + filesSharingPublicSupportsUploadOnly = 0, + filesSharingUserSendMail = 0, + filesSharingResharing = 0, + filesSharingFederationOutgoing = 0, + filesSharingFederationIncoming = 0, + filesBigFileChunking = 0, + filesUndelete = 0, + filesVersioning = 0 + ) + + val item2 = OCCapabilityEntity( + null, + 2, + 1, + 0, + null, + null, + 0, + 0, + 3, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ) + + // Autogenerate Id should differ but it is not generated at this moment + // Tested on DAO + assertTrue(item1 == item2) + assertFalse(item1 === item2) + } + + @Test + fun testNotEqualsNamedParams() { + val item1 = OCCapabilityEntity( + accountName = "user@server", + versionMayor = 2, + versionMinor = 1, + versionMicro = 0, + versionString = "1.0.0", + versionEdition = "1.0.0", + corePollInterval = 0, + filesSharingApiEnabled = 0, + filesSharingSearchMinLength = 5, + filesSharingPublicEnabled = 1, + filesSharingPublicPasswordEnforced = 0, + filesSharingPublicPasswordEnforcedReadOnly = 0, + filesSharingPublicPasswordEnforcedReadWrite = 0, + filesSharingPublicPasswordEnforcedUploadOnly = 0, + filesSharingPublicExpireDateEnabled = 0, + filesSharingPublicExpireDateDays = 0, + filesSharingPublicExpireDateEnforced = 0, + filesSharingPublicSendMail = 0, + filesSharingPublicUpload = 0, + filesSharingPublicMultiple = 0, + filesSharingPublicSupportsUploadOnly = 0, + filesSharingUserSendMail = 0, + filesSharingResharing = 0, + filesSharingFederationOutgoing = 0, + filesSharingFederationIncoming = 0, + filesBigFileChunking = 0, + filesUndelete = 0, + filesVersioning = 0 + ) + + val item2 = OCCapabilityEntity( + "AnyAccountName", + 2, + 1, + 0, + "1.0.0", + "1.0.0", + 0, + 0, + 5, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ) + + assertFalse(item1 == item2) + assertFalse(item1 === item2) + } +} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt new file mode 100644 index 00000000000..dc2135946d9 --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt @@ -0,0 +1,129 @@ +/** + * ownCloud Android client application + * + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.data.capabilities.repository + +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.lifecycle.MutableLiveData +import com.owncloud.android.data.capabilities.datasources.LocalCapabilitiesDataSource +import com.owncloud.android.data.capabilities.datasources.RemoteCapabilitiesDataSource +import com.owncloud.android.data.utils.DataTestUtil +import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.domain.exceptions.NoConnectionWithServerException +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.junit.Assert +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class OCCapabilityRepositoryTest { + @Rule + @JvmField + val instantExecutorRule = InstantTaskExecutorRule() + + private val localCapabilitiesDataSource = mockk(relaxed = true) + private val remoteCapabilitiesDataSource = mockk(relaxed = true) + private val ocCapabilityRepository: OCCapabilityRepository = + OCCapabilityRepository(localCapabilitiesDataSource, remoteCapabilitiesDataSource) + + @Test + fun refreshCapabilitiesFromNetworkOk() { + val defaultAccountName = "admin@server" + + val capability = DataTestUtil.createCapability(defaultAccountName) + + every { remoteCapabilitiesDataSource.getCapabilities(any()) } returns capability + + ocCapabilityRepository.refreshCapabilitiesForAccount(defaultAccountName) + + verify(exactly = 1) { + remoteCapabilitiesDataSource.getCapabilities(defaultAccountName) + } + + verify(exactly = 1) { + localCapabilitiesDataSource.insert(listOf(capability)) + } + } + + @Test(expected = NoConnectionWithServerException::class) + fun refreshCapabilitiesFromNetworkNoConnection() { + val defaultAccountName = "admin@server" + val capability = DataTestUtil.createCapability(defaultAccountName) + + every { remoteCapabilitiesDataSource.getCapabilities(any()) } throws NoConnectionWithServerException() + + ocCapabilityRepository.refreshCapabilitiesForAccount(defaultAccountName) + + verify(exactly = 1) { + remoteCapabilitiesDataSource.getCapabilities(defaultAccountName) + } + verify(exactly = 0) { + localCapabilitiesDataSource.insert(listOf(capability)) + } + } + + @Test + fun getCapabilitiesAsLiveData() { + val defaultAccountName = "admin@server" + + val capabilitiesLiveData = MutableLiveData() + + every { + localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(any()) + } returns capabilitiesLiveData + + val capabilitiesEmitted = mutableListOf() + ocCapabilityRepository.getCapabilitiesAsLiveData(defaultAccountName).observeForever { + capabilitiesEmitted.add(it!!) + } + + + val capabilitiesToEmit = listOf(DataTestUtil.createCapability()) + capabilitiesToEmit.forEach { + capabilitiesLiveData.postValue(it) + } + + Assert.assertEquals(capabilitiesToEmit, capabilitiesEmitted) + } + + @Test(expected = Exception::class) + fun getCapabilitiesAsLiveDataException() { + val defaultAccountName = "admin@server" + + val capabilitiesLiveData = MutableLiveData() + + every { + localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(any()) + } throws Exception() + + val capabilitiesEmitted = mutableListOf() + ocCapabilityRepository.getCapabilitiesAsLiveData(defaultAccountName) + + val capabilitiesToEmit = listOf(DataTestUtil.createCapability()) + capabilitiesToEmit.forEach { + capabilitiesLiveData.postValue(it) + } + + Assert.assertEquals(capabilitiesToEmit, capabilitiesEmitted) + } +} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/sharees/repository/OCShareeRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/sharees/repository/OCShareeRepositoryTest.kt new file mode 100644 index 00000000000..97f668c273a --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/data/sharees/repository/OCShareeRepositoryTest.kt @@ -0,0 +1,64 @@ +/** + * ownCloud Android client application + * + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.data.sharees.repository + +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import com.owncloud.android.data.sharing.sharees.datasources.RemoteShareeDataSource +import com.owncloud.android.data.sharing.sharees.repository.OCShareeRepository +import com.owncloud.android.domain.exceptions.NoConnectionWithServerException +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class OCShareeRepositoryTest { + @Rule + @JvmField + val instantExecutorRule = InstantTaskExecutorRule() + + private val remoteShareeDataSource = mockk(relaxed = true) + private val oCShareeRepository: OCShareeRepository = OCShareeRepository((remoteShareeDataSource)) + + @Test + fun readShareesFromNetworkOk() { + every { remoteShareeDataSource.getSharees(any(), any(), any()) } returns arrayListOf() + + oCShareeRepository.getSharees("user", 1, 5) + + verify(exactly = 1) { + remoteShareeDataSource.getSharees("user", 1, 5) + } + } + + @Test(expected = NoConnectionWithServerException::class) + fun readShareesFromNetworkNoConnection() { + every { remoteShareeDataSource.getSharees(any(), any(), any()) } throws NoConnectionWithServerException() + + oCShareeRepository.getSharees("user", 1, 5) + + verify(exactly = 1) { + remoteShareeDataSource.getSharees("user", 1, 5) + } + } +} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt index 22a99799417..b877975e3f5 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt @@ -101,17 +101,17 @@ class OCLocalDataSourceTest { ) ) - assertEquals(2, shares?.size) + assertEquals(2, shares.size) - assertEquals("/Docs/doc1.doc", shares?.first()?.path) - assertEquals(false, shares?.first()?.isFolder) - assertEquals("username", shares?.first()?.shareWith) - assertEquals("Sophie", shares?.first()?.sharedWithDisplayName) + assertEquals("/Docs/doc1.doc", shares.first().path) + assertEquals(false, shares.first().isFolder) + assertEquals("username", shares.first().shareWith) + assertEquals("Sophie", shares.first().sharedWithDisplayName) - assertEquals("/Docs/doc1.doc", shares?.get(1)?.path) - assertEquals(false, shares?.get(1)?.isFolder) - assertEquals("user.name", shares?.get(1)?.shareWith) - assertEquals("Nicole", shares?.get(1)?.sharedWithDisplayName) + assertEquals("/Docs/doc1.doc", shares[1].path) + assertEquals(false, shares[1].isFolder) + assertEquals("user.name", shares[1].shareWith) + assertEquals("Nicole", shares[1].sharedWithDisplayName) } @Test @@ -215,17 +215,17 @@ class OCLocalDataSourceTest { ) ) - assertEquals(2, shares?.size) + assertEquals(2, shares.size) - assertEquals("/Photos/", shares?.first()?.path) - assertEquals(true, shares?.first()?.isFolder) - assertEquals("Photos link", shares?.first()?.name) - assertEquals("http://server:port/s/1", shares?.first()?.shareLink) + assertEquals("/Photos/", shares.first().path) + assertEquals(true, shares.first().isFolder) + assertEquals("Photos link", shares.first().name) + assertEquals("http://server:port/s/1", shares.first().shareLink) - assertEquals("/Photos/", shares?.get(1)?.path) - assertEquals(true, shares?.get(1)?.isFolder) - assertEquals("Photos link 2", shares?.get(1)?.name) - assertEquals("http://server:port/s/2", shares?.get(1)?.shareLink) + assertEquals("/Photos/", shares[1].path) + assertEquals(true, shares[1].isFolder) + assertEquals("Photos link 2", shares[1].name) + assertEquals("http://server:port/s/2", shares[1].shareLink) } @Test diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt index e85770e3303..e575e9bee00 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt @@ -20,33 +20,32 @@ package com.owncloud.android.data.shares.datasources -import com.owncloud.android.data.sharing.shares.datasources.OCRemoteShareDataSource +import com.owncloud.android.data.sharing.shares.datasources.implementation.OCRemoteShareDataSource +import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteShareMapper +import com.owncloud.android.data.sharing.shares.network.OCShareService import com.owncloud.android.data.utils.DataTestUtil -import com.owncloud.android.lib.common.OwnCloudClient +import com.owncloud.android.domain.exceptions.ShareForbiddenException +import com.owncloud.android.domain.exceptions.ShareNotFoundException +import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.CreateRemoteShareOperation -import com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation -import com.owncloud.android.lib.resources.shares.RemoveRemoteShareOperation import com.owncloud.android.lib.resources.shares.ShareParserResult -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.lib.resources.shares.UpdateRemoteShareOperation import io.mockk.every import io.mockk.mockk -import io.mockk.mockkClass -import junit.framework.Assert.assertEquals import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat +import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test -class OCRemoteSharesDataSourceTest { - private lateinit var ocRemoteSharesDataSource: OCRemoteShareDataSource - private val ownCloudClient = mockkClass(OwnCloudClient::class) +class OCRemoteShareDataSourceTest { + private lateinit var ocRemoteShareDataSource: OCRemoteShareDataSource + + private val ocShareService: OCShareService = mockk() + private val remoteShareMapper = RemoteShareMapper() @Before fun init() { - ocRemoteSharesDataSource = - com.owncloud.android.data.sharing.shares.datasources.OCRemoteShareDataSource(ownCloudClient) + ocRemoteShareDataSource = OCRemoteShareDataSource(ocShareService, remoteShareMapper) } /****************************************************************************************************** @@ -55,8 +54,6 @@ class OCRemoteSharesDataSourceTest { @Test fun insertPrivateShare() { - val createShareOperation = mockk(relaxed = true) - val createRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( ShareParserResult( arrayListOf( @@ -73,22 +70,19 @@ class OCRemoteSharesDataSourceTest { ) every { - createShareOperation.execute(ownCloudClient) + ocShareService.insertShare(any(), any(), any(), any(), any(), any(), any(), any()) } returns createRemoteShareOperationResult // Insert share on remote datasource - val remoteOperationResult = ocRemoteSharesDataSource.insertShare( + val privateShareAdded = ocRemoteShareDataSource.insertShare( remoteFilePath = "Photos/", shareType = ShareType.USER, shareWith = "user", permissions = 1, - createRemoteShareOperation = createShareOperation + accountName = "user@server" ) - assertThat(remoteOperationResult, notNullValue()) - assertEquals(1, remoteOperationResult.data.shares.size) - - val privateShareAdded = remoteOperationResult.data.shares[0] + assertThat(privateShareAdded, notNullValue()) assertEquals("Photos/", privateShareAdded.path) assertEquals(true, privateShareAdded.isFolder) @@ -99,12 +93,10 @@ class OCRemoteSharesDataSourceTest { @Test fun updatePrivateShare() { - val updateRemoteShareOperation = mock(UpdateRemoteShareOperation::class.java) - - val updateRemoteShareOperationResult = TestUtil.createRemoteOperationResultMock( + val updateRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( ShareParserResult( arrayListOf( - TestUtil.createRemoteShare( + DataTestUtil.createRemoteShare( shareType = ShareType.USER.value, path = "Images/image_1.mp4", shareWith = "user", @@ -118,21 +110,18 @@ class OCRemoteSharesDataSourceTest { true ) - `when`(updateRemoteShareOperation.execute(ownCloudClient)).thenReturn( - updateRemoteShareOperationResult - ) + every { + ocShareService.updateShare(any(), any(), any(), any(), any(), any()) + } returns updateRemoteShareOperationResult // Update share on remote datasource - val remoteOperationResult = ocRemoteSharesDataSource.updateShare( + val privateShareUpdated = ocRemoteShareDataSource.updateShare( remoteId = 3, permissions = 17, - updateRemoteShareOperation = updateRemoteShareOperation + accountName = "user@server" ) - assertThat(remoteOperationResult, notNullValue()) - assertEquals(1, remoteOperationResult.data.shares.size) - - val privateShareUpdated = remoteOperationResult.data.shares[0] + assertThat(privateShareUpdated, notNullValue()) assertEquals("Images/image_1.mp4", privateShareUpdated.path) assertEquals("user", privateShareUpdated.shareWith) @@ -147,8 +136,6 @@ class OCRemoteSharesDataSourceTest { @Test fun insertPublicShare() { - val createShareOperation = mockk(relaxed = true) - val createRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( ShareParserResult( arrayListOf( @@ -165,26 +152,19 @@ class OCRemoteSharesDataSourceTest { ) every { - createShareOperation.execute(ownCloudClient) + ocShareService.insertShare(any(), any(), any(), any(), any(), any(), any(), any()) } returns createRemoteShareOperationResult // Insert share on remote datasource - val remoteOperationResult = ocRemoteSharesDataSource.insertShare( + val publicShareAdded = ocRemoteShareDataSource.insertShare( "Photos/img1.png", ShareType.PUBLIC_LINK, "", 1, - "img1 link", - "1234", - -1, - false, - createShareOperation + accountName = "user@server" ) - assertThat(remoteOperationResult, notNullValue()) - assertEquals(1, remoteOperationResult.data.shares.size) - - val publicShareAdded = remoteOperationResult.data.shares[0] + assertThat(publicShareAdded, notNullValue()) assertEquals("", publicShareAdded.shareWith) assertEquals(1, publicShareAdded.permissions) @@ -194,45 +174,8 @@ class OCRemoteSharesDataSourceTest { assertEquals("http://server:port/s/112ejbhdasyd1", publicShareAdded.shareLink) } - @Test - fun insertPublicShareNoFile() { - val createRemoteShareOperation = mockk(relaxed = true) - - val httpPhrase = "Wrong path, file/folder doesn't exist" - val createRemoteSharesOperationResult = DataTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf()), - false, - httpPhrase, - RemoteOperationResult.ResultCode.SHARE_NOT_FOUND - ) - - every { - createRemoteShareOperation.execute(ownCloudClient) - } returns createRemoteSharesOperationResult - - val remoteOperationResult = ocRemoteSharesDataSource.insertShare( - "Photos/img2.png", - ShareType.PUBLIC_LINK, - "", - 1, - "img2 link", - "5678", - -1, - false, - createRemoteShareOperation - ) - - val publicSharesAdded = remoteOperationResult.data - - assertEquals(0, publicSharesAdded.shares.size) - assertEquals(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND, remoteOperationResult.code) - assertEquals(httpPhrase, remoteOperationResult.httpPhrase) - } - @Test fun updatePublicShare() { - val updateRemoteShareOperation = mockk(relaxed = true) - val updateRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( ShareParserResult( arrayListOf( @@ -251,24 +194,17 @@ class OCRemoteSharesDataSourceTest { ) every { - updateRemoteShareOperation.execute(ownCloudClient) + ocShareService.updateShare(any(), any(), any(), any(), any(), any()) } returns updateRemoteShareOperationResult // Update share on remote datasource - val remoteOperationResult = ocRemoteSharesDataSource.updateShare( - 3, - "Videos/video1.mp4", - "1234", - 2000, - 1, - false, - updateRemoteShareOperation + val publicShareUpdated = ocRemoteShareDataSource.updateShare( + remoteId = 3, + permissions = 17, + accountName = "user@server" ) - assertThat(remoteOperationResult, notNullValue()) - assertEquals(1, remoteOperationResult.data.shares.size) - - val publicShareUpdated = remoteOperationResult.data.shares[0] + assertThat(publicShareUpdated, notNullValue()) assertEquals("video1 link updated", publicShareUpdated.name) assertEquals("Videos/video1.mp4", publicShareUpdated.path) @@ -278,33 +214,12 @@ class OCRemoteSharesDataSourceTest { assertEquals("http://server:port/s/1275farv", publicShareUpdated.shareLink) } - @Test - fun deletePublicShare() { - val removeRemoteShareOperation = mockkClass(RemoveRemoteShareOperation::class) - - val removeRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf()), - isSuccess = true - ) - - every { - removeRemoteShareOperation.execute(ownCloudClient) - } returns removeRemoteShareOperationResult - - val remoteOperationResult = ocRemoteSharesDataSource.deleteShare(1, removeRemoteShareOperation) - - assertThat(remoteOperationResult, notNullValue()) - assertEquals(true, remoteOperationResult.isSuccess) - } - /****************************************************************************************************** *********************************************** COMMON *********************************************** ******************************************************************************************************/ @Test fun readRemoteShares() { - val getRemoteSharesForFileOperation = mockkClass(GetRemoteSharesForFileOperation::class) - val remoteShares = arrayListOf( DataTestUtil.createRemoteShare( shareType = ShareType.PUBLIC_LINK.value, @@ -342,42 +257,41 @@ class OCRemoteSharesDataSourceTest { ) every { - getRemoteSharesForFileOperation.execute(ownCloudClient) + ocShareService.getShares(any(), any(), any()) } returns getRemoteSharesOperationResult // Get shares from remote datasource - val remoteOperationResult = ocRemoteSharesDataSource.getShares( - "/Documents/doc", - true, - true, - getRemoteSharesForFileOperation + val shares = ocRemoteShareDataSource.getShares( + remoteFilePath = "/Documents/doc", + reshares = true, + subfiles = true, + accountName = "user@server" ) - assertThat(remoteOperationResult, notNullValue()) - assertEquals(4, remoteOperationResult.data.shares.size) + assertEquals(4, shares.size) - val publicShare1 = remoteOperationResult.data.shares[0] + val publicShare1 = shares[0] assertEquals(ShareType.PUBLIC_LINK, publicShare1.shareType) assertEquals("/Documents/doc", publicShare1.path) assertEquals(false, publicShare1.isFolder) assertEquals("Doc link", publicShare1.name) assertEquals("http://server:port/s/1", publicShare1.shareLink) - val publicShare2 = remoteOperationResult.data.shares[1] + val publicShare2 = shares[1] assertEquals(ShareType.PUBLIC_LINK, publicShare2.shareType) assertEquals("/Documents/doc", publicShare2.path) assertEquals(false, publicShare2.isFolder) assertEquals("Doc link 2", publicShare2.name) assertEquals("http://server:port/s/2", publicShare2.shareLink) - val userShare = remoteOperationResult.data.shares[2] + val userShare = shares[2] assertEquals(ShareType.USER, userShare.shareType) assertEquals("/Documents/doc", userShare.path) assertEquals(false, userShare.isFolder) assertEquals("steve", userShare.shareWith) assertEquals("Steve", userShare.sharedWithDisplayName) - val groupShare = remoteOperationResult.data.shares[3] + val groupShare = shares[3] assertEquals(ShareType.GROUP, groupShare.shareType) assertEquals("/Documents/doc", groupShare.path) assertEquals(false, groupShare.isFolder) @@ -385,22 +299,104 @@ class OCRemoteSharesDataSourceTest { assertEquals("My family", groupShare.sharedWithDisplayName) } + @Test(expected = ShareNotFoundException::class) + fun insertShareFileNotFound() { + createShareOperationWithError(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND) + } + + @Test(expected = ShareForbiddenException::class) + fun insertShareForbidden() { + createShareOperationWithError(RemoteOperationResult.ResultCode.SHARE_FORBIDDEN) + } + + private fun createShareOperationWithError(resultCode: RemoteOperationResult.ResultCode? = null) { + val createRemoteSharesOperationResult = DataTestUtil.createRemoteOperationResultMock( + ShareParserResult(arrayListOf()), + false, + null, + resultCode + ) + + every { + ocShareService.insertShare(any(), any(), any(), any(), any(), any(), any(), any()) + } returns createRemoteSharesOperationResult + + ocRemoteShareDataSource.insertShare( + "Photos/img2.png", + ShareType.PUBLIC_LINK, + "", + 1, + accountName = "user@server" + ) + } + + @Test(expected = ShareNotFoundException::class) + fun updateShareFileNotFound() { + updateShareOperationWithError(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND) + } + + @Test(expected = ShareForbiddenException::class) + fun updateShareForbidden() { + updateShareOperationWithError(RemoteOperationResult.ResultCode.SHARE_FORBIDDEN) + } + + private fun updateShareOperationWithError(resultCode: RemoteOperationResult.ResultCode? = null) { + val updateRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( + ShareParserResult(arrayListOf()), + false, + null, + resultCode + ) + + every { + ocShareService.updateShare(any(), any(), any(), any(), any(), any()) + } returns updateRemoteShareOperationResult + + ocRemoteShareDataSource.updateShare( + 3, + permissions = 17, + accountName = "user@server" + ) + } + @Test fun deleteShare() { - val removeRemoteShareOperation = mock(RemoveRemoteShareOperation::class.java) - - val removeRemoteShareOperationResult = TestUtil.createRemoteOperationResultMock( + val removeRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( ShareParserResult(arrayListOf()), isSuccess = true ) - `when`(removeRemoteShareOperation.execute(ownCloudClient)).thenReturn( - removeRemoteShareOperationResult + every { + ocShareService.deleteShare(any()) + } returns removeRemoteShareOperationResult + + ocRemoteShareDataSource.deleteShare(1) + + // We check there's no exception here + } + + @Test(expected = ShareNotFoundException::class) + fun removeShareFileNotFound() { + deleteShareOperationWithError(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND) + } + + @Test(expected = ShareForbiddenException::class) + fun removeShareForbidden() { + deleteShareOperationWithError(RemoteOperationResult.ResultCode.SHARE_FORBIDDEN) + } + + private fun deleteShareOperationWithError(resultCode: RemoteOperationResult.ResultCode? = null) { + val removeRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( + ShareParserResult(arrayListOf()), + false, + null, + resultCode ) - val remoteOperationResult = ocRemoteSharesDataSource.deleteShare(1, removeRemoteShareOperation) + every { + ocShareService.deleteShare(any()) + } returns removeRemoteShareOperationResult - assertThat(remoteOperationResult, notNullValue()) - assertEquals(true, remoteOperationResult.isSuccess) + ocRemoteShareDataSource.deleteShare(1) } -} +} \ No newline at end of file diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt new file mode 100644 index 00000000000..a5c030c1877 --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt @@ -0,0 +1,45 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.data.shares.datasources.mapper + +import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteShareMapper +import com.owncloud.android.data.utils.DataTestUtil.DUMMY_REMOTE_SHARE +import com.owncloud.android.data.utils.DataTestUtil.DUMMY_SHARE +import org.junit.Assert +import org.junit.Test + +class OCRemoteShareMapperTest { + + private val ocRemoteShareMapper = RemoteShareMapper() + + @Test + fun checkToModelNull() { + Assert.assertNull(ocRemoteShareMapper.toModel(null)) + } + + @Test + fun checkToModelNotNull() { + Assert.assertNotNull(DUMMY_REMOTE_SHARE) + + val capability = ocRemoteShareMapper.toModel(DUMMY_REMOTE_SHARE) + Assert.assertNotNull(capability) + Assert.assertEquals(capability, DUMMY_SHARE.copy(accountOwner = "")) + } +} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt new file mode 100644 index 00000000000..cbde8191936 --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt @@ -0,0 +1,79 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.data.shares.datasources.mapper + +import com.owncloud.android.data.sharing.shares.datasources.mapper.OCShareMapper +import com.owncloud.android.data.utils.DataTestUtil.createShare +import com.owncloud.android.data.utils.DataTestUtil.createShareEntity +import org.junit.Assert +import org.junit.Test + +class OCShareMapperTest { + private val ocShareMapper = OCShareMapper() + + private val ocShare = + createShare( + isFolder = false, + path = "/Photos/image2.jpg", + shareType = 0 + ) + + private val ocShareEntity = + createShareEntity( + isFolder = false, + path = "/Photos/image2.jpg", + shareType = 0 + ) + + @Test + fun checkToModelNull() { + Assert.assertNull(ocShareMapper.toModel(null)) + } + + @Test + fun checkToModelNotNull() { + Assert.assertNotNull(ocShareEntity) + + val model = ocShareMapper.toModel(ocShareEntity) + Assert.assertNotNull(model) + Assert.assertEquals(ocShare, model) + + val mappedEntity = ocShareMapper.toEntity(model) + Assert.assertNotNull(mappedEntity) + + Assert.assertEquals(ocShareEntity, mappedEntity) + } + + @Test + fun checkToEntityNull() { + Assert.assertNull(ocShareMapper.toEntity(null)) + } + + @Test + fun checkToEntityNotNull() { + val entity = ocShareMapper.toEntity(ocShare) + Assert.assertNotNull(entity) + + val model = ocShareMapper.toModel(entity) + Assert.assertNotNull(model) + + Assert.assertEquals(ocShare, model) + } +} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/db/OCShareEntityTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/db/OCShareEntityTest.kt new file mode 100644 index 00000000000..289e788a27d --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/db/OCShareEntityTest.kt @@ -0,0 +1,169 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.data.shares.db + +import com.owncloud.android.data.sharing.shares.db.OCShareEntity +import org.junit.Assert.assertTrue +import org.junit.Assert.assertFalse +import org.junit.Test + +class OCShareEntityTest { + + @Test + fun testEqualsNamedParams() { + val item1 = OCShareEntity( + fileSource = 7, + itemSource = 7, + shareType = 0, + shareWith = "", + path = "/Photos/image2.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "pwdasd12dasdWZ", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = "", + shareLink = "" + ) + + val item2 = OCShareEntity( + 7, + 7, + 0, + "", + "/Photos/image2.jpg", + 1, + 1542628397, + 0, + "pwdasd12dasdWZ", + "", + "", + false, + -1, + 1, + "admin@server", + "", + "" + ) + + // Autogenerate Id should differ but it is not generated at this moment + // Tested on DAO + assertTrue(item1 == item2) + assertFalse(item1 === item2) + } + + @Test + fun testEqualsNamedParamsNullValues() { + val item1 = OCShareEntity( + fileSource = 7, + itemSource = 7, + shareType = 0, + shareWith = null, + path = "/Photos/image2.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = null, + sharedWithDisplayName = null, + sharedWithAdditionalInfo = null, + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = null, + shareLink = null + ) + + val item2 = OCShareEntity( + 7, + 7, + 0, + null, + "/Photos/image2.jpg", + 1, + 1542628397, + 0, + null, + null, + null, + false, + -1, + 1, + "admin@server", + null, + null + ) + + // Autogenerate Id should differ but it is not generated at this moment + assertTrue(item1 == item2) + assertFalse(item1 === item2) + } + + @Test + fun testNotEqualsNamedParams() { + val item1 = OCShareEntity( + fileSource = 7, + itemSource = 7, + shareType = 0, + shareWith = "", + path = "/Photos/image2.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "pwdasd12dasdWZ", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = "", + shareLink = "" + ) + + val item2 = OCShareEntity( + 7, + 7, + 0, + "", + "/Photos/image2.jpg", + 1, + 1542628397, + 0, + "pwdasd12dasdWZ", + "", + "", + false, + -1, + 1, + "AnyServer", + "", + "" + ) + + assertFalse(item1 == item2) + assertFalse(item1 === item2) + } +} diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt new file mode 100644 index 00000000000..70045a51642 --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt @@ -0,0 +1,517 @@ +/** + * ownCloud Android client application + * + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.data.shares.repository + +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.lifecycle.MutableLiveData +import com.owncloud.android.data.sharing.shares.datasources.LocalShareDataSource +import com.owncloud.android.data.sharing.shares.datasources.RemoteShareDataSource +import com.owncloud.android.data.sharing.shares.repository.OCShareRepository +import com.owncloud.android.data.utils.DataTestUtil +import com.owncloud.android.domain.exceptions.FileNotFoundException +import com.owncloud.android.domain.exceptions.NoConnectionWithServerException +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.model.ShareType +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import org.junit.Assert +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class OCShareRepositoryTest { + @Rule + @JvmField + val instantExecutorRule = InstantTaskExecutorRule() + + private val localShareDataSource = mockk(relaxed = true) + private val remoteShareDataSource = mockk(relaxed = true) + private val ocShareRepository: OCShareRepository = + OCShareRepository(localShareDataSource, remoteShareDataSource) + + private val shares = arrayListOf( + DataTestUtil.createPublicShare(), + DataTestUtil.createPrivateShare(), + DataTestUtil.createPrivateShare(), + DataTestUtil.createPublicShare() + ) + + private val filePath = "/Images" + private val accountName = "admin@server" + + @Test + fun refreshSharesFromNetworkOk() { + every { remoteShareDataSource.getShares(any(), any(), any(), any()) } returns shares + + ocShareRepository.refreshSharesFromNetwork(filePath, accountName) + + verify(exactly = 1) { + remoteShareDataSource.getShares(filePath, true, false, accountName) + } + + verify(exactly = 1) { + localShareDataSource.replaceShares(shares) + } + } + + @Test + fun refreshSharesFromNetworkEmptyShares() { + every { remoteShareDataSource.getShares(any(), any(), any(), any()) } returns listOf() + + ocShareRepository.refreshSharesFromNetwork(filePath, accountName) + + verify(exactly = 1) { + remoteShareDataSource.getShares(filePath, true, false, accountName) + } + + verify(exactly = 1) { + localShareDataSource.deleteSharesForFile(filePath, accountName) + } + } + + @Test(expected = NoConnectionWithServerException::class) + fun refreshSharesFromNetworkNoConnection() { + every { remoteShareDataSource.getShares(any(), any(), any(), any()) } throws NoConnectionWithServerException() + + ocShareRepository.refreshSharesFromNetwork(filePath, accountName) + + verify(exactly = 1) { + remoteShareDataSource.getShares(filePath, true, false, accountName) + } + + verify(exactly = 1) { + localShareDataSource.replaceShares(shares) + } + } + + @Test + fun getStoredSharesOk() { + val sharesLiveData = MutableLiveData>() + + every { + localShareDataSource.getSharesAsLiveData(any(), any(), any()) + } returns sharesLiveData + + val sharesEmitted = mutableListOf>() + ocShareRepository.getSharesAsLiveData(filePath, accountName).observeForever { + sharesEmitted.add(it!!) + } + + val sharesToEmit = listOf(shares) + sharesToEmit.forEach { + sharesLiveData.postValue(it) + } + + Assert.assertEquals(sharesToEmit, sharesEmitted) + } + + @Test(expected = Exception::class) + fun getStoredSharesException() { + val sharesLiveData = MutableLiveData>() + + every { + localShareDataSource.getSharesAsLiveData(any(), any(), any()) + } throws Exception() + + val sharesEmitted = mutableListOf>() + ocShareRepository.getSharesAsLiveData(filePath, accountName) + + val sharesToEmit = listOf(shares) + sharesToEmit.forEach { + sharesLiveData.postValue(it) + } + + Assert.assertEquals(sharesToEmit, sharesEmitted) + } + + @Test + fun getStoredShareOk() { + val shareLiveData = MutableLiveData() + + every { + localShareDataSource.getShareAsLiveData(any()) + } returns shareLiveData + + val sharesEmitted = mutableListOf() + ocShareRepository.getShareAsLiveData(1).observeForever { + sharesEmitted.add(it!!) + } + + val sharesToEmit = listOf(shares.first()) + + sharesToEmit.forEach { + shareLiveData.postValue(it) + } + + Assert.assertEquals(sharesToEmit, sharesEmitted) + } + + @Test(expected = Exception::class) + fun getStoredShareException() { + val shareLiveData = MutableLiveData() + + every { + localShareDataSource.getShareAsLiveData(any()) + } throws Exception() + + val sharesEmitted = mutableListOf() + ocShareRepository.getShareAsLiveData(1) + + val sharesToEmit = listOf(shares.first()) + + sharesToEmit.forEach { + shareLiveData.postValue(it) + } + + Assert.assertEquals(sharesToEmit, sharesEmitted) + } + + @Test + fun insertPublicShareOk() { + every { + remoteShareDataSource.insertShare( + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } returns shares.first() + + ocShareRepository.insertPublicShare( + filePath, + -1, + "Docs link", + "password", + 2000, + false, + accountName + ) + + verify(exactly = 1) { + remoteShareDataSource.insertShare( + filePath, + ShareType.PUBLIC_LINK, + "", + -1, + "Docs link", + "password", + 2000, + false, + accountName + ) + } + + verify(exactly = 1) { localShareDataSource.insert(shares.first()) } + } + + @Test(expected = FileNotFoundException::class) + fun insertPublicShareFileNotFoundException() { + every { + remoteShareDataSource.insertShare( + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } throws FileNotFoundException() + + ocShareRepository.insertPublicShare( + filePath, + -1, + "Docs link", + "password", + 2000, + false, + accountName + ) + + verify(exactly = 1) { + remoteShareDataSource.insertShare( + filePath, + ShareType.PUBLIC_LINK, + "", + -1, + "Docs link", + "password", + 2000, + false, + accountName + ) + } + + verify(exactly = 0) { + localShareDataSource.insert(shares.first()) + } + } + + @Test + fun updatePublicShareOk() { + every { + remoteShareDataSource.updateShare( + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } returns shares.first() + + ocShareRepository.updatePublicShare( + 1, + "Docs link", + "password", + 2000, + -1, + false, + accountName + ) + + verify(exactly = 1) { + remoteShareDataSource.updateShare( + 1, + "Docs link", + "password", + 2000, + -1, + false, + accountName + ) + } + + verify(exactly = 1) { localShareDataSource.update(shares.first()) } + } + + @Test(expected = FileNotFoundException::class) + fun updatePublicShareFileNotFoundException() { + every { + remoteShareDataSource.updateShare( + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } throws FileNotFoundException() + + ocShareRepository.updatePublicShare( + 1, + "Docs link", + "password", + 2000, + -1, + false, + accountName + ) + + verify(exactly = 1) { + remoteShareDataSource.updateShare( + 1, + "Docs link", + "password", + 2000, + -1, + false, + accountName + ) + } + + verify(exactly = 0) { + localShareDataSource.update(shares.first()) + } + } + + @Test + fun insertPrivateShareOk() { + every { + remoteShareDataSource.insertShare( + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } returns shares.get(2) + + ocShareRepository.insertPrivateShare( + filePath, + ShareType.GROUP, + "whoever", + -1, + accountName + ) + + verify(exactly = 1) { + remoteShareDataSource.insertShare( + filePath, + ShareType.GROUP, + "whoever", + -1, + accountName = accountName + ) + } + + verify(exactly = 1) { localShareDataSource.insert(shares.get(2)) } + } + + @Test(expected = FileNotFoundException::class) + fun insertPrivateShareFileNotFoundException() { + every { + remoteShareDataSource.insertShare( + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } throws FileNotFoundException() + + ocShareRepository.insertPrivateShare( + filePath, + ShareType.GROUP, + "whoever", + -1, + accountName + ) + + verify(exactly = 1) { + remoteShareDataSource.insertShare( + filePath, + ShareType.GROUP, + "whoever", + -1, + accountName = accountName + ) + } + + verify(exactly = 0) { + localShareDataSource.insert(shares.get(2)) + } + } + + @Test + fun updatePrivateShareOk() { + every { + remoteShareDataSource.updateShare( + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } returns shares.get(2) + + ocShareRepository.updatePrivateShare( + 1, + -1, + accountName + ) + + verify(exactly = 1) { + remoteShareDataSource.updateShare( + 1, + permissions = -1, + accountName = accountName + ) + } + + verify(exactly = 1) { localShareDataSource.update(shares.get(2)) } + } + + @Test(expected = FileNotFoundException::class) + fun updatePrivateShareFileNotFoundException() { + every { + remoteShareDataSource.updateShare( + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } throws FileNotFoundException() + + ocShareRepository.updatePrivateShare( + 1, + -1, + accountName + ) + + verify(exactly = 1) { + remoteShareDataSource.updateShare( + 1, + permissions = -1, + accountName = accountName + ) + } + + verify(exactly = 0) { localShareDataSource.update(shares.get(2)) } + } + + @Test + fun removeShare() { + val shareId = 1L + ocShareRepository.deleteShare(shareId) + + verify(exactly = 1) { remoteShareDataSource.deleteShare(shareId) } + verify(exactly = 1) { localShareDataSource.deleteShare(shareId) } + } + + @Test(expected = FileNotFoundException::class) + fun removeShareFileNotFoundException() { + val shareId = 1L + + every { + remoteShareDataSource.deleteShare(shareId) + } throws FileNotFoundException() + + ocShareRepository.deleteShare(shareId) + + verify(exactly = 1) { remoteShareDataSource.deleteShare(shareId) } + verify(exactly = 0) { localShareDataSource.deleteShare(shareId) } + } +} From 4a9263b32991d0681a35ec1405f960a9cef486b9 Mon Sep 17 00:00:00 2001 From: davigonz Date: Mon, 18 Nov 2019 12:32:57 +0100 Subject: [PATCH 05/41] Data module: instrumented tests --- .../capabilities/db/OCCapabilityDaoTest.kt | 16 +-- .../OCRemoteShareesDataSourceTest.kt | 29 +++-- .../data/sharing/shares/db/OCShareDaoTest.kt | 104 +++++++++++++----- .../OCLocalCapabilitiesDataSource.kt | 2 +- .../data/capabilities/db/OCCapabilityDao.kt | 2 +- 5 files changed, 98 insertions(+), 55 deletions(-) diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt index c09b05b7efe..bae7007e512 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt @@ -25,7 +25,7 @@ import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.utils.DataTestUtil import com.owncloud.android.data.utils.LiveDataTestUtil.getValue -import com.owncloud.android.lib.resources.status.CapabilityBooleanType +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import junit.framework.Assert.assertEquals import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.CoreMatchers.nullValue @@ -54,8 +54,8 @@ class OCCapabilityDaoTest { fun insertCapabilitiesAndRead() { ocCapabilityDao.insert( listOf( - DataTestUtil.createCapability("user1@server", 3, 2, 1, "3.1"), - DataTestUtil.createCapability("user2@server", 6, 5, 4, "6.0") + DataTestUtil.createCapabilityEntity("user1@server", 3, 2, 1, "3.1"), + DataTestUtil.createCapabilityEntity("user2@server", 6, 5, 4, "6.0") ) ) @@ -75,7 +75,7 @@ class OCCapabilityDaoTest { @Test fun getNonExistingCapabilities() { ocCapabilityDao.insert( - DataTestUtil.createCapability("user@server", 10, 9, 8, "10.1.4") + DataTestUtil.createCapabilityEntity("user@server", 10, 9, 8, "10.1.4") ) val capability = getValue( @@ -89,7 +89,7 @@ class OCCapabilityDaoTest { @Test fun replaceCapabilityIfAlreadyExists_exists() { ocCapabilityDao.insert( - DataTestUtil.createCapability( + DataTestUtil.createCapabilityEntity( "admin@server", 3, 2, @@ -101,7 +101,7 @@ class OCCapabilityDaoTest { ocCapabilityDao.replace( listOf( // Update capability - DataTestUtil.createCapability( + DataTestUtil.createCapabilityEntity( "admin@server", 3, 2, @@ -129,7 +129,7 @@ class OCCapabilityDaoTest { @Test fun replacePublicShareIfAlreadyExists_doesNotExist() { ocCapabilityDao.insert( - DataTestUtil.createCapability( + DataTestUtil.createCapabilityEntity( "cto@server", 10, 8, @@ -141,7 +141,7 @@ class OCCapabilityDaoTest { ocCapabilityDao.replace( listOf( // Update capability - DataTestUtil.createCapability( + DataTestUtil.createCapabilityEntity( "seo@server", 14, 13, diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt index f1aa328d22a..e861827ddc8 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt @@ -19,11 +19,12 @@ package com.owncloud.android.data.sharing.sharees.datasources +import com.owncloud.android.data.sharing.sharees.datasources.implementation.OCRemoteShareeDataSource +import com.owncloud.android.data.sharing.sharees.network.OCShareeService import com.owncloud.android.data.utils.DataTestUtil -import com.owncloud.android.lib.common.OwnCloudClient import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation import io.mockk.every -import io.mockk.mockkClass +import io.mockk.mockk import junit.framework.Assert.assertEquals import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat @@ -31,20 +32,19 @@ import org.json.JSONObject import org.junit.Before import org.junit.Test +// Needs to be instrumented since JSONObject is tied to the Android platform class OCRemoteShareesDataSourceTest { private lateinit var ocRemoteShareesDataSource: OCRemoteShareeDataSource - private val ownCloudClient = mockkClass(OwnCloudClient::class) + private val ocShareeService: OCShareeService = mockk() @Before fun init() { ocRemoteShareesDataSource = - OCRemoteShareeDataSource(ownCloudClient) + OCRemoteShareeDataSource(ocShareeService) } @Test fun readRemoteSharees() { - val getRemoteShareesForFileOperation = mockkClass(GetRemoteShareesOperation::class) - val remoteSharees: ArrayList = arrayListOf( DataTestUtil.createSharee("User 1", "0", "user1", "user1@mail.com"), DataTestUtil.createSharee("User 2", "0", "user2", "user2@mail.com"), @@ -57,35 +57,34 @@ class OCRemoteShareesDataSourceTest { ) every { - getRemoteShareesForFileOperation.execute(ownCloudClient) + ocShareeService.getSharees("user", 1 ,30) } returns getRemoteShareesOperationResult // Get sharees from remote datasource - val remoteOperationResult = ocRemoteShareesDataSource.getSharees( + val sharees = ocRemoteShareesDataSource.getSharees( "user", 1, - 30, - getRemoteShareesForFileOperation + 30 ) - assertThat(remoteOperationResult, notNullValue()) - assertEquals(3, remoteOperationResult.data.size) + assertThat(sharees, notNullValue()) + assertEquals(3, sharees.size) - val sharee1 = remoteOperationResult.data[0] + val sharee1 = sharees.first() assertEquals(sharee1.getString(GetRemoteShareesOperation.PROPERTY_LABEL), "User 1") val value = sharee1.getJSONObject(GetRemoteShareesOperation.NODE_VALUE) assertEquals(value.getString(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE), "0") assertEquals(value.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH), "user1") assertEquals(value.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO), "user1@mail.com") - val sharee2 = remoteOperationResult.data[1] + val sharee2 = sharees.get(1) assertEquals(sharee2.getString(GetRemoteShareesOperation.PROPERTY_LABEL), "User 2") val value2 = sharee2.getJSONObject(GetRemoteShareesOperation.NODE_VALUE) assertEquals(value2.getString(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE), "0") assertEquals(value2.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH), "user2") assertEquals(value2.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO), "user2@mail.com") - val sharee3 = remoteOperationResult.data[2] + val sharee3 = sharees.get(2) assertEquals(sharee3.getString(GetRemoteShareesOperation.PROPERTY_LABEL), "User 3") val value3 = sharee3.getJSONObject(GetRemoteShareesOperation.NODE_VALUE) assertEquals(value3.getString(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE), "0") diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt index 588f15b2eff..d0adf48454a 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt @@ -25,10 +25,11 @@ import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.utils.DataTestUtil import com.owncloud.android.data.utils.LiveDataTestUtil.getValue -import com.owncloud.android.lib.resources.shares.ShareType -import junit.framework.Assert.assertEquals +import com.owncloud.android.domain.sharing.shares.model.ShareType import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Rule import org.junit.Test @@ -78,19 +79,19 @@ class OCShareDaoTest { fun insertSharesFromDifferentFilesAndRead() { ocShareDao.insert( listOf( - DataTestUtil.createPublicShare( + DataTestUtil.createPublicShareEntity( path = "/Photos/", isFolder = true, name = "Photos folder link", shareLink = "http://server:port/s/1" ), - DataTestUtil.createPublicShare( + DataTestUtil.createPublicShareEntity( path = "/Photos/image1.jpg", isFolder = false, name = "Image 1 link", shareLink = "http://server:port/s/2" ), - DataTestUtil.createPrivateShare( + DataTestUtil.createPrivateShareEntity( path = "/Photos/image2.jpg", isFolder = false, shareWith = "username", @@ -143,21 +144,21 @@ class OCShareDaoTest { fun insertSharesFromDifferentAccountsAndRead() { ocShareDao.insert( listOf( - DataTestUtil.createPublicShare( + DataTestUtil.createPublicShareEntity( path = "/Documents/document1.docx", isFolder = false, accountOwner = "user1@server", name = "Document 1 link", shareLink = "http://server:port/s/1" ), - DataTestUtil.createPublicShare( + DataTestUtil.createPublicShareEntity( path = "/Documents/document1.docx", isFolder = false, accountOwner = "user2@server", name = "Document 1 link", shareLink = "http://server:port/s/2" ), - DataTestUtil.createPrivateShare( + DataTestUtil.createPrivateShareEntity( path = "/Documents/document1.docx", isFolder = false, accountOwner = "user3@server", @@ -207,13 +208,56 @@ class OCShareDaoTest { assertEquals("Patrick", document1PrivateSharesForUser3[0].sharedWithDisplayName) } + @Test + fun testAutogenerationId() { + ocShareDao.insert( + listOf( + DataTestUtil.createPublicShareEntity( + path = "/Documents/document1.docx", + isFolder = false, + accountOwner = "user1@server", + name = "Document 1 link", + shareLink = "http://server:port/s/1" + ), + DataTestUtil.createPublicShareEntity( + path = "/Documents/document1.docx", + isFolder = false, + accountOwner = "user1@server", + name = "Document 1 link", + shareLink = "http://server:port/s/1" + ) + ) + ) + + val sharesWithSameValues = getValue( + ocShareDao.getSharesAsLiveData( + "/Documents/document1.docx", "user1@server", listOf(ShareType.PUBLIC_LINK.value) + ) + ) + assertNotNull(sharesWithSameValues) + assertEquals(2, sharesWithSameValues.size) + assertEquals("/Documents/document1.docx", sharesWithSameValues[0].path) + assertEquals("/Documents/document1.docx", sharesWithSameValues[1].path) + assertEquals(false, sharesWithSameValues[0].isFolder) + assertEquals(false, sharesWithSameValues[1].isFolder) + assertEquals("user1@server", sharesWithSameValues[0].accountOwner) + assertEquals("user1@server", sharesWithSameValues[1].accountOwner) + assertEquals("Document 1 link", sharesWithSameValues[0].name) + assertEquals("Document 1 link", sharesWithSameValues[1].name) + assertEquals("http://server:port/s/1", sharesWithSameValues[0].shareLink) + assertEquals("http://server:port/s/1", sharesWithSameValues[1].shareLink) + assertNotNull(sharesWithSameValues[0].id) + assertNotNull(sharesWithSameValues[1].id) + assert(sharesWithSameValues[0].id != sharesWithSameValues[1].id) + } + /****************************************************************************************************** ******************************************* PRIVATE SHARES ******************************************* ******************************************************************************************************/ @Test fun getNonExistingPrivateShare() { - val privateShare = createDefaultPrivateShare() + val privateShare = createDefaultPrivateShareEntity() ocShareDao.insert(privateShare) @@ -228,11 +272,11 @@ class OCShareDaoTest { @Test fun replacePrivateShareIfAlreadyExists_exists() { - val privateShare = createDefaultPrivateShare() + val privateShare = createDefaultPrivateShareEntity() - ocShareDao.insert(createDefaultPrivateShare()) + ocShareDao.insert(createDefaultPrivateShareEntity()) - val privateShareToReplace = createDefaultPrivateShare(shareWith = "userName") + val privateShareToReplace = createDefaultPrivateShareEntity(shareWith = "userName") ocShareDao.replaceShares( listOf(privateShareToReplace) @@ -250,13 +294,13 @@ class OCShareDaoTest { @Test fun replacePrivateShareIfAlreadyExists_doesNotExist() { - val privateShare = createDefaultPrivateShare( + val privateShare = createDefaultPrivateShareEntity( shareType = ShareType.GROUP.value ) ocShareDao.insert(privateShare) - val privateShareToReplace = createDefaultPrivateShare( + val privateShareToReplace = createDefaultPrivateShareEntity( shareType = ShareType.GROUP.value, shareWith = "userName", path = "/Texts/text2.txt" @@ -288,12 +332,12 @@ class OCShareDaoTest { @Test fun updatePrivateShare() { - val privateShare = createDefaultPrivateShare() + val privateShare = createDefaultPrivateShareEntity() ocShareDao.insert(privateShare) ocShareDao.update( - createDefaultPrivateShare(permissions = 17) + createDefaultPrivateShareEntity(permissions = 17) ) val textShares = getValue( @@ -309,9 +353,9 @@ class OCShareDaoTest { @Test fun deletePrivateShare() { - val privateShare = createDefaultPrivateShare() + val privateShare = createDefaultPrivateShareEntity() - ocShareDao.insert(createDefaultPrivateShare()) + ocShareDao.insert(createDefaultPrivateShareEntity()) ocShareDao.deleteShare(privateShare.remoteId) @@ -324,13 +368,13 @@ class OCShareDaoTest { assertEquals(0, textShares.size) // List of textShares empty after deleting the existing share } - private fun createDefaultPrivateShare( + private fun createDefaultPrivateShareEntity( shareType: Int = 0, shareWith: String = "username", path: String = "/Texts/text1.txt", permissions: Int = -1, shareWithDisplayName: String = "Steve" - ) = DataTestUtil.createPrivateShare( + ) = DataTestUtil.createPrivateShareEntity( shareType = shareType, shareWith = shareWith, path = path, @@ -345,7 +389,7 @@ class OCShareDaoTest { @Test fun getNonExistingPublicShare() { - val publicShare = createDefaultPublicShare() + val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) @@ -360,11 +404,11 @@ class OCShareDaoTest { @Test fun replacePublicShareIfAlreadyExists_exists() { - val publicShare = createDefaultPublicShare() + val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) - val publicShareToReplace = createDefaultPublicShare(name = "Text 2 link") + val publicShareToReplace = createDefaultPublicShareEntity(name = "Text 2 link") ocShareDao.replaceShares( listOf(publicShareToReplace) @@ -382,11 +426,11 @@ class OCShareDaoTest { @Test fun replacePublicShareIfAlreadyExists_doesNotExist() { - val publicShare = createDefaultPublicShare() + val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) - val publicShareToReplace = createDefaultPublicShare(path = "/Texts/text2.txt", name = "Text 2 link") + val publicShareToReplace = createDefaultPublicShareEntity(path = "/Texts/text2.txt", name = "Text 2 link") ocShareDao.replaceShares( listOf(publicShareToReplace) @@ -414,11 +458,11 @@ class OCShareDaoTest { @Test fun updatePublicShare() { - val publicShare = createDefaultPublicShare() + val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) - val publicShareToUpdate = createDefaultPublicShare(name = "Text 1 link updated", expirationDate = 2000) + val publicShareToUpdate = createDefaultPublicShareEntity(name = "Text 1 link updated", expirationDate = 2000) ocShareDao.update(publicShareToUpdate) @@ -435,7 +479,7 @@ class OCShareDaoTest { @Test fun deletePublicShare() { - val publicShare = createDefaultPublicShare() + val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) @@ -450,11 +494,11 @@ class OCShareDaoTest { assertEquals(0, textShares.size) // List of textShares empty after deleting the existing share } - private fun createDefaultPublicShare( + private fun createDefaultPublicShareEntity( path: String = "/Texts/text1.txt", expirationDate: Long = 1000, name: String = "Text 1 link" - ) = DataTestUtil.createPublicShare( + ) = DataTestUtil.createPublicShareEntity( path = path, expirationDate = expirationDate, isFolder = false, diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/implementation/OCLocalCapabilitiesDataSource.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/implementation/OCLocalCapabilitiesDataSource.kt index f9e6555bde0..6ec198a07a3 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/implementation/OCLocalCapabilitiesDataSource.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/implementation/OCLocalCapabilitiesDataSource.kt @@ -37,7 +37,7 @@ class OCLocalCapabilitiesDataSource( } override fun getCapabilityForAccount(accountName: String): OCCapability? = - ocCapabilityMapper.toModel(ocCapabilityDao.getCapabilityForAccount(accountName)) + ocCapabilityMapper.toModel(ocCapabilityDao.getCapabilitiesForAccount(accountName)) override fun insert(ocCapabilities: List) { ocCapabilityDao.replace( diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityDao.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityDao.kt index d0e8aa02064..b37b833906f 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityDao.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityDao.kt @@ -42,7 +42,7 @@ abstract class OCCapabilityDao { "SELECT * from " + ProviderTableMeta.CAPABILITIES_TABLE_NAME + " WHERE " + ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + " = :accountName" ) - abstract fun getCapabilityForAccount( + abstract fun getCapabilitiesForAccount( accountName: String ): OCCapabilityEntity From b5553b184b8e5be6126da72b73d5de20e8a26465 Mon Sep 17 00:00:00 2001 From: davigonz Date: Mon, 18 Nov 2019 14:27:47 +0100 Subject: [PATCH 06/41] Domain module tests --- .../OCRemoteShareesDataSourceTest.kt | 2 + .../repository/OCShareRepositoryTest.kt | 8 +- .../sharing/sharees/OCShareeRepositoryTest.kt | 115 --- .../sharees/RemoteShareesDataSourceTest.kt | 37 - .../android/domain/utils/DomainTestUtil.kt | 353 ++-------- .../android/domain/utils/LiveDataTestUtil.kt | 41 -- .../capabilities/model/OCCapabilityTest.kt | 260 +++++++ .../GetCapabilitiesAsLiveDataUseCaseTest.kt | 71 ++ ...hCapabilitiesFromServerAsyncUseCaseTest.kt | 60 ++ .../domain/shares/OCShareRepositoryTest.kt | 664 ------------------ .../shares/RemoteSharesDataSourceTest.kt | 73 -- .../domain/shares/model/OCShareTest.kt | 267 +++++++ .../CreatePrivateShareAsyncUseCaseTest.kt | 88 +++ .../CreatePublicShareAsyncUseCaseTest.kt | 99 +++ .../usecases/DeleteShareAsyncUseCaseTest.kt | 64 ++ .../EditPrivateShareAsyncUseCaseTest.kt | 65 ++ .../EditPublicShareAsyncUseCaseTest.kt | 74 ++ .../usecases/GetShareAsLiveDataUseCaseTest.kt | 73 ++ .../GetSharesAsLiveDataUseCaseTest.kt | 73 ++ ...RefreshSharesFromServerAsyncUseCaseTest.kt | 59 ++ .../android/domain/utils/InstantExecutors.kt | 26 - 21 files changed, 1312 insertions(+), 1260 deletions(-) delete mode 100644 owncloudDomain/src/androidTest/java/com/owncloud/android/domain/sharing/sharees/OCShareeRepositoryTest.kt delete mode 100644 owncloudDomain/src/androidTest/java/com/owncloud/android/domain/sharing/sharees/RemoteShareesDataSourceTest.kt delete mode 100644 owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/LiveDataTestUtil.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetCapabilitiesAsLiveDataUseCaseTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/RefreshCapabilitiesFromServerAsyncUseCaseTest.kt delete mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/OCShareRepositoryTest.kt delete mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/RemoteSharesDataSourceTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/model/OCShareTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/CreatePrivateShareAsyncUseCaseTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/CreatePublicShareAsyncUseCaseTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/DeleteShareAsyncUseCaseTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/EditPrivateShareAsyncUseCaseTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/EditPublicShareAsyncUseCaseTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetShareAsLiveDataUseCaseTest.kt create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetSharesAsLiveDataUseCaseTest.kt delete mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/utils/InstantExecutors.kt diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt index e861827ddc8..d8207934f9f 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt @@ -30,6 +30,7 @@ import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat import org.json.JSONObject import org.junit.Before +import org.junit.Ignore import org.junit.Test // Needs to be instrumented since JSONObject is tied to the Android platform @@ -43,6 +44,7 @@ class OCRemoteShareesDataSourceTest { OCRemoteShareeDataSource(ocShareeService) } + @Ignore("We need first to address https://github.com/owncloud/android/issues/2704 to properly test this") @Test fun readRemoteSharees() { val remoteSharees: ArrayList = arrayListOf( diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt index 70045a51642..d90f3ad886e 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt @@ -105,7 +105,7 @@ class OCShareRepositoryTest { } @Test - fun getStoredSharesOk() { + fun getSharesAsLiveDataOk() { val sharesLiveData = MutableLiveData>() every { @@ -126,7 +126,7 @@ class OCShareRepositoryTest { } @Test(expected = Exception::class) - fun getStoredSharesException() { + fun getSharesAsLiveDataException() { val sharesLiveData = MutableLiveData>() every { @@ -145,7 +145,7 @@ class OCShareRepositoryTest { } @Test - fun getStoredShareOk() { + fun getShareAsLiveDataOk() { val shareLiveData = MutableLiveData() every { @@ -167,7 +167,7 @@ class OCShareRepositoryTest { } @Test(expected = Exception::class) - fun getStoredShareException() { + fun getShareAsLiveDataException() { val shareLiveData = MutableLiveData() every { diff --git a/owncloudDomain/src/androidTest/java/com/owncloud/android/domain/sharing/sharees/OCShareeRepositoryTest.kt b/owncloudDomain/src/androidTest/java/com/owncloud/android/domain/sharing/sharees/OCShareeRepositoryTest.kt deleted file mode 100644 index c5b82d7fb31..00000000000 --- a/owncloudDomain/src/androidTest/java/com/owncloud/android/domain/sharing/sharees/OCShareeRepositoryTest.kt +++ /dev/null @@ -1,115 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.domain.sharing.sharees - -import com.owncloud.android.domain.utils.DomainTestUtil -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation -import junit.framework.Assert.assertEquals -import org.json.JSONObject -import org.junit.Test - -class OCShareeRepositoryTest { - @Test - fun loadShareesFromNetworkSuccessfully() { - val remoteSharees: ArrayList = arrayListOf( - DomainTestUtil.createSharee("Thor", "0", "thor", "thor@avengers.com"), - DomainTestUtil.createSharee("Iron Man", "0", "ironman", "ironman@avengers.com"), - DomainTestUtil.createSharee("Avengers", "1", "avengers", "everybody@avengers.com") - ) - - val getRemoteShareesOperationResult = - DomainTestUtil.createRemoteOperationResultMock(arrayListOf(remoteSharees[1]), true) - - val ocShareeRepository = createShareeRepositoryWithRemoteDataSource(getRemoteShareesOperationResult) - - val resource = ocShareeRepository.getSharees( - "Iron", - 1, - 30 - ) - - assertEquals(resource.code, RemoteOperationResult.ResultCode.OK) - - assertEquals(resource.data?.get(0)?.getString(GetRemoteShareesOperation.PROPERTY_LABEL), "Iron Man") - val value = resource.data?.get(0)?.getJSONObject(GetRemoteShareesOperation.NODE_VALUE) - assertEquals(value?.getString(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE), "0") - assertEquals(value?.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH), "ironman") - assertEquals( - value?.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO), - "ironman@avengers.com" - ) - } - - @Test - fun loadEmptyShareesFromNetwork() { - val remoteSharees: ArrayList = arrayListOf() - - val getRemoteShareesOperationResult = - DomainTestUtil.createRemoteOperationResultMock(remoteSharees, true) - - val ocShareeRepository = createShareeRepositoryWithRemoteDataSource(getRemoteShareesOperationResult) - - val resource = ocShareeRepository.getSharees( - "Thor", - 1, - 30 - ) - - assertEquals(resource.code, RemoteOperationResult.ResultCode.OK) - assertEquals(resource.data?.size, 0) - } - - @Test - fun loadEmptyShareesFromNetworkWithError() { - val remoteSharees: ArrayList = arrayListOf( - DomainTestUtil.createSharee("Joker", "0", "joker", "joker@dc.com") - ) - - val exception = Exception("Error when retrieving sharees") - - val getRemoteShareesOperationResult = - DomainTestUtil.createRemoteOperationResultMock( - remoteSharees, - false, - resultCode = RemoteOperationResult.ResultCode.HOST_NOT_AVAILABLE, - exception = exception - ) - - val ocShareeRepository = createShareeRepositoryWithRemoteDataSource(getRemoteShareesOperationResult) - - val resource = ocShareeRepository.getSharees( - "Joker", - 1, - 30 - ) - - assertEquals(resource.code, RemoteOperationResult.ResultCode.HOST_NOT_AVAILABLE) - assertEquals(resource.exception?.message, exception.message) - } - - private fun createShareeRepositoryWithRemoteDataSource( - getRemoteShareesOperationResult: RemoteOperationResult> - ): OCShareeRepository { - val remoteShareesDataSource = RemoteShareesDataSourceTest(getRemoteShareesOperationResult) - - return OCShareeRepository(remoteShareesDataSource) - } -} diff --git a/owncloudDomain/src/androidTest/java/com/owncloud/android/domain/sharing/sharees/RemoteShareesDataSourceTest.kt b/owncloudDomain/src/androidTest/java/com/owncloud/android/domain/sharing/sharees/RemoteShareesDataSourceTest.kt deleted file mode 100644 index d117f421d99..00000000000 --- a/owncloudDomain/src/androidTest/java/com/owncloud/android/domain/sharing/sharees/RemoteShareesDataSourceTest.kt +++ /dev/null @@ -1,37 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ -package com.owncloud.android.domain.sharing.sharees - -import com.owncloud.android.data.sharing.sharees.datasources.RemoteShareeDataSource -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation -import org.json.JSONObject - -class RemoteShareesDataSourceTest( - private val remoteOperationResult: RemoteOperationResult> -) : RemoteShareeDataSource { - override fun getSharees( - searchString: String, - page: Int, - perPage: Int, - getRemoteShareesOperation: GetRemoteShareesOperation - ): RemoteOperationResult> { - return remoteOperationResult - } -} diff --git a/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/DomainTestUtil.kt b/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/DomainTestUtil.kt index 32d66f1165f..3ca719db426 100644 --- a/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/DomainTestUtil.kt +++ b/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/DomainTestUtil.kt @@ -19,315 +19,68 @@ package com.owncloud.android.domain.utils -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation -import com.owncloud.android.lib.resources.shares.RemoteShare -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.RemoteCapability -import io.mockk.every -import io.mockk.mockk -import org.json.JSONObject +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType +import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.model.ShareType object DomainTestUtil { /** * Shares */ - private fun createShare( - fileSource: Long = 7, - itemSource: Long = 7, - shareType: Int, // Public share by default - shareWith: String = "", - path: String, - permissions: Int = 1, - sharedDate: Long = 1542628397, - expirationDate: Long = 0, - token: String = "pwdasd12dasdWZ", - sharedWithDisplayName: String = "", - sharedWithAdditionalInfo: String = "", - isFolder: Boolean, - userId: Long = -1, - remoteId: Long = 1, - accountOwner: String = "admin@server", - name: String = "", - shareLink: String = "" - ) = OCShareEntity( - fileSource, - itemSource, - shareType, - shareWith, - path, - permissions, - sharedDate, - expirationDate, - token, - sharedWithDisplayName, - sharedWithAdditionalInfo, - isFolder, - userId, - remoteId, - accountOwner, - name, - shareLink - ) - - fun createPrivateShare( - shareType: Int = 0, - shareWith: String, - path: String, - isFolder: Boolean, - sharedWithDisplayName: String, - accountOwner: String = "admin@server" - ) = createShare( - shareType = shareType, - shareWith = shareWith, - path = path, - isFolder = isFolder, - sharedWithDisplayName = sharedWithDisplayName, - accountOwner = accountOwner - ) - fun createPublicShare( - shareWith: String = "", - path: String, - expirationDate: Long = 1000, - isFolder: Boolean, - permissions: Int = 1, - remoteId: Long = 1, - accountOwner: String = "admin@server", - name: String, - shareLink: String - ) = createShare( - shareWith = shareWith, - shareType = 3, - path = path, - permissions = permissions, - expirationDate = expirationDate, - isFolder = isFolder, - remoteId = remoteId, - accountOwner = accountOwner, - name = name, - shareLink = shareLink + val DUMMY_SHARE = OCShare( + fileSource = 7, + itemSource = 7, + shareType = ShareType.USER, // Public share by default + shareWith = "", + path = "/Photos/image.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "AnyToken", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = "", + shareLink = "" ) - fun createRemoteShare( - fileSource: Long = 7, - itemSource: Long = 7, - shareType: Int, // Public share by default - shareWith: String = "", - path: String, - permissions: Int = 1, - sharedDate: Long = 1542628397, - expirationDate: Long = 0, - token: String = "pwdasd12dasdWZ", - sharedWithDisplayName: String = "", - isFolder: Boolean, - userId: Long = -1, - remoteId: Long = 1, - name: String = "", - shareLink: String = "" - ): RemoteShare { - val remoteShare = RemoteShare(); - - remoteShare.fileSource = fileSource - remoteShare.itemSource = itemSource - remoteShare.shareType = ShareType.fromValue(shareType) - remoteShare.shareWith = shareWith - remoteShare.path = path - remoteShare.permissions = permissions - remoteShare.sharedDate = sharedDate - remoteShare.expirationDate = expirationDate - remoteShare.token = token - remoteShare.sharedWithDisplayName = sharedWithDisplayName - remoteShare.isFolder = isFolder - remoteShare.userId = userId - remoteShare.id = remoteId - remoteShare.name = name - remoteShare.shareLink = shareLink - - return remoteShare - } - - /** - * Sharees - */ - fun createSharee( - label: String, - shareType: String, - shareWith: String, - shareWithAdditionalInfo: String - ): JSONObject { - val jsonObject = JSONObject() - - jsonObject.put(GetRemoteShareesOperation.PROPERTY_LABEL, label) - - val value = JSONObject() - value.put(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE, shareType) - value.put(GetRemoteShareesOperation.PROPERTY_SHARE_WITH, shareWith) - value.put(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO, shareWithAdditionalInfo) - - jsonObject.put(GetRemoteShareesOperation.NODE_VALUE, value) - - return jsonObject - } - /** * Capability */ - fun createCapability( - accountName: String = "user@server", - versionMayor: Int = 2, - versionMinor: Int = 1, - versionMicro: Int = 0, - versionString: String = "1.0.0", - versionEdition: String = "1.0.0", - corePollinterval: Int = 0, - sharingApiEnabled: Int = 0, - sharingPublicEnabled: Int = 1, - sharingPublicPasswordEnforced: Int = 0, - sharingPublicPasswordEnforcedReadOnly: Int = 0, - sharingPublicPasswordEnforcedReadWrite: Int = 0, - sharingPublicPasswordEnforcedUploadOnly: Int = 0, - sharingPublicExpireDateEnabled: Int = 0, - sharingPublicExpireDateDays: Int = 0, - sharingPublicExpireDateEnforced: Int = 0, - sharingPublicSendMail: Int = 0, - sharingPublicUpload: Int = 0, - sharingPublicMultiple: Int = 0, - sharingPublicSupportsUploadOnly: Int = 0, - sharingUserSendMail: Int = 0, - sharingResharing: Int = 0, - sharingFederationOutgoing: Int = 0, - sharingFederationIncoming: Int = 0, - filesBigFileChunking: Int = 0, - filesUndelete: Int = 0, - filesVersioning: Int = 0 - ) = OCCapabilityEntity( - accountName, - versionMayor, - versionMinor, - versionMicro, - versionString, - versionEdition, - corePollinterval, - sharingApiEnabled, - sharingPublicEnabled, - sharingPublicPasswordEnforced, - sharingPublicPasswordEnforcedReadOnly, - sharingPublicPasswordEnforcedReadWrite, - sharingPublicPasswordEnforcedUploadOnly, - sharingPublicExpireDateEnabled, - sharingPublicExpireDateDays, - sharingPublicExpireDateEnforced, - sharingPublicSendMail, - sharingPublicUpload, - sharingPublicMultiple, - sharingPublicSupportsUploadOnly, - sharingUserSendMail, - sharingResharing, - sharingFederationOutgoing, - sharingFederationIncoming, - filesBigFileChunking, - filesUndelete, - filesVersioning - ) - - fun createRemoteCapability( - accountName: String = "user@server", - versionMayor: Int = 2, - versionMinor: Int = 1, - versionMicro: Int = 0, - versionString: String = "1.0.0", - versionEdition: String = "1.0.0", - corePollinterval: Int = 0, - sharingApiEnabled: Int = 0, - sharingPublicEnabled: Int = 1, - sharingPublicPasswordEnforced: Int = 0, - sharingPublicPasswordEnforcedReadOnly: Int = 0, - sharingPublicPasswordEnforcedReadWrite: Int = 0, - sharingPublicPasswordEnforcedUploadOnly: Int = 0, - sharingPublicExpireDateEnabled: Int = 0, - sharingPublicExpireDateDays: Int = 0, - sharingPublicExpireDateEnforced: Int = 0, - sharingPublicSendMail: Int = 0, - sharingPublicUpload: Int = 0, - sharingPublicMultiple: Int = 0, - sharingPublicSupportsUploadOnly: Int = 0, - sharingUserSendMail: Int = 0, - sharingResharing: Int = 0, - sharingFederationOutgoing: Int = 0, - sharingFederationIncoming: Int = 0, - filesBigFileChunking: Int = 0, - filesUndelete: Int = 0, - filesVersioning: Int = 0 - ): RemoteCapability = RemoteCapability().apply { - this.accountName = accountName - this.versionMayor = versionMayor - this.versionMinor = versionMinor - this.versionMicro = versionMicro - this.versionString = versionString - this.versionEdition = versionEdition - this.corePollinterval = corePollinterval - filesSharingApiEnabled = CapabilityBooleanType.fromValue(sharingApiEnabled)!! - filesSharingPublicEnabled = CapabilityBooleanType.fromValue(sharingPublicEnabled)!! - filesSharingPublicPasswordEnforced = CapabilityBooleanType.fromValue(sharingPublicPasswordEnforced)!! - filesSharingPublicPasswordEnforcedReadOnly = - CapabilityBooleanType.fromValue(sharingPublicPasswordEnforcedReadOnly)!! - filesSharingPublicPasswordEnforcedReadWrite = - CapabilityBooleanType.fromValue(sharingPublicPasswordEnforcedReadWrite)!! - filesSharingPublicPasswordEnforcedUploadOnly = - CapabilityBooleanType.fromValue(sharingPublicPasswordEnforcedUploadOnly)!! - filesSharingPublicExpireDateEnabled = CapabilityBooleanType.fromValue(sharingPublicExpireDateEnabled)!! - filesSharingPublicExpireDateDays = sharingPublicExpireDateDays - filesSharingPublicExpireDateEnforced = CapabilityBooleanType.fromValue(sharingPublicExpireDateEnforced)!! - filesSharingPublicSendMail = CapabilityBooleanType.fromValue(sharingPublicSendMail)!! - filesSharingPublicUpload = CapabilityBooleanType.fromValue(sharingPublicUpload)!! - filesSharingPublicMultiple = CapabilityBooleanType.fromValue(sharingPublicMultiple)!! - filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.fromValue(sharingPublicSupportsUploadOnly)!! - filesSharingUserSendMail = CapabilityBooleanType.fromValue(sharingUserSendMail)!! - filesSharingResharing = CapabilityBooleanType.fromValue(sharingResharing)!! - filesSharingFederationOutgoing = CapabilityBooleanType.fromValue(sharingFederationOutgoing)!! - filesSharingFederationIncoming = CapabilityBooleanType.fromValue(sharingFederationIncoming)!! - this.filesBigFileChunking = CapabilityBooleanType.fromValue(filesBigFileChunking)!! - this.filesUndelete = CapabilityBooleanType.fromValue(filesUndelete)!! - this.filesVersioning = CapabilityBooleanType.fromValue(filesVersioning)!! - } - - fun createRemoteOperationResultMock( - data: T, - isSuccess: Boolean, - httpPhrase: String? = null, - resultCode: RemoteOperationResult.ResultCode? = null, - exception: Exception? = null - ): RemoteOperationResult { - val remoteOperationResult = mockk>(relaxed = true) - - every { - remoteOperationResult.data - } returns data - - every { - remoteOperationResult.isSuccess - } returns isSuccess - - every { - remoteOperationResult.httpPhrase - } returns httpPhrase - - if (resultCode != null) { - every { - remoteOperationResult.code - } returns resultCode - } - - if (exception != null) { - every { - remoteOperationResult.exception - } returns exception - } - - return remoteOperationResult - } + val DUMMY_CAPABILITY = + OCCapability( + accountName = "user@server", + versionMayor = 2, + versionMinor = 1, + versionMicro = 0, + versionString = "1.0.0", + versionEdition = "1.0.0", + corePollInterval = 0, + filesSharingApiEnabled = CapabilityBooleanType.TRUE, + filesSharingSearchMinLength = 3, + filesSharingPublicEnabled = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicExpireDateEnabled = CapabilityBooleanType.FALSE, + filesSharingPublicExpireDateDays = 0, + filesSharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE, + filesSharingPublicSendMail = CapabilityBooleanType.FALSE, + filesSharingPublicUpload = CapabilityBooleanType.FALSE, + filesSharingPublicMultiple = CapabilityBooleanType.FALSE, + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.FALSE, + filesSharingUserSendMail = CapabilityBooleanType.FALSE, + filesSharingResharing = CapabilityBooleanType.FALSE, + filesSharingFederationOutgoing = CapabilityBooleanType.FALSE, + filesSharingFederationIncoming = CapabilityBooleanType.FALSE, + filesBigFileChunking = CapabilityBooleanType.FALSE, + filesUndelete = CapabilityBooleanType.FALSE, + filesVersioning = CapabilityBooleanType.FALSE + ) } diff --git a/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/LiveDataTestUtil.kt b/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/LiveDataTestUtil.kt deleted file mode 100644 index d06492e2c30..00000000000 --- a/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/LiveDataTestUtil.kt +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.owncloud.android.domain.utils - -import androidx.lifecycle.LiveData -import androidx.lifecycle.Observer -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit - -object LiveDataTestUtil { - fun getValue(liveData: LiveData): T { - val data = arrayOfNulls(1) - val latch = CountDownLatch(1) - val observer = object : Observer { - override fun onChanged(o: T?) { - data[0] = o - latch.countDown() - liveData.removeObserver(this) - } - } - liveData.observeForever(observer) - latch.await(2, TimeUnit.SECONDS) - - @Suppress("UNCHECKED_CAST") - return data[0] as T - } -} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt new file mode 100644 index 00000000000..1d9b8789ada --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt @@ -0,0 +1,260 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.capabilities.model + +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType.Companion.fromBooleanValue +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType.FALSE +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType.TRUE +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType.UNKNOWN +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType.Companion.fromValue + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class OCCapabilityTest { + @Test + fun testConstructor() { + val item = OCCapability( + 123, + "user@server", + 2, + 1, + 0, + "1.0.0", + "1.0.0", + 0, + TRUE, + 3, + TRUE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + 0, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE + ) + + assertEquals(123, item.id) + assertEquals("user@server", item.accountName) + assertEquals(2, item.versionMayor) + assertEquals(1, item.versionMinor) + assertEquals(0, item.versionMicro) + assertEquals("1.0.0", item.versionString) + assertEquals("1.0.0", item.versionEdition) + assertEquals(0, item.corePollInterval) + assertEquals(TRUE, item.filesSharingApiEnabled) + assertEquals(TRUE, item.filesSharingPublicEnabled) + assertEquals(FALSE, item.filesSharingPublicPasswordEnforced) + assertEquals(FALSE, item.filesSharingPublicPasswordEnforcedReadOnly) + assertEquals(FALSE, item.filesSharingPublicPasswordEnforcedReadWrite) + assertEquals(FALSE, item.filesSharingPublicPasswordEnforcedUploadOnly) + assertEquals(FALSE, item.filesSharingPublicExpireDateEnabled) + assertEquals(0, item.filesSharingPublicExpireDateDays) + assertEquals(FALSE, item.filesSharingPublicExpireDateEnforced) + assertEquals(FALSE, item.filesSharingPublicSendMail) + assertEquals(FALSE, item.filesSharingPublicUpload) + assertEquals(FALSE, item.filesSharingPublicMultiple) + assertEquals(FALSE, item.filesSharingPublicSupportsUploadOnly) + assertEquals(FALSE, item.filesSharingUserSendMail) + assertEquals(FALSE, item.filesSharingResharing) + assertEquals(FALSE, item.filesSharingFederationOutgoing) + assertEquals(FALSE, item.filesSharingFederationIncoming) + assertEquals(FALSE, item.filesBigFileChunking) + assertEquals(FALSE, item.filesUndelete) + assertEquals(FALSE, item.filesVersioning) + } + + @Test + fun testEqualsOk() { + val item1 = OCCapability( + id = 123, + accountName = "user@server", + versionMayor = 2, + versionMinor = 1, + versionMicro = 0, + versionString = "1.0.0", + versionEdition = "1.0.0", + corePollInterval = 0, + filesSharingApiEnabled = TRUE, + filesSharingPublicEnabled = TRUE, + filesSharingPublicPasswordEnforced = FALSE, + filesSharingPublicPasswordEnforcedReadOnly = FALSE, + filesSharingPublicPasswordEnforcedReadWrite = FALSE, + filesSharingPublicPasswordEnforcedUploadOnly = FALSE, + filesSharingPublicExpireDateEnabled = FALSE, + filesSharingPublicExpireDateDays = 0, + filesSharingPublicExpireDateEnforced = FALSE, + filesSharingPublicSendMail = FALSE, + filesSharingPublicUpload = FALSE, + filesSharingPublicMultiple = FALSE, + filesSharingPublicSupportsUploadOnly = FALSE, + filesSharingUserSendMail = FALSE, + filesSharingResharing = FALSE, + filesSharingFederationOutgoing = FALSE, + filesSharingFederationIncoming = FALSE, + filesBigFileChunking = FALSE, + filesUndelete = FALSE, + filesVersioning = FALSE + ) + + val item2 = OCCapability( + 123, + "user@server", + 2, + 1, + 0, + "1.0.0", + "1.0.0", + 0, + TRUE, + 3, + TRUE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + 0, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE + ) + + assertTrue(item1 == item2) + assertFalse(item1 === item2) + } + + @Test + fun testEqualsKo() { + val item1 = OCCapability( + id = 123, + accountName = "admin@server", + versionMayor = 2, + versionMinor = 1, + versionMicro = 0, + versionString = "1.0.0", + versionEdition = "1.0.0", + corePollInterval = 0, + filesSharingApiEnabled = TRUE, + filesSharingPublicEnabled = TRUE, + filesSharingPublicPasswordEnforced = FALSE, + filesSharingPublicPasswordEnforcedReadOnly = FALSE, + filesSharingPublicPasswordEnforcedReadWrite = FALSE, + filesSharingPublicPasswordEnforcedUploadOnly = FALSE, + filesSharingPublicExpireDateEnabled = FALSE, + filesSharingPublicExpireDateDays = 0, + filesSharingPublicExpireDateEnforced = FALSE, + filesSharingPublicSendMail = FALSE, + filesSharingPublicUpload = FALSE, + filesSharingPublicMultiple = FALSE, + filesSharingPublicSupportsUploadOnly = FALSE, + filesSharingUserSendMail = FALSE, + filesSharingResharing = FALSE, + filesSharingFederationOutgoing = FALSE, + filesSharingFederationIncoming = FALSE, + filesBigFileChunking = FALSE, + filesUndelete = FALSE, + filesVersioning = FALSE + ) + + val item2 = OCCapability( + 123, + "user@server", + 2, + 1, + 0, + "1.0.0", + "1.0.0", + 0, + TRUE, + 3, + TRUE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + 0, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE, + FALSE + ) + + assertFalse(item1 == item2) + assertFalse(item1 === item2) + } + + @Test + fun testCapabilityBooleanType() { + val fromValueUnknownType = fromValue(-1) + val fromValueFalseType = fromValue(0) + val fromValueTrueType = fromValue(1) + val fromValueDifferentValue = fromValue(2) + val fromBooleanTrue = fromBooleanValue(true) + val fromBooleanFalse = fromBooleanValue(false) + val capabilityUnknown = UNKNOWN + val capabilityFalse = FALSE + val capabilityTrue = TRUE + + assertEquals(UNKNOWN, fromValueUnknownType) + assertEquals(FALSE, fromValueFalseType) + assertEquals(TRUE, fromValueTrueType) + assertNull(fromValueDifferentValue) + assertEquals(TRUE, fromBooleanTrue) + assertEquals(FALSE, fromBooleanFalse) + assertEquals(true, capabilityUnknown.isUnknown) + assertEquals(false, capabilityUnknown.isTrue) + assertEquals(true, capabilityFalse.isFalse) + assertEquals(true, capabilityTrue.isTrue) + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetCapabilitiesAsLiveDataUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetCapabilitiesAsLiveDataUseCaseTest.kt new file mode 100644 index 00000000000..b9519c0a9eb --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetCapabilitiesAsLiveDataUseCaseTest.kt @@ -0,0 +1,71 @@ + +/** + * ownCloud Android client application + * + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.capabilities.usecases + +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.lifecycle.MutableLiveData +import com.owncloud.android.domain.capabilities.CapabilityRepository +import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.domain.utils.DomainTestUtil +import io.mockk.every +import io.mockk.spyk +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test + +class GetCapabilitiesAsLiveDataUseCaseTest { + @Rule + @JvmField + var instantTaskExecutorRule = InstantTaskExecutorRule() + + private val capabilityRepository: CapabilityRepository = spyk() + private val useCase = GetCapabilitiesAsLiveDataUseCase((capabilityRepository)) + private val useCaseParams = GetCapabilitiesAsLiveDataUseCase.Params("") + private lateinit var capabilitiesEmitted: MutableList + + @Before + fun init() { + capabilitiesEmitted = mutableListOf() + } + + @Test + fun getCapabilitiesAsLiveDataOk() { + val capabilitiesLiveData = MutableLiveData() + every { capabilityRepository.getCapabilitiesAsLiveData(any()) } returns capabilitiesLiveData + + val capabilitiesToEmit = listOf(DomainTestUtil.DUMMY_CAPABILITY) + + useCase.execute(useCaseParams).observeForever { + capabilitiesEmitted.add(it!!) + } + + capabilitiesToEmit.forEach { capabilitiesLiveData.postValue(it) } + + Assert.assertEquals(capabilitiesToEmit, capabilitiesEmitted) + } + + @Test(expected = Exception::class) + fun getCapabilitiesAsLiveDataException() { + every { capabilityRepository.getCapabilitiesAsLiveData(any()) } throws Exception() + useCase.execute(useCaseParams) + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/RefreshCapabilitiesFromServerAsyncUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/RefreshCapabilitiesFromServerAsyncUseCaseTest.kt new file mode 100644 index 00000000000..1eadd53e5e8 --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/RefreshCapabilitiesFromServerAsyncUseCaseTest.kt @@ -0,0 +1,60 @@ +/** + * ownCloud Android client application + * + * @author David González Verdugo + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.capabilities.usecases + +import com.owncloud.android.domain.capabilities.CapabilityRepository +import com.owncloud.android.domain.exceptions.UnauthorizedException +import io.mockk.every +import io.mockk.spyk +import io.mockk.verify +import org.junit.Assert +import org.junit.Test + +class RefreshCapabilitiesFromServerAsyncUseCaseTest { + private val capabilityRepository: CapabilityRepository = spyk() + private val useCase = RefreshCapabilitiesFromServerAsyncUseCase((capabilityRepository)) + private val useCaseParams = RefreshCapabilitiesFromServerAsyncUseCase.Params("") + + @Test + fun refreshCapabilitiesFromServerOk() { + val useCaseResult = useCase.execute(useCaseParams) + + Assert.assertTrue(useCaseResult.isSuccess) + Assert.assertFalse(useCaseResult.isError) + Assert.assertEquals(Unit, useCaseResult.getDataOrNull()) + + verify(exactly = 1) { capabilityRepository.refreshCapabilitiesForAccount("") } + } + + @Test + fun refreshCapabilitiesFromServerWithUnauthorizedException() { + every { capabilityRepository.refreshCapabilitiesForAccount(any()) } throws UnauthorizedException() + + val useCaseResult = useCase.execute(useCaseParams) + + Assert.assertFalse(useCaseResult.isSuccess) + Assert.assertTrue(useCaseResult.isError) + + Assert.assertNull(useCaseResult.getDataOrNull()) + Assert.assertTrue(useCaseResult.getThrowableOrNull() is UnauthorizedException) + + verify(exactly = 1) { capabilityRepository.refreshCapabilitiesForAccount("") } + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/OCShareRepositoryTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/OCShareRepositoryTest.kt deleted file mode 100644 index 04acbf25b2d..00000000000 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/OCShareRepositoryTest.kt +++ /dev/null @@ -1,664 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.domain.shares - -import androidx.arch.core.executor.testing.InstantTaskExecutorRule -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData -import androidx.lifecycle.Observer -import com.owncloud.android.data.DataResult -import com.owncloud.android.data.sharing.shares.datasources.LocalShareDataSource -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.domain.sharing.shares.OCShareRepository -import com.owncloud.android.domain.utils.DomainTestUtil -import com.owncloud.android.domain.utils.InstantExecutors -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.ShareParserResult -import com.owncloud.android.lib.resources.shares.ShareType -import io.mockk.every -import io.mockk.mockk -import io.mockk.verify -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.junit.runners.JUnit4 - -@RunWith(JUnit4::class) -class OCShareRepositoryTest { - @Rule - @JvmField - val instantExecutorRule = InstantTaskExecutorRule() - - private val defaultAccountName = "admin@server" - private val filePath = "/Photos/" - private val localSharesDataSource = mockk(relaxed = true) - - private val remoteShares = arrayListOf( - DomainTestUtil.createRemoteShare( - shareType = ShareType.PUBLIC_LINK.value, // Public share - path = filePath, - isFolder = true, - name = "Photos folder link", - shareLink = "http://server:port/s/1" - ), - DomainTestUtil.createRemoteShare( - shareType = ShareType.PUBLIC_LINK.value, // Public share - path = "${filePath}img", - isFolder = true, - name = "Photos folder link 1", - shareLink = "http://server:port/s/2" - ), - DomainTestUtil.createRemoteShare( - shareType = ShareType.PUBLIC_LINK.value, // Public share - path = filePath, - isFolder = true, - name = "Photos folder link 2", - shareLink = "http://server:port/s/3" - ), - DomainTestUtil.createRemoteShare( - shareType = ShareType.USER.value, // Private share - path = filePath, - permissions = 1, - isFolder = true, - shareWith = "username", - sharedWithDisplayName = "John" - ), - DomainTestUtil.createRemoteShare( - shareType = ShareType.GROUP.value, // Private share - path = filePath, - permissions = 3, - isFolder = true, - shareWith = "username2", - sharedWithDisplayName = "Sophie" - ) - ) - - /****************************************************************************************************** - ******************************************* PRIVATE SHARES ******************************************* - ******************************************************************************************************/ - - private val privateShare = listOf( - DomainTestUtil.createPrivateShare( - path = filePath, - isFolder = true, - shareWith = "username2", - sharedWithDisplayName = "Sophie" - ) - ) - - private val privateShareTypes = listOf( - ShareType.USER, ShareType.GROUP, ShareType.FEDERATED - ) - - @Test - fun loadPrivateSharesFromNetwork() { - val localData = MutableLiveData>() // Local shares - - val remoteOperationResult = - DomainTestUtil.createRemoteOperationResultMock(ShareParserResult(remoteShares), true) // Remote shares - - val privateSharesAsLiveData = loadPrivateSharesAsLiveData(localData, remoteOperationResult) - - val observer = mockk>>>(relaxed = true) - privateSharesAsLiveData.observeForever(observer) - - localData.postValue(null) - - // Get private shares from database to observe them, is called twice (one showing current db shares while - // getting shares from server and another one with db shares already updated with server ones) - verify(exactly = 2) { - localSharesDataSource.getSharesAsLiveData(filePath, defaultAccountName, privateShareTypes) - } - - // Retrieving shares from server... - - // Public shares are retrieved from server and inserted in database if not empty list - verify { - localSharesDataSource.replaceShares( - remoteShares.map { remoteShare -> - OCShareEntity.fromRemoteShare(remoteShare).also { it.accountOwner = defaultAccountName } - } - ) - } - - // Observe changes in database livedata when there's a new public share - localData.postValue( - privateShare - ) - - verify { - observer.onChanged(DataResult.success(privateShare)) - } - } - - @Test - fun loadEmptyPrivateSharesFromNetwork() { - val localData = MutableLiveData>() - - val remoteOperationResult = - DomainTestUtil.createRemoteOperationResultMock(ShareParserResult(arrayListOf()), true) - - val data = loadPrivateSharesAsLiveData(localData, remoteOperationResult) - val observer = mockk>>>(relaxed = true) - data.observeForever(observer) - - localData.postValue(null) - - // Get public shares from database to observe them, is called twice (one showing current db shares while - // getting shares from server and another one with db shares already updated with server ones) - verify(exactly = 2) { - localSharesDataSource.getSharesAsLiveData(filePath, defaultAccountName, privateShareTypes) - } - - // Retrieving public shares from server... - - // When there's no shares in server for a specific file, delete them locally - verify { - localSharesDataSource.deleteSharesForFile(filePath, defaultAccountName) - } - - // Observe changes in database livedata when the list of shares is empty - localData.postValue(listOf()) - - verify { - observer.onChanged(DataResult.success(listOf())) - } - } - - @Test - fun loadPrivateSharesFromNetworkWithError() { - val localData = MutableLiveData>() - localData.value = privateShare - - val exception = Exception("Error when retrieving shares") - - val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf()), - false, - resultCode = RemoteOperationResult.ResultCode.FORBIDDEN, - exception = exception - ) - - val data = loadPrivateSharesAsLiveData(localData, remoteOperationResult) - - // Get public shares from database to observe them - verify { - localSharesDataSource.getSharesAsLiveData(filePath, defaultAccountName, privateShareTypes) - } - - // Retrieving public shares from server... - - // Observe changes in database livedata when there's an error from server - val observer = mockk>>>(relaxed = true) - data.observeForever(observer) - - verify { - observer.onChanged( - DataResult.error( - RemoteOperationResult.ResultCode.FORBIDDEN, localData.value, exception = exception - ) - ) - } - } - - @Test - fun insertPrivateShareOnNetwork() { - val localData = MutableLiveData>() - localData.value = privateShare - - val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf(remoteShares[3])), true - ) - - val data = insertPrivateShare(localData, remoteOperationResult) - val observer = mockk>>(relaxed = true) - data.observeForever(observer) - - // Public shares are retrieved from server and inserted in database if not empty list - verify { - localSharesDataSource.insert( - arrayListOf(remoteShares[3]).map { remoteShare -> - OCShareEntity.fromRemoteShare(remoteShare).also { it.accountOwner = defaultAccountName } - } - ) - } - } - - @Test - fun insertPrivateShareOnNetworkWithError() { - val localData = MutableLiveData>() - localData.value = privateShare - - val exception = Exception("Error when retrieving shares") - - val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf()), - false, - resultCode = RemoteOperationResult.ResultCode.HOST_NOT_AVAILABLE, - exception = exception - ) - - val data = insertPrivateShare(localData, remoteOperationResult) - - // Observe changes in database livedata when there's an error from server - val observer = mockk>>(relaxed = true) - data.observeForever(observer) - - verify { - observer.onChanged( - DataResult.error( - RemoteOperationResult.ResultCode.HOST_NOT_AVAILABLE, exception = exception - ) - ) - } - } - - @Test - fun updatePrivateShareOnNetwork() { - val localData = MutableLiveData>() - localData.value = privateShare - - val remoteOperationResult = TestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf(remoteShares[3])), true - ) - - val data = updatePrivateShare(localData, remoteOperationResult) - - val observer = mock>>() - data.observeForever(observer) - - // Public shares are retrieved from server and updated in database - verify(localSharesDataSource).update( - OCShare.fromRemoteShare(remoteShares[3]).also { it.accountOwner = "admin@server" } - ) - } - - @Test - fun deletePrivateShareOnNetwork() { - val localData = MutableLiveData>() - localData.value = privateShare - - val remoteOperationResult = TestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf()), true - ) - - val data = deleteShare(localData, remoteOperationResult) - - val observer = mock>>() - data.observeForever(observer) - - // Retrieving public shares from server... - verify(localSharesDataSource).deleteShare( - 1 - ) - } - - private fun loadPrivateSharesAsLiveData( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): LiveData>> { - val ocShareRepository = createRepositoryWithPrivateData(localData, remoteOperationResult) - return ocShareRepository.refreshShares(filePath) - } - - private fun createShareRepositoryWithPrivateData( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): OCShareRepository = - createShareRepositoryWithDataSources( - localData, remoteOperationResult, privateShareTypes - ) - - private fun insertPrivateShare( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): LiveData> { - val ocShareRepository = createShareRepositoryWithPublicData(localData, remoteOperationResult) - - return ocShareRepository.insertPrivateShare( - filePath, - ShareType.GROUP, - "user", - 1 - ) - } - - private fun updatePrivateShare( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): LiveData> { - val ocShareRepository = createShareRepositoryWithPrivateData(localData, remoteOperationResult) - - return ocShareRepository.updatePrivateShare( - 1, - 17 - ) - } - - /****************************************************************************************************** - ******************************************* PUBLIC SHARES ******************************************** - ******************************************************************************************************/ - - private val publicShare = listOf( - DomainTestUtil.createPublicShare( - path = filePath, - isFolder = true, - name = "Photos folder link", - shareLink = "http://server:port/s/1" - ) - ) - - @Test - fun loadPublicSharesFromNetworkSuccessfully() { - val localData = MutableLiveData>() - - val remoteOperationResult = - DomainTestUtil.createRemoteOperationResultMock(ShareParserResult(remoteShares), true) - - val data = loadPublicSharesAsLiveData(localData, remoteOperationResult) - val observer = mockk>>>(relaxed = true) - data.observeForever(observer) - - localData.postValue(null) - - // Get public shares from database to observe them, is called twice (one showing current db shares while - // getting shares from server and another one with db shares already updated with server ones) - verify(exactly = 2) { - localSharesDataSource.getSharesAsLiveData( - filePath, defaultAccountName, listOf(ShareType.PUBLIC_LINK) - ) - } - - // Retrieving shares from server... - - // Public shares are retrieved from server and inserted in database if not empty list - verify { - localSharesDataSource.replaceShares( - remoteShares.map { remoteShare -> - OCShareEntity.fromRemoteShare(remoteShare).also { it.accountOwner = defaultAccountName } - }) - } - - // Observe changes in database livedata when there's a new public share - localData.postValue( - publicShare - ) - - verify { observer.onChanged(DataResult.success(publicShare)) } - } - - @Test - fun loadEmptyPublicSharesFromNetwork() { - val localData = MutableLiveData>() - - val remoteOperationResult = - DomainTestUtil.createRemoteOperationResultMock(ShareParserResult(arrayListOf()), true) - - val data = loadPublicSharesAsLiveData(localData, remoteOperationResult) - val observer = mockk>>>(relaxed = true) - data.observeForever(observer) - - localData.postValue(null) - - // Get public shares from database to observe them, is called twice (one showing current db shares while - // getting shares from server and another one with db shares already updated with server ones) - verify(exactly = 2) { - localSharesDataSource.getSharesAsLiveData( - filePath, defaultAccountName, listOf(ShareType.PUBLIC_LINK) - ) - } - - // Retrieving public shares from server... - - // When there's no shares in server for a specific file, delete them locally - verify { - localSharesDataSource.deleteSharesForFile(filePath, defaultAccountName) - } - - // Observe changes in database livedata when the list of shares is empty - localData.postValue(listOf()) - - verify { - observer.onChanged(DataResult.success(listOf())) - } - } - - @Test - fun loadPublicSharesFromNetworkWithError() { - val localData = MutableLiveData>() - localData.value = publicShare - - val exception = Exception("Error when retrieving shares") - - val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf()), - false, - resultCode = RemoteOperationResult.ResultCode.FORBIDDEN, - exception = exception - ) - - val data = loadPublicSharesAsLiveData(localData, remoteOperationResult) - - // Get public shares from database to observe them - verify { - localSharesDataSource.getSharesAsLiveData( - filePath, defaultAccountName, listOf(ShareType.PUBLIC_LINK) - ) - } - - // Retrieving public shares from server... - - // Observe changes in database livedata when there's an error from server - val observer = mockk>>>(relaxed = true) - data.observeForever(observer) - - verify { - observer.onChanged( - DataResult.error( - RemoteOperationResult.ResultCode.FORBIDDEN, localData.value, exception = exception - ) - ) - } - } - - @Test - fun insertPublicShareOnNetwork() { - val localData = MutableLiveData>() - localData.value = publicShare - - val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf(remoteShares[1])), true - ) - - val data = insertPublicShare(localData, remoteOperationResult) - val observer = mockk>>(relaxed = true) - data.observeForever(observer) - - // Public shares are retrieved from server and inserted in database if not empty list - verify { - localSharesDataSource.insert( - arrayListOf(remoteShares[1]).map { remoteShare -> - OCShareEntity.fromRemoteShare(remoteShare).also { it.accountOwner = defaultAccountName } - }) - } - } - - @Test - fun insertPublicShareOnNetworkWithError() { - val localData = MutableLiveData>() - localData.value = publicShare - - val exception = Exception("Error when retrieving shares") - - val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf()), - false, - resultCode = RemoteOperationResult.ResultCode.SHARE_NOT_FOUND, - exception = exception - ) - - val data = insertPublicShare(localData, remoteOperationResult) - - // Observe changes in database livedata when there's an error from server - val observer = mockk>>(relaxed = true) - data.observeForever(observer) - - verify { - observer.onChanged( - DataResult.error( - RemoteOperationResult.ResultCode.SHARE_NOT_FOUND, exception = exception - ) - ) - } - } - - @Test - fun updatePublicShareOnNetwork() { - val localData = MutableLiveData>() - localData.value = publicShare - - val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf(remoteShares[2])), true - ) - - val data = updatePublicShare(localData, remoteOperationResult) - - val observer = mockk>>(relaxed = true) - data.observeForever(observer) - - // Public shares are retrieved from server and updated in database - verify { - localSharesDataSource.update( - OCShareEntity.fromRemoteShare(remoteShares[2]).also { it.accountOwner = defaultAccountName } - ) - } - } - - @Test - fun deletePublicShareOnNetwork() { - val localData = MutableLiveData>() - localData.value = publicShare - - val remoteOperationResult = DomainTestUtil.createRemoteOperationResultMock( - ShareParserResult(arrayListOf()), true - ) - - val data = deleteShare(localData, remoteOperationResult) - - val observer = mockk>>(relaxed = true) - data.observeForever(observer) - - // Retrieving public shares from server... - verify { - localSharesDataSource.deleteShare(1) - } - } - - private fun loadPublicSharesAsLiveData( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): LiveData>> { - val ocShareRepository = createShareRepositoryWithPublicData(localData, remoteOperationResult) - return ocShareRepository.refreshPublicShares(filePath) - } - - private fun insertPublicShare( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): LiveData> { - val ocShareRepository = createShareRepositoryWithPublicData(localData, remoteOperationResult) - - return ocShareRepository.insertPublicShare( - filePath, - 1, - "Photos folder link 3", - "1234", - -1, - true - ) - } - - private fun updatePublicShare( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): LiveData> { - val ocShareRepository = createShareRepositoryWithPublicData(localData, remoteOperationResult) - - return ocShareRepository.updatePublicShare( - 1, - "Photos folder link updated", - "123456", - 2000, - 1, - false - ) - } - - private fun deletePublicShare( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): LiveData> { - val ocShareRepository = createShareRepositoryWithPublicData(localData, remoteOperationResult) - return ocShareRepository.deleteShare( - 1 - ) - } - - private fun createShareRepositoryWithPublicData( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): OCShareRepository = - createShareRepositoryWithDataSources(localData, remoteOperationResult, listOf(ShareType.PUBLIC_LINK)) - - /****************************************************************************************************** - *********************************************** COMMON *********************************************** - ******************************************************************************************************/ - - private fun createShareRepositoryWithDataSources( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult, - shareTypes: List - ): OCShareRepository { - every { - localSharesDataSource.getSharesAsLiveData( - filePath, defaultAccountName, shareTypes - ) - } returns localData - - val remoteSharesDataSource = RemoteShareDataSourceTest(remoteOperationResult) - - return OCShareRepository( - InstantExecutors(), - localSharesDataSource, - remoteSharesDataSource, - defaultAccountName - ) - } - - private fun deleteShare( - localData: MutableLiveData>, - remoteOperationResult: RemoteOperationResult - ): LiveData> { - val ocShareRepository = createShareRepositoryWithPublicData(localData, remoteOperationResult) - return ocShareRepository.deleteShare( - 1 - ) - } -} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/RemoteSharesDataSourceTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/RemoteSharesDataSourceTest.kt deleted file mode 100644 index 24c7db7e083..00000000000 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/RemoteSharesDataSourceTest.kt +++ /dev/null @@ -1,73 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.domain.shares - -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.CreateRemoteShareOperation -import com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation -import com.owncloud.android.lib.resources.shares.RemoveRemoteShareOperation -import com.owncloud.android.lib.resources.shares.ShareParserResult -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.lib.resources.shares.UpdateRemoteShareOperation - -class RemoteSharesDataSourceTest(private val remoteOperationResult: RemoteOperationResult) : - com.owncloud.android.data.sharing.shares.datasources.RemoteShareDataSource { - override fun getShares( - remoteFilePath: String, - reshares: Boolean, - subfiles: Boolean, - getRemoteSharesForFileOperation: GetRemoteSharesForFileOperation - ): RemoteOperationResult { - return remoteOperationResult - } - - override fun insertShare( - remoteFilePath: String, - shareType: ShareType, - shareWith: String, - permissions: Int, - name: String, - password: String, - expirationDate: Long, - publicUpload: Boolean, - createRemoteShareOperation: CreateRemoteShareOperation - ): RemoteOperationResult { - return remoteOperationResult - } - - override fun updateShare( - remoteId: Long, - name: String, - password: String?, - expirationDateInMillis: Long, - permissions: Int, - publicUpload: Boolean, - updateRemoteShareOperation: UpdateRemoteShareOperation - ): RemoteOperationResult { - return remoteOperationResult - } - - override fun deleteShare( - remoteId: Long, - removeRemoteShareOperation: RemoveRemoteShareOperation - ): RemoteOperationResult { - return remoteOperationResult - } -} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/model/OCShareTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/model/OCShareTest.kt new file mode 100644 index 00000000000..b582d96e6aa --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/model/OCShareTest.kt @@ -0,0 +1,267 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.shares.model + +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.model.ShareType +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class OCShareTest { + + @Test + fun testConstructor() { + val item = OCShare( + 1, + 7, + 7, + ShareType.USER, + "", + "/Photos/image.jpg", + 1, + 1542628397, + 0, + "AnyToken", + "", + "", + false, + -1, + 1, + "admin@server", + "", + "" + ) + + assertEquals(1, item.id) + assertEquals(7, item.fileSource) + assertEquals(7, item.itemSource) + assertEquals(ShareType.USER, item.shareType) + assertEquals("", item.shareWith) + assertEquals("/Photos/image.jpg", item.path) + assertEquals(1, item.permissions) + assertEquals(1542628397, item.sharedDate) + assertEquals(0, item.expirationDate) + assertEquals("AnyToken", item.token) + assertEquals("", item.sharedWithDisplayName) + assertEquals("", item.sharedWithAdditionalInfo) + assertEquals(false, item.isFolder) + assertEquals(-1, item.userId) + assertEquals(1, item.remoteId) + assertEquals("admin@server", item.accountOwner) + assertEquals("", item.name) + assertEquals("", item.shareLink) + } + + @Test + fun testEqualsOk() { + val item1 = OCShare( + id = 1, + fileSource = 7, + itemSource = 7, + shareType = ShareType.USER, + shareWith = "", + path = "/Photos/image.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "AnyToken", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = "", + shareLink = "" + ) + + val item2 = OCShare( + 1, + 7, + 7, + ShareType.USER, + "", + "/Photos/image.jpg", + 1, + 1542628397, + 0, + "AnyToken", + "", + "", + false, + -1, + 1, + "admin@server", + "", + "" + ) + + assertTrue(item1 == item2) + assertFalse(item1 === item2) + } + + @Test + fun testEqualsDefaultValues() { + val item1 = OCShare( + fileSource = 7, + itemSource = 7, + shareType = ShareType.USER, + shareWith = "", + path = "/Photos/image.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "AnyToken", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + name = "", + shareLink = "" + ) + + val item2 = OCShare( + null, + 7, + 7, + ShareType.USER, + "", + "/Photos/image.jpg", + 1, + 1542628397, + 0, + "AnyToken", + "", + "", + false, + -1, + 1, + "", + "", + "" + ) + + assertTrue(item1 == item2) + assertFalse(item1 === item2) + } + + @Test + fun testEqualsKo() { + val item1 = OCShare( + id = 123, + fileSource = 7, + itemSource = 7, + shareType = ShareType.USER, + shareWith = "", + path = "/Photos/image.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "AnyToken", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = "", + shareLink = "" + ) + + val item2 = OCShare( + 456, + 7, + 7, + ShareType.USER, + "", + "/Photos/image.jpg", + 1, + 1542628397, + 0, + "AnyToken", + "", + "", + false, + -1, + 1, + "admin@server", + "", + "" + ) + assertFalse(item1 == item2) + assertFalse(item1 === item2) + } + + @Test + fun testIsPasswordProtected() { + val item1 = OCShare( + id = 123, + fileSource = 7, + itemSource = 7, + shareType = ShareType.PUBLIC_LINK, + shareWith = "user@server", + path = "/Photos/image.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "AnyToken", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = "", + shareLink = "" + ) + assertEquals(true, item1.isPasswordProtected) + + val item2 = item1.copy(shareWith = "") + assertEquals(false, item2.isPasswordProtected) + + val item3 = item1.copy(shareType = ShareType.GROUP) + assertEquals(false, item3.isPasswordProtected) + } + + @Test + fun testShareType() { + val unknown = ShareType.fromValue(-1) + val user = ShareType.fromValue(0) + val group = ShareType.fromValue(1) + val publicLink = ShareType.fromValue(3) + val email = ShareType.fromValue(4) + val contact = ShareType.fromValue(5) + val federated = ShareType.fromValue(6) + val fromValue2 = ShareType.fromValue(2) + + assertEquals(ShareType.UNKNOWN, unknown) + assertEquals(ShareType.USER, user) + assertEquals(ShareType.GROUP, group) + assertEquals(ShareType.PUBLIC_LINK, publicLink) + assertEquals(ShareType.EMAIL, email) + assertEquals(ShareType.CONTACT, contact) + assertEquals(ShareType.FEDERATED, federated) + assertNull(fromValue2) + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/CreatePrivateShareAsyncUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/CreatePrivateShareAsyncUseCaseTest.kt new file mode 100644 index 00000000000..3ba4e104544 --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/CreatePrivateShareAsyncUseCaseTest.kt @@ -0,0 +1,88 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.shares.usecases + +import com.owncloud.android.domain.exceptions.UnauthorizedException +import com.owncloud.android.domain.sharing.shares.ShareRepository +import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.domain.sharing.shares.usecases.CreatePrivateShareAsyncUseCase +import io.mockk.every +import io.mockk.spyk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class CreatePrivateShareAsyncUseCaseTest { + private val shareRepository: ShareRepository = spyk() + private val useCase = CreatePrivateShareAsyncUseCase((shareRepository)) + private val useCaseParams = CreatePrivateShareAsyncUseCase.Params("", ShareType.USER, "", 1, "") + + @Test + fun createPrivateShareOk() { + val useCaseResult = useCase.execute(useCaseParams) + + assertTrue(useCaseResult.isSuccess) + assertFalse(useCaseResult.isError) + assertEquals(Unit, useCaseResult.getDataOrNull()) + + verify(exactly = 1) { shareRepository.insertPrivateShare("", ShareType.USER, "", 1, "") } + } + + @Test + fun createPrivateShareWithUnauthorizedException() { + every { shareRepository.insertPrivateShare(any(), any(), any(), any(), any()) } throws UnauthorizedException() + + val useCaseResult = useCase.execute(useCaseParams) + + assertFalse(useCaseResult.isSuccess) + assertTrue(useCaseResult.isError) + + assertNull(useCaseResult.getDataOrNull()) + assertTrue(useCaseResult.getThrowableOrNull() is UnauthorizedException) + + verify(exactly = 1) { shareRepository.insertPrivateShare("", ShareType.USER, "", 1, "") } + } + + @Test + fun createPrivateShareWithNotValidShareTypeException() { + val useCaseParamsNotValid1 = useCaseParams.copy(shareType = null) + val useCaseResult1 = useCase.execute(useCaseParamsNotValid1) + + assertFalse(useCaseResult1.isSuccess) + assertTrue(useCaseResult1.isError) + + assertNull(useCaseResult1.getDataOrNull()) + assertTrue(useCaseResult1.getThrowableOrNull() is IllegalArgumentException) + + val useCaseParamsNotValid2 = useCaseParams.copy(shareType = ShareType.CONTACT) + val useCaseResult2 = useCase.execute(useCaseParamsNotValid2) + + assertFalse(useCaseResult2.isSuccess) + assertTrue(useCaseResult2.isError) + + assertNull(useCaseResult2.getDataOrNull()) + assertTrue(useCaseResult2.getThrowableOrNull() is IllegalArgumentException) + + verify(exactly = 0) { shareRepository.insertPrivateShare(any(), any(), any(), any(), any()) } + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/CreatePublicShareAsyncUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/CreatePublicShareAsyncUseCaseTest.kt new file mode 100644 index 00000000000..5deee2cd492 --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/CreatePublicShareAsyncUseCaseTest.kt @@ -0,0 +1,99 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.shares.usecases + +import com.owncloud.android.domain.exceptions.UnauthorizedException +import com.owncloud.android.domain.sharing.shares.ShareRepository +import com.owncloud.android.domain.sharing.shares.usecases.CreatePublicShareAsyncUseCase +import io.mockk.every +import io.mockk.spyk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class CreatePublicShareAsyncUseCaseTest { + private val shareRepository: ShareRepository = spyk() + private val useCase = CreatePublicShareAsyncUseCase((shareRepository)) + private val useCaseParams = CreatePublicShareAsyncUseCase.Params("", 1, "", "", 100, false, "") + + @Test + fun createPublicShareOk() { + val useCaseResult = useCase.execute(useCaseParams) + + assertTrue(useCaseResult.isSuccess) + assertFalse(useCaseResult.isError) + assertEquals(Unit, useCaseResult.getDataOrNull()) + + verify(exactly = 1) { shareRepository.insertPublicShare("", 1, "", "", 100, false, "") } + } + + @Test + fun createPublicShareWithUnauthorizedException() { + every { + shareRepository.insertPublicShare( + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } throws UnauthorizedException() + + val useCaseResult = useCase.execute(useCaseParams) + + assertFalse(useCaseResult.isSuccess) + assertTrue(useCaseResult.isError) + + assertNull(useCaseResult.getDataOrNull()) + assertTrue(useCaseResult.getThrowableOrNull() is UnauthorizedException) + + verify(exactly = 1) { shareRepository.insertPublicShare("", 1, "", "", 100, false, "") } + } + + @Test + fun createPublicShareWithIllegalArgumentException() { + every { + shareRepository.insertPublicShare( + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } throws IllegalArgumentException() + + val useCaseResult = useCase.execute(useCaseParams) + + assertFalse(useCaseResult.isSuccess) + assertTrue(useCaseResult.isError) + + assertNull(useCaseResult.getDataOrNull()) + assertTrue(useCaseResult.getThrowableOrNull() is IllegalArgumentException) + + verify(exactly = 1) { shareRepository.insertPublicShare("", 1, "", "", 100, false, "") } + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/DeleteShareAsyncUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/DeleteShareAsyncUseCaseTest.kt new file mode 100644 index 00000000000..0f1c06096eb --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/DeleteShareAsyncUseCaseTest.kt @@ -0,0 +1,64 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.shares.usecases + +import com.owncloud.android.domain.exceptions.UnauthorizedException +import com.owncloud.android.domain.sharing.shares.ShareRepository +import com.owncloud.android.domain.sharing.shares.usecases.DeleteShareAsyncUseCase +import io.mockk.every +import io.mockk.spyk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class DeleteShareAsyncUseCaseTest { + private val shareRepository: ShareRepository = spyk() + private val useCase = DeleteShareAsyncUseCase((shareRepository)) + private val useCaseParams = DeleteShareAsyncUseCase.Params(1) + + @Test + fun deleteShareOk() { + val useCaseResult = useCase.execute(useCaseParams) + + assertTrue(useCaseResult.isSuccess) + assertFalse(useCaseResult.isError) + assertEquals(Unit, useCaseResult.getDataOrNull()) + + verify(exactly = 1) { shareRepository.deleteShare(1) } + } + + @Test + fun deleteShareWithUnauthorizedException() { + every { shareRepository.deleteShare(any()) } throws UnauthorizedException() + + val useCaseResult = useCase.execute(useCaseParams) + + assertFalse(useCaseResult.isSuccess) + assertTrue(useCaseResult.isError) + + assertNull(useCaseResult.getDataOrNull()) + assertTrue(useCaseResult.getThrowableOrNull() is UnauthorizedException) + + verify(exactly = 1) { shareRepository.deleteShare(1) } + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/EditPrivateShareAsyncUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/EditPrivateShareAsyncUseCaseTest.kt new file mode 100644 index 00000000000..ac681889e0d --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/EditPrivateShareAsyncUseCaseTest.kt @@ -0,0 +1,65 @@ + +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.shares.usecases + +import com.owncloud.android.domain.exceptions.UnauthorizedException +import com.owncloud.android.domain.sharing.shares.ShareRepository +import com.owncloud.android.domain.sharing.shares.usecases.EditPrivateShareAsyncUseCase +import io.mockk.every +import io.mockk.spyk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class EditPrivateShareAsyncUseCaseTest { + private val shareRepository: ShareRepository = spyk() + private val useCase = EditPrivateShareAsyncUseCase((shareRepository)) + private val useCaseParams = EditPrivateShareAsyncUseCase.Params(1, 1, "") + + @Test + fun editPrivateShareOk() { + val useCaseResult = useCase.execute(useCaseParams) + + assertTrue(useCaseResult.isSuccess) + assertFalse(useCaseResult.isError) + assertEquals(Unit, useCaseResult.getDataOrNull()) + + verify(exactly = 1) { shareRepository.updatePrivateShare(1, 1, "") } + } + + @Test + fun editPrivateShareWithUnauthorizedException() { + every { shareRepository.updatePrivateShare(any(), any(), any()) } throws UnauthorizedException() + + val useCaseResult = useCase.execute(useCaseParams) + + assertFalse(useCaseResult.isSuccess) + assertTrue(useCaseResult.isError) + + assertNull(useCaseResult.getDataOrNull()) + assertTrue(useCaseResult.getThrowableOrNull() is UnauthorizedException) + + verify(exactly = 1) { shareRepository.updatePrivateShare(1, 1, "") } + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/EditPublicShareAsyncUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/EditPublicShareAsyncUseCaseTest.kt new file mode 100644 index 00000000000..cc570dbfe1d --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/EditPublicShareAsyncUseCaseTest.kt @@ -0,0 +1,74 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.shares.usecases + +import com.owncloud.android.domain.exceptions.UnauthorizedException +import com.owncloud.android.domain.sharing.shares.ShareRepository +import com.owncloud.android.domain.sharing.shares.usecases.EditPublicShareAsyncUseCase +import io.mockk.every +import io.mockk.spyk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class EditPublicShareAsyncUseCaseTest { + private val shareRepository: ShareRepository = spyk() + private val useCase = EditPublicShareAsyncUseCase((shareRepository)) + private val useCaseParams = EditPublicShareAsyncUseCase.Params(1, "", "", 1, 1, false, "") + + @Test + fun editPublicShareOk() { + val useCaseResult = useCase.execute(useCaseParams) + + assertTrue(useCaseResult.isSuccess) + assertFalse(useCaseResult.isError) + assertEquals(Unit, useCaseResult.getDataOrNull()) + + verify(exactly = 1) { shareRepository.updatePublicShare(1, "", "", 1, 1, false, "") } + } + + @Test + fun editPublicShareWithUnauthorizedException() { + every { + shareRepository.updatePublicShare( + any(), + any(), + any(), + any(), + any(), + any(), + any() + ) + } throws UnauthorizedException() + + val useCaseResult = useCase.execute(useCaseParams) + + assertFalse(useCaseResult.isSuccess) + assertTrue(useCaseResult.isError) + + assertNull(useCaseResult.getDataOrNull()) + assertTrue(useCaseResult.getThrowableOrNull() is UnauthorizedException) + + verify(exactly = 1) { shareRepository.updatePublicShare(1, "", "", 1, 1, false, "") } + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetShareAsLiveDataUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetShareAsLiveDataUseCaseTest.kt new file mode 100644 index 00000000000..a64860edf10 --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetShareAsLiveDataUseCaseTest.kt @@ -0,0 +1,73 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.shares.usecases + +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.lifecycle.MutableLiveData +import com.owncloud.android.domain.sharing.shares.ShareRepository +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.usecases.GetShareAsLiveDataUseCase +import com.owncloud.android.domain.utils.DomainTestUtil.DUMMY_SHARE + +import io.mockk.every +import io.mockk.spyk +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test + +class GetShareAsLiveDataUseCaseTest { + @Rule + @JvmField + var instantTaskExecutorRule = InstantTaskExecutorRule() + + private val shareRepository: ShareRepository = spyk() + private val useCase = GetShareAsLiveDataUseCase((shareRepository)) + private val useCaseParams = GetShareAsLiveDataUseCase.Params(1) + private lateinit var shareEmitted: MutableList + + @Before + fun init() { + shareEmitted = mutableListOf() + } + + @Test + fun getShareAsLiveDataOk() { + val shareLiveData = MutableLiveData() + every { shareRepository.getShareAsLiveData(any()) } returns shareLiveData + + val shareToEmit = listOf(DUMMY_SHARE) + + useCase.execute(useCaseParams).observeForever { + shareEmitted.add(it) + } + + shareToEmit.forEach{ shareLiveData.postValue(it)} + + Assert.assertEquals(shareToEmit, shareEmitted) + } + + @Test(expected = Exception::class) + fun getShareAsLiveDataException() { + every { shareRepository.getShareAsLiveData(any()) } throws Exception() + + useCase.execute(useCaseParams) + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetSharesAsLiveDataUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetSharesAsLiveDataUseCaseTest.kt new file mode 100644 index 00000000000..aef95b07aef --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetSharesAsLiveDataUseCaseTest.kt @@ -0,0 +1,73 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.shares.usecases + +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import androidx.lifecycle.MutableLiveData +import com.owncloud.android.domain.sharing.shares.ShareRepository +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.usecases.GetSharesAsLiveDataUseCase +import com.owncloud.android.domain.utils.DomainTestUtil.DUMMY_SHARE + +import io.mockk.every +import io.mockk.spyk +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test + +class GetSharesAsLiveDataUseCaseTest { + @Rule + @JvmField + var instantTaskExecutorRule = InstantTaskExecutorRule() + + private val shareRepository: ShareRepository = spyk() + private val useCase = GetSharesAsLiveDataUseCase((shareRepository)) + private val useCaseParams = GetSharesAsLiveDataUseCase.Params("", "") + private lateinit var sharesEmitted: MutableList + + @Before + fun init() { + sharesEmitted = mutableListOf() + } + + @Test + fun getSharesAsLiveDataOk() { + val sharesLiveData = MutableLiveData>() + every { shareRepository.getSharesAsLiveData(any(), any()) } returns sharesLiveData + + val sharesToEmit = listOf(DUMMY_SHARE, DUMMY_SHARE.copy(id = 2), DUMMY_SHARE.copy(id = 3)) + + useCase.execute(useCaseParams).observeForever { + it?.forEach { ocShare -> sharesEmitted.add(ocShare) } + } + + sharesLiveData.postValue(sharesToEmit) + + Assert.assertEquals(sharesToEmit, sharesEmitted) + } + + @Test(expected = Exception::class) + fun getSharesAsLiveDataException() { + every { shareRepository.getSharesAsLiveData(any(), any()) } throws Exception() + + useCase.execute(useCaseParams) + } +} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/RefreshSharesFromServerAsyncUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/RefreshSharesFromServerAsyncUseCaseTest.kt index cd0528d81c9..5e27cb4c310 100644 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/RefreshSharesFromServerAsyncUseCaseTest.kt +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/RefreshSharesFromServerAsyncUseCaseTest.kt @@ -1,5 +1,64 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + package com.owncloud.android.domain.shares.usecases +import com.owncloud.android.domain.exceptions.UnauthorizedException +import com.owncloud.android.domain.sharing.shares.ShareRepository +import com.owncloud.android.domain.sharing.shares.usecases.RefreshSharesFromServerAsyncUseCase +import io.mockk.every +import io.mockk.spyk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + class RefreshSharesFromServerAsyncUseCaseTest { + private val shareRepository: ShareRepository = spyk() + private val useCase = RefreshSharesFromServerAsyncUseCase((shareRepository)) + private val useCaseParams = RefreshSharesFromServerAsyncUseCase.Params("", "") + + @Test + fun refreshSharesFromNetworkOk() { + val useCaseResult = useCase.execute(useCaseParams) + + assertTrue(useCaseResult.isSuccess) + assertFalse(useCaseResult.isError) + assertEquals(Unit, useCaseResult.getDataOrNull()) + + verify(exactly = 1) { shareRepository.refreshSharesFromNetwork("", "") } + } + + @Test + fun refreshSharesFromNetworkWithUnauthorizedException() { + every { shareRepository.refreshSharesFromNetwork(any(), any()) } throws UnauthorizedException() + + val useCaseResult = useCase.execute(useCaseParams) + + assertFalse(useCaseResult.isSuccess) + assertTrue(useCaseResult.isError) + + assertNull(useCaseResult.getDataOrNull()) + assertTrue(useCaseResult.getThrowableOrNull() is UnauthorizedException) + verify(exactly = 1) { shareRepository.refreshSharesFromNetwork("", "") } + } } diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/utils/InstantExecutors.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/utils/InstantExecutors.kt deleted file mode 100644 index 5020476a9b1..00000000000 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/utils/InstantExecutors.kt +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.owncloud.android.domain.utils - -import com.owncloud.android.data.Executors -import java.util.concurrent.Executor - -class InstantExecutors : Executors(instant, instant, instant) { - companion object { - private val instant = Executor { it.run() } - } -} From 49e54de3fddb2dcc82a8cdf381eda10213577532 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Mon, 18 Nov 2019 14:11:37 +0100 Subject: [PATCH 07/41] Create test utils module --- owncloudApp/build.gradle | 1 + owncloudData/build.gradle | 1 + owncloudDomain/build.gradle | 1 + owncloudTestUtil/.gitignore | 1 + owncloudTestUtil/build.gradle | 24 +++++++++++++++++++ owncloudTestUtil/proguard-rules.pro | 21 ++++++++++++++++ owncloudTestUtil/src/main/AndroidManifest.xml | 1 + settings.gradle | 2 +- 8 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 owncloudTestUtil/.gitignore create mode 100644 owncloudTestUtil/build.gradle create mode 100644 owncloudTestUtil/proguard-rules.pro create mode 100644 owncloudTestUtil/src/main/AndroidManifest.xml diff --git a/owncloudApp/build.gradle b/owncloudApp/build.gradle index 603d89d8be3..2f2e45b30c2 100644 --- a/owncloudApp/build.gradle +++ b/owncloudApp/build.gradle @@ -11,6 +11,7 @@ dependencies { /// data and domain modules implementation project(':owncloudDomain') implementation project(':owncloudData') + testImplementation project(':owncloudTestUtil') /// dependencies for app building implementation "androidx.legacy:legacy-support-v4:$androidX" diff --git a/owncloudData/build.gradle b/owncloudData/build.gradle index 71af8fdf4b0..02d407a7c78 100644 --- a/owncloudData/build.gradle +++ b/owncloudData/build.gradle @@ -41,6 +41,7 @@ android { dependencies { implementation project(':owncloudDomain') + testImplementation project(':owncloudTestUtil') // Owncloud Android Library api project(':owncloud-android-library:owncloudComLibrary') diff --git a/owncloudDomain/build.gradle b/owncloudDomain/build.gradle index 3df965ec4aa..45a0e19fa00 100644 --- a/owncloudDomain/build.gradle +++ b/owncloudDomain/build.gradle @@ -41,6 +41,7 @@ android { dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) + testImplementation project(':owncloudTestUtil') implementation 'androidx.appcompat:appcompat:1.0.2' diff --git a/owncloudTestUtil/.gitignore b/owncloudTestUtil/.gitignore new file mode 100644 index 00000000000..796b96d1c40 --- /dev/null +++ b/owncloudTestUtil/.gitignore @@ -0,0 +1 @@ +/build diff --git a/owncloudTestUtil/build.gradle b/owncloudTestUtil/build.gradle new file mode 100644 index 00000000000..784fead5792 --- /dev/null +++ b/owncloudTestUtil/build.gradle @@ -0,0 +1,24 @@ +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' +android { + compileSdkVersion 28 + + defaultConfig { + minSdkVersion 19 + targetSdkVersion 28 + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation project(':owncloudDomain') + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" +} diff --git a/owncloudTestUtil/proguard-rules.pro b/owncloudTestUtil/proguard-rules.pro new file mode 100644 index 00000000000..f1b424510da --- /dev/null +++ b/owncloudTestUtil/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/owncloudTestUtil/src/main/AndroidManifest.xml b/owncloudTestUtil/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..9f4e6fd4d41 --- /dev/null +++ b/owncloudTestUtil/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/settings.gradle b/settings.gradle index d6555e0cadd..745bf24f67a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1 @@ -include ':owncloudApp', ':owncloudDomain', ':owncloudData', ':owncloud-android-library:owncloudComLibrary' +include ':owncloudApp', ':owncloudDomain', ':owncloudData', ':owncloud-android-library:owncloudComLibrary', ':owncloudTestUtil' From dee911a5cfa7e3ca2cc772f080f4de9a82072646 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Mon, 18 Nov 2019 14:51:58 +0100 Subject: [PATCH 08/41] Add new tests to OCCapabilityRepository --- .../repository/OCCapabilityRepositoryTest.kt | 61 +++++++++++-------- .../owncloud/android/testutil/OCAccount.kt | 3 + .../owncloud/android/testutil/OCCapability.kt | 36 +++++++++++ 3 files changed, 73 insertions(+), 27 deletions(-) create mode 100644 owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt create mode 100644 owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt index dc2135946d9..46c2fa57acf 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt @@ -2,6 +2,7 @@ * ownCloud Android client application * * @author David González Verdugo + * @author Abel García de Prada * Copyright (C) 2019 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify @@ -23,9 +24,10 @@ import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import com.owncloud.android.data.capabilities.datasources.LocalCapabilitiesDataSource import com.owncloud.android.data.capabilities.datasources.RemoteCapabilitiesDataSource -import com.owncloud.android.data.utils.DataTestUtil import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.exceptions.NoConnectionWithServerException +import com.owncloud.android.testutil.OC_ACCOUNT_NAME +import com.owncloud.android.testutil.OC_CAPABILITY import io.mockk.every import io.mockk.mockk import io.mockk.verify @@ -48,16 +50,14 @@ class OCCapabilityRepositoryTest { @Test fun refreshCapabilitiesFromNetworkOk() { - val defaultAccountName = "admin@server" - - val capability = DataTestUtil.createCapability(defaultAccountName) + val capability = OC_CAPABILITY.copy(accountName = OC_ACCOUNT_NAME) every { remoteCapabilitiesDataSource.getCapabilities(any()) } returns capability - ocCapabilityRepository.refreshCapabilitiesForAccount(defaultAccountName) + ocCapabilityRepository.refreshCapabilitiesForAccount(OC_ACCOUNT_NAME) verify(exactly = 1) { - remoteCapabilitiesDataSource.getCapabilities(defaultAccountName) + remoteCapabilitiesDataSource.getCapabilities(OC_ACCOUNT_NAME) } verify(exactly = 1) { @@ -67,25 +67,21 @@ class OCCapabilityRepositoryTest { @Test(expected = NoConnectionWithServerException::class) fun refreshCapabilitiesFromNetworkNoConnection() { - val defaultAccountName = "admin@server" - val capability = DataTestUtil.createCapability(defaultAccountName) every { remoteCapabilitiesDataSource.getCapabilities(any()) } throws NoConnectionWithServerException() - ocCapabilityRepository.refreshCapabilitiesForAccount(defaultAccountName) + ocCapabilityRepository.refreshCapabilitiesForAccount(OC_ACCOUNT_NAME) verify(exactly = 1) { - remoteCapabilitiesDataSource.getCapabilities(defaultAccountName) + remoteCapabilitiesDataSource.getCapabilities(OC_ACCOUNT_NAME) } verify(exactly = 0) { - localCapabilitiesDataSource.insert(listOf(capability)) + localCapabilitiesDataSource.insert(any()) } } @Test fun getCapabilitiesAsLiveData() { - val defaultAccountName = "admin@server" - val capabilitiesLiveData = MutableLiveData() every { @@ -93,12 +89,11 @@ class OCCapabilityRepositoryTest { } returns capabilitiesLiveData val capabilitiesEmitted = mutableListOf() - ocCapabilityRepository.getCapabilitiesAsLiveData(defaultAccountName).observeForever { + ocCapabilityRepository.getCapabilitiesAsLiveData(OC_ACCOUNT_NAME).observeForever { capabilitiesEmitted.add(it!!) } - - val capabilitiesToEmit = listOf(DataTestUtil.createCapability()) + val capabilitiesToEmit = listOf(OC_CAPABILITY) capabilitiesToEmit.forEach { capabilitiesLiveData.postValue(it) } @@ -108,22 +103,34 @@ class OCCapabilityRepositoryTest { @Test(expected = Exception::class) fun getCapabilitiesAsLiveDataException() { - val defaultAccountName = "admin@server" - - val capabilitiesLiveData = MutableLiveData() - every { localCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(any()) } throws Exception() - val capabilitiesEmitted = mutableListOf() - ocCapabilityRepository.getCapabilitiesAsLiveData(defaultAccountName) + ocCapabilityRepository.getCapabilitiesAsLiveData(OC_ACCOUNT_NAME) + } - val capabilitiesToEmit = listOf(DataTestUtil.createCapability()) - capabilitiesToEmit.forEach { - capabilitiesLiveData.postValue(it) - } + @Test + fun getStoredCapabilities() { - Assert.assertEquals(capabilitiesToEmit, capabilitiesEmitted) + every { + localCapabilitiesDataSource.getCapabilityForAccount(any()) + } returns OC_CAPABILITY + + val result = ocCapabilityRepository.getStoredCapabilities(OC_ACCOUNT_NAME) + + Assert.assertEquals(OC_CAPABILITY, result) + } + + @Test + fun getStoredCapabilitiesNull() { + + every { + localCapabilitiesDataSource.getCapabilityForAccount(any()) + } returns null + + val result = ocCapabilityRepository.getStoredCapabilities(OC_ACCOUNT_NAME) + + Assert.assertEquals(null, result) } } diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt new file mode 100644 index 00000000000..757b137265a --- /dev/null +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt @@ -0,0 +1,3 @@ +package com.owncloud.android.testutil + +const val OC_ACCOUNT_NAME = "admin@server" \ No newline at end of file diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt new file mode 100644 index 00000000000..392bfc4fad4 --- /dev/null +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt @@ -0,0 +1,36 @@ +package com.owncloud.android.testutil + +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType +import com.owncloud.android.domain.capabilities.model.OCCapability + +val OC_CAPABILITY = + OCCapability( + accountName = "user@server", + versionMayor = 2, + versionMinor = 1, + versionMicro = 0, + versionString = "1.0.0", + versionEdition = "1.0.0", + corePollInterval = 0, + filesSharingApiEnabled = CapabilityBooleanType.TRUE, + filesSharingSearchMinLength = 3, + filesSharingPublicEnabled = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicExpireDateEnabled = CapabilityBooleanType.FALSE, + filesSharingPublicExpireDateDays = 0, + filesSharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE, + filesSharingPublicSendMail = CapabilityBooleanType.FALSE, + filesSharingPublicUpload = CapabilityBooleanType.FALSE, + filesSharingPublicMultiple = CapabilityBooleanType.FALSE, + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.FALSE, + filesSharingUserSendMail = CapabilityBooleanType.FALSE, + filesSharingResharing = CapabilityBooleanType.FALSE, + filesSharingFederationOutgoing = CapabilityBooleanType.FALSE, + filesSharingFederationIncoming = CapabilityBooleanType.FALSE, + filesBigFileChunking = CapabilityBooleanType.FALSE, + filesUndelete = CapabilityBooleanType.FALSE, + filesVersioning = CapabilityBooleanType.FALSE + ) From d48fbdcc8ccb5b9ff8f37b6d3d843e2d2193209f Mon Sep 17 00:00:00 2001 From: davigonz Date: Mon, 18 Nov 2019 14:55:40 +0100 Subject: [PATCH 09/41] App module tests, restructure --- .../viewmodels}/OCCapabilityViewModelTest.kt | 2 +- .../privateShares/DeletePrivateShareTest.kt | 298 ----------- .../privateShares/EditPrivateShareTest.kt | 254 ---------- .../publicShares/CreatePublicShareTest.kt | 373 -------------- .../publicShares/DeletePublicShareTest.kt | 325 ------------ .../publicShares/EditPublicShareFolderTest.kt | 470 ----------------- .../publicShares/EditPublicShareTest.kt | 474 ------------------ .../sharees/ui}/SearchShareesFragmentTest.kt | 4 +- .../viewmodels/OCShareeViewmodelTest.kt | 2 +- .../shares}/flow/CreatePublicShareTest.kt | 2 +- .../shares}/flow/DeletePublicShareTest.kt | 2 +- .../shares}/flow/EditPublicShareFolderTest.kt | 2 +- .../shares}/flow/EditPublicShareTest.kt | 2 +- .../shares}/flow/LoadSharesTest.kt | 2 +- .../ui/EditPrivateShareFragmentTest.kt | 4 +- .../PublicShareCreationDialogFragmentTest.kt | 2 +- .../PublicShareEditionDialogFragmentTest.kt | 2 +- .../shares/ui}/ShareFileFragmentTest.kt | 2 +- .../shares/ui}/ShareFolderFragmentTest.kt | 2 +- .../shares/ui}/SharesContentProviderTest.kt | 2 +- .../shares/ui}/TestShareFileActivity.kt | 2 +- .../shares/viewmodels/OCShareViewModelTest.kt | 2 +- owncloudApp/src/debug/AndroidManifest.xml | 2 +- .../android/ErrorMessageAdapterUnitTest.java | 77 --- .../shares/data/RemoteShareDataSourceTest.kt | 74 --- 25 files changed, 19 insertions(+), 2364 deletions(-) rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation/capabilities/viewmodel => capabilities/viewmodels}/OCCapabilityViewModelTest.kt (98%) delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/privateShares/DeletePrivateShareTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/privateShares/EditPrivateShareTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/CreatePublicShareTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/DeletePublicShareTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/EditPublicShareFolderTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/EditPublicShareTest.kt rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation/sharing/sharees/views => sharing/sharees/ui}/SearchShareesFragmentTest.kt (97%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation => }/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt (98%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{ => sharing/shares}/flow/CreatePublicShareTest.kt (99%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{ => sharing/shares}/flow/DeletePublicShareTest.kt (99%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{ => sharing/shares}/flow/EditPublicShareFolderTest.kt (99%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{ => sharing/shares}/flow/EditPublicShareTest.kt (99%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{ => sharing/shares}/flow/LoadSharesTest.kt (99%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{shares/presentation => sharing/shares}/ui/EditPrivateShareFragmentTest.kt (99%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation/sharing/shares/views => sharing/shares/ui}/PublicShareCreationDialogFragmentTest.kt (99%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation/sharing/shares/views => sharing/shares/ui}/PublicShareEditionDialogFragmentTest.kt (98%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation/sharing/shares/views => sharing/shares/ui}/ShareFileFragmentTest.kt (99%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation/sharing/shares/views => sharing/shares/ui}/ShareFolderFragmentTest.kt (98%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation/sharing/shares/views => sharing/shares/ui}/SharesContentProviderTest.kt (99%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation/sharing/shares/views => sharing/shares/ui}/TestShareFileActivity.kt (98%) rename owncloudApp/src/androidTest/java/com/owncloud/android/{presentation => }/sharing/shares/viewmodels/OCShareViewModelTest.kt (99%) delete mode 100644 owncloudApp/src/test/java/com/owncloud/android/ErrorMessageAdapterUnitTest.java delete mode 100644 owncloudApp/src/test/java/com/owncloud/android/shares/data/RemoteShareDataSourceTest.kt diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/capabilities/viewmodel/OCCapabilityViewModelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt similarity index 98% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/capabilities/viewmodel/OCCapabilityViewModelTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt index 5955cac05b0..50239c15162 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/capabilities/viewmodel/OCCapabilityViewModelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.capabilities.viewmodel +package com.owncloud.android.capabilities.viewmodels import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/privateShares/DeletePrivateShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/privateShares/DeletePrivateShareTest.kt deleted file mode 100644 index 52f28879db0..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/privateShares/DeletePrivateShareTest.kt +++ /dev/null @@ -1,298 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.shares.domain.privateShares - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import android.os.Parcelable -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.assertion.ViewAssertions.doesNotExist -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.hasSibling -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator -import com.owncloud.android.capabilities.db.OCCapability -import com.owncloud.android.capabilities.viewmodel.OCCapabilityViewModel -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.shares.domain.OCShare -import com.owncloud.android.shares.presentation.OCShareViewModel -import com.owncloud.android.shares.presentation.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.Permissions -import com.owncloud.android.utils.TestUtil -import com.owncloud.android.vo.Resource -import org.hamcrest.CoreMatchers.allOf -import org.junit.After -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module -import org.mockito.Mockito -import org.mockito.Mockito.`when` -import org.mockito.Mockito.mock - -class DeletePrivateShareTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val privateShareList = arrayListOf( - TestUtil.createPrivateShare( - remoteId = 10, - shareType = ShareType.USER.value, - shareWith = "paco", - path = "/Documents/doc1", - permissions = Permissions.READ_PERMISSIONS.value, - isFolder = false, - sharedWithDisplayName = "Paco" - ), - TestUtil.createPrivateShare( - remoteId = 20, - shareType = ShareType.GROUP.value, - shareWith = "family", - path = "/Documents", - permissions = Permissions.READ_PERMISSIONS.value, - isFolder = true, - sharedWithDisplayName = "Family" - ) - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val privateSharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = mock(OCCapabilityViewModel::class.java) - private val ocShareViewModel = mock(OCShareViewModel::class.java) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = Mockito.spy(Intent::class.java) - - file = TestUtil.createFile("image.jpg") - - `when`(intent.getParcelableExtra(FileActivity.EXTRA_FILE) as? Parcelable).thenReturn(file) - intent.putExtra(FileActivity.EXTRA_FILE, file) - - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(false)).thenReturn(capabilitiesLiveData) - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(true)).thenReturn(capabilitiesLiveData) - `when`(ocShareViewModel.getPrivateShares(file.remotePath)).thenReturn(privateSharesLiveData) - `when`(ocShareViewModel.getPublicShares(file.remotePath)).thenReturn(MutableLiveData()) - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @After - fun clean() { - stopKoin() - } - - @Test - fun deletePrivateShare() { - loadCapabilitiesSuccessfully() - loadPrivateSharesSuccessfully() - - `when`( - ocShareViewModel.deleteShare(10) - ).thenReturn( - MutableLiveData>().apply { - postValue(Resource.success()) - } - ) - - onView( - allOf( - withId(R.id.unshareButton), - hasSibling(withText(privateShareList[0].sharedWithDisplayName)) - ) - ).perform(click()) - - privateSharesLiveData.postValue( - Resource.success( - arrayListOf(privateShareList[1]) - ) - ) - - onView(withText(privateShareList[0].sharedWithDisplayName)).check(doesNotExist()) - onView(withText(privateShareList[1].sharedWithDisplayName + " (group)")).check(matches(isDisplayed())) - } - - @Test - fun deletePrivateShareLoading() { - loadCapabilitiesSuccessfully() - loadPrivateSharesSuccessfully() - - `when`( - ocShareViewModel.deleteShare(10) - ).thenReturn( - MutableLiveData>().apply { - postValue(Resource.loading()) - } - ) - - onView( - allOf( - withId(R.id.unshareButton), - hasSibling(withText(privateShareList[0].sharedWithDisplayName)) - ) - ).perform(click()) - - onView(withText(R.string.common_loading)).check(matches(isDisplayed())) - } - - @Test - fun deletePrivateShareError() { - loadCapabilitiesSuccessfully() - loadPrivateSharesSuccessfully() - - `when`( - ocShareViewModel.deleteShare(10) - ).thenReturn( - MutableLiveData>().apply { - postValue( - Resource.error( - RemoteOperationResult.ResultCode.FORBIDDEN, - exception = Exception("Error when retrieving shares") - ) - ) - } - ) - - onView( - allOf( - withId(R.id.unshareButton), - hasSibling(withText(privateShareList[0].sharedWithDisplayName)) - ) - ).perform(click()) - - onView(withText(R.string.unshare_link_file_error)).check(matches(isDisplayed())) - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapability = TestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - Resource.success( - capability - ) - ) - } - - private fun loadPrivateSharesSuccessfully(privateShares: ArrayList = privateShareList) { - privateSharesLiveData.postValue(Resource.success(privateShares)) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/privateShares/EditPrivateShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/privateShares/EditPrivateShareTest.kt deleted file mode 100644 index 1a0bc639d92..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/privateShares/EditPrivateShareTest.kt +++ /dev/null @@ -1,254 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.shares.domain.privateShares - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import android.os.Parcelable -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator -import com.owncloud.android.capabilities.db.OCCapability -import com.owncloud.android.capabilities.viewmodel.OCCapabilityViewModel -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.shares.domain.OCShare -import com.owncloud.android.shares.presentation.OCShareViewModel -import com.owncloud.android.shares.presentation.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.Permissions -import com.owncloud.android.utils.TestUtil -import com.owncloud.android.vo.Resource -import org.junit.After -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module -import org.mockito.Mockito -import org.mockito.Mockito.`when` - -class EditPrivateShareTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val privateShare = TestUtil.createPrivateShare( - shareType = ShareType.GROUP.value, - shareWith = "friends", - path = "/Photos", - permissions = Permissions.READ_PERMISSIONS.value, - isFolder = true, - sharedWithDisplayName = "Friends" - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val privateSharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = Mockito.mock(OCCapabilityViewModel::class.java) - private val ocShareViewModel = Mockito.mock(OCShareViewModel::class.java) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = Mockito.spy(Intent::class.java) - - file = TestUtil.createFile("image.jpg") - - `when`(intent.getParcelableExtra(FileActivity.EXTRA_FILE) as? Parcelable).thenReturn(file) - intent.putExtra(FileActivity.EXTRA_FILE, file) - - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(false)).thenReturn(capabilitiesLiveData) - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(true)).thenReturn(capabilitiesLiveData) - `when`(ocShareViewModel.getPrivateShares(file.remotePath)).thenReturn(privateSharesLiveData) - `when`(ocShareViewModel.getPrivateShare(1)).thenReturn( - MutableLiveData().apply { - postValue(privateShare) - } - ) - `when`(ocShareViewModel.getPublicShares(file.remotePath)).thenReturn(MutableLiveData()) - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @After - fun clean() { - stopKoin() - } - - @Test - fun editPrivateShareLoading() { - loadCapabilitiesSuccessfully() - loadPrivateSharesSuccessfully() - - `when`( - ocShareViewModel.updatePrivateShare( - 1, - Permissions.EDIT_PERMISSIONS.value - ) - ).thenReturn( - MutableLiveData>().apply { - postValue(Resource.loading()) - } - ) - - onView(withId(R.id.editShareButton)).perform(click()) - onView(withId(R.id.canEditSwitch)).perform(click()) - - onView(withText(R.string.common_loading)).check(matches(isDisplayed())) - } - - @Test - fun editPrivateShareError() { - loadCapabilitiesSuccessfully() - loadPrivateSharesSuccessfully() - - `when`( - ocShareViewModel.updatePrivateShare( - 1, - Permissions.EDIT_PERMISSIONS.value - ) - ).thenReturn( - MutableLiveData>().apply { - postValue( - Resource.error( - RemoteOperationResult.ResultCode.HOST_NOT_AVAILABLE - ) - ) - } - ) - - onView(withId(R.id.editShareButton)).perform(click()) - onView(withId(R.id.canEditSwitch)).perform(click()) - - onView(withText(R.string.network_host_not_available)).check(matches(isDisplayed())) - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapability = TestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - Resource.success( - capability - ) - ) - } - - private fun loadPrivateSharesSuccessfully(privateShares: ArrayList = arrayListOf(privateShare)) { - privateSharesLiveData.postValue(Resource.success(privateShares)) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/CreatePublicShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/CreatePublicShareTest.kt deleted file mode 100644 index 77a2ff51256..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/CreatePublicShareTest.kt +++ /dev/null @@ -1,373 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.shares.domain.publicShares - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import android.os.Parcelable -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.assertion.ViewAssertions.doesNotExist -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator.KEY_AUTH_TOKEN_TYPE -import com.owncloud.android.capabilities.db.OCCapability -import com.owncloud.android.capabilities.viewmodel.OCCapabilityViewModel -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.shares.domain.OCShare -import com.owncloud.android.shares.presentation.OCShareViewModel -import com.owncloud.android.shares.presentation.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.TestUtil -import com.owncloud.android.vo.Resource -import org.junit.After -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module -import org.mockito.Mockito.`when` -import org.mockito.Mockito.mock -import org.mockito.Mockito.spy - -class CreatePublicShareTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val publicShares = arrayListOf( - TestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1" - ), - TestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg link (2)", - shareLink = "http://server:port/s/2" - ), - TestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg link (3)", - shareLink = "http://server:port/s/3" - ) - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val sharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = mock(OCCapabilityViewModel::class.java) - private val ocShareViewModel = mock(OCShareViewModel::class.java) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = spy(Intent::class.java) - - file = TestUtil.createFile("image.jpg") - - `when`(intent.getParcelableExtra(FileActivity.EXTRA_FILE) as? Parcelable).thenReturn(file) - intent.putExtra(FileActivity.EXTRA_FILE, file) - - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(false)).thenReturn(capabilitiesLiveData) - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(true)).thenReturn(capabilitiesLiveData) - `when`(ocShareViewModel.getPublicShares(file.remotePath)).thenReturn(sharesLiveData) - `when`(ocShareViewModel.getPrivateShares(file.remotePath)).thenReturn(MutableLiveData()) - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @After - fun clean() { - stopKoin() - } - - @Test - fun createPublicShareWithNoPublicSharesYet() { - loadCapabilitiesSuccessfully() - loadSharesSuccessfully(arrayListOf()) - - // Create share - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare = publicShares[0] - savePublicShare(newPublicShare) - - // New share properly created - sharesLiveData.postValue( - Resource.success( - arrayListOf(newPublicShare) - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare.name)).check(matches(isDisplayed())) - } - - @Test - fun createPublicShareWithAlreadyExistingShares() { - loadCapabilitiesSuccessfully() - val existingPublicShares = publicShares.take(2) as ArrayList - loadSharesSuccessfully( - existingPublicShares - ) - - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare = publicShares[2] - savePublicShare(newPublicShare) - - // New share properly created - sharesLiveData.postValue( - Resource.success( - publicShares - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare.name)).check(matches(isDisplayed())) - } - - @Test - fun createMultiplePublicShares() { - loadCapabilitiesSuccessfully() - loadSharesSuccessfully(arrayListOf()) - - /** - * 1st public share - */ - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare1 = publicShares[0] - savePublicShare(newPublicShare1) - - // New share properly created - sharesLiveData.postValue( - Resource.success( - arrayListOf(newPublicShare1) - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare1.name)).check(matches(isDisplayed())) - - /** - * 2nd public share - */ - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare2 = publicShares[1] - savePublicShare(newPublicShare2) - - // New share properly created - sharesLiveData.postValue( - Resource.success( - publicShares.take(2) - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare2.name)).check(matches(isDisplayed())) - - /** - * 3rd public share - */ - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare3 = publicShares[2] - savePublicShare(newPublicShare3) - - // New share properly created - sharesLiveData.postValue( - Resource.success( - publicShares - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare3.name)).check(matches(isDisplayed())) - } - - @Test - fun createShareLoading() { - loadCapabilitiesSuccessfully() - loadSharesSuccessfully(arrayListOf()) - - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - savePublicShare(publicShares[0], Resource.loading()) - - onView(withText(R.string.common_loading)).check(matches(isDisplayed())) - } - - @Test - fun createShareError() { - loadCapabilitiesSuccessfully() - loadSharesSuccessfully(arrayListOf()) - - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - savePublicShare( - publicShares[0], - Resource.error( - RemoteOperationResult.ResultCode.FORBIDDEN, - exception = Exception("Error when retrieving shares") - ) - ) - - onView(withText(R.string.share_link_file_error)).check(matches(isDisplayed())) - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapability = TestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - Resource.success( - capability - ) - ) - } - - private fun loadSharesSuccessfully(shares: ArrayList = publicShares) { - sharesLiveData.postValue(Resource.success(shares)) - } - - private fun savePublicShare(newShare: OCShare, resource: Resource = Resource.success()) { - `when`( - ocShareViewModel.insertPublicShare( - file.remotePath, - 1, - newShare.name!!, - "", - -1, - false - ) - ).thenReturn( - MutableLiveData>().apply { - postValue(resource) - } - ) - - onView(withId(R.id.saveButton)).perform(click()) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/DeletePublicShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/DeletePublicShareTest.kt deleted file mode 100644 index 38d24f0ab5b..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/DeletePublicShareTest.kt +++ /dev/null @@ -1,325 +0,0 @@ -/** - * ownCloud Android client application - * - * @author Jesus Recio (@jesmrec) - * @author David González (@davigonz) - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.shares.domain.publicShares - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import android.os.Parcelable -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.assertion.ViewAssertions.doesNotExist -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.hasSibling -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator.KEY_AUTH_TOKEN_TYPE -import com.owncloud.android.capabilities.db.OCCapability -import com.owncloud.android.capabilities.viewmodel.OCCapabilityViewModel -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.shares.domain.OCShare -import com.owncloud.android.shares.presentation.OCShareViewModel -import com.owncloud.android.shares.presentation.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.TestUtil -import com.owncloud.android.vo.Resource -import org.hamcrest.Matchers.allOf -import org.hamcrest.Matchers.not -import org.junit.After -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module -import org.mockito.ArgumentMatchers -import org.mockito.Mockito.`when` -import org.mockito.Mockito.mock -import org.mockito.Mockito.spy - -class DeletePublicShareTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val publicShares = arrayListOf( - TestUtil.createPublicShare( // With no expiration date - path = "/Photos/image.jpg", - expirationDate = 0L, - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1" - ), - TestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg updated link", - shareLink = "http://server:port/s/2" - ) - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val sharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = mock(OCCapabilityViewModel::class.java) - private val ocShareViewModel = mock(OCShareViewModel::class.java) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = spy(Intent::class.java) - - file = getOCFileForTesting("image.jpg") - - `when`(intent.getParcelableExtra(FileActivity.EXTRA_FILE) as? Parcelable).thenReturn(file) - intent.putExtra(FileActivity.EXTRA_FILE, file) - - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(false)).thenReturn(capabilitiesLiveData) - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(true)).thenReturn(capabilitiesLiveData) - `when`(ocShareViewModel.getPublicShares(file.remotePath)).thenReturn(sharesLiveData) - `when`(ocShareViewModel.getPrivateShares(file.remotePath)).thenReturn(MutableLiveData()) - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @After - fun clean() { - stopKoin() - } - - @Test - fun deletePublicLink() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares.take(2) as ArrayList - loadSharesSuccessfully(existingPublicShare) - - `when`( - ocShareViewModel.deleteShare(ArgumentMatchers.anyLong()) - ).thenReturn( - MutableLiveData>().apply { - postValue(Resource.success()) - } - ) - - onView(allOf(withId(R.id.deletePublicLinkButton), hasSibling(withText(existingPublicShare[0].name)))) - .perform(click()) - onView(withId(android.R.id.button1)).perform(click()) - - sharesLiveData.postValue( - Resource.success( - arrayListOf(existingPublicShare[1]) - ) - ) - - onView(withText(existingPublicShare[0].name)).check(doesNotExist()) - onView(withText(existingPublicShare[1].name)).check(matches(isDisplayed())) - } - - @Test - fun deleteLastPublicLink() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - `when`( - ocShareViewModel.deleteShare(ArgumentMatchers.anyLong()) - ).thenReturn( - MutableLiveData>().apply { - postValue(Resource.success()) - } - ) - - onView(withId(R.id.deletePublicLinkButton)).perform(click()) - onView(withId(android.R.id.button1)).perform(click()) - - sharesLiveData.postValue( - Resource.success( - arrayListOf() - ) - ) - - onView(withText(existingPublicShare.name)).check(matches(not(isDisplayed()))) - onView(withText(R.string.share_no_public_links)).check(matches(isDisplayed())) - - } - - @Test - fun deletePublicLinkLoading() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - onView(withId(R.id.deletePublicLinkButton)).perform(click()) - - sharesLiveData.postValue( - Resource.loading( - publicShares - ) - ) - - onView(withText(R.string.common_loading)).check(matches(isDisplayed())) - } - - @Test - fun deletePublicLinkError() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - `when`( - ocShareViewModel.deleteShare(ArgumentMatchers.anyLong()) - ).thenReturn( - MutableLiveData>().apply { - postValue( - Resource.error( - RemoteOperationResult.ResultCode.FORBIDDEN, - exception = Exception("Error when retrieving shares") - ) - ) - } - ) - - onView(withId(R.id.deletePublicLinkButton)).perform(click()) - onView(withId(android.R.id.button1)).perform(click()) - - onView(withText(R.string.unshare_link_file_error)).check(matches(isDisplayed())) - } - - private fun getOCFileForTesting(name: String = "default"): OCFile { - val file = OCFile("/Photos/image.jpg") - file.availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - file.fileName = name - file.fileId = 9456985479 - file.remoteId = "1" - file.privateLink = "image link" - return file - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapability = TestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - Resource.success( - capability - ) - ) - } - - private fun loadSharesSuccessfully(shares: ArrayList = publicShares) { - sharesLiveData.postValue(Resource.success(shares)) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/EditPublicShareFolderTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/EditPublicShareFolderTest.kt deleted file mode 100644 index 3e7b1f28c57..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/EditPublicShareFolderTest.kt +++ /dev/null @@ -1,470 +0,0 @@ -/** - * ownCloud Android client application - * - * @author Jesús Recio (@jesmrec) - * @author David González (@davigonz) - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.shares.domain.publicShares - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import android.os.Parcelable -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.action.ViewActions.replaceText -import androidx.test.espresso.action.ViewActions.scrollTo -import androidx.test.espresso.assertion.ViewAssertions.doesNotExist -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.isChecked -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator.KEY_AUTH_TOKEN_TYPE -import com.owncloud.android.capabilities.db.OCCapability -import com.owncloud.android.capabilities.viewmodel.OCCapabilityViewModel -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.shares.domain.OCShare -import com.owncloud.android.shares.presentation.OCShareViewModel -import com.owncloud.android.shares.presentation.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.TestUtil -import com.owncloud.android.vo.Resource -import org.hamcrest.Matchers.not -import org.junit.After -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module -import org.mockito.Mockito.`when` -import org.mockito.Mockito.mock -import org.mockito.Mockito.spy - -class EditPublicShareFolderTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val publicShares = arrayListOf( - TestUtil.createPublicShare( - path = "/Photos/", - expirationDate = 0L, - permissions = 1, - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1" - ), - TestUtil.createPublicShare( // With name updated - path = "/Photos/", - expirationDate = 0L, - permissions = 1, - isFolder = true, - name = "Photos updated link", - shareLink = "http://server:port/s/1" - ), - TestUtil.createPublicShare( // With permission Download/View/Upload - path = "/Photos/", - expirationDate = 0L, - permissions = 15, - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1" - ), - TestUtil.createPublicShare( // With permission Upload only - path = "/Photos/", - expirationDate = 0L, - permissions = 4, - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1" - ), - TestUtil.createPublicShare( // With password - path = "/Photos/", - expirationDate = 0L, - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1", - shareWith = "1" - ) - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val sharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = mock(OCCapabilityViewModel::class.java) - private val ocShareViewModel = mock(OCShareViewModel::class.java) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = spy(Intent::class.java) - - file = getOCFileForTesting("Photos") - - `when`(intent.getParcelableExtra(FileActivity.EXTRA_FILE) as? Parcelable).thenReturn(file) - intent.putExtra(FileActivity.EXTRA_FILE, file) - - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(false)).thenReturn(capabilitiesLiveData) - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(true)).thenReturn(capabilitiesLiveData) - `when`(ocShareViewModel.getPublicShares(file.remotePath)).thenReturn(sharesLiveData) - `when`(ocShareViewModel.getPrivateShares(file.remotePath)).thenReturn(MutableLiveData()) - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @After - fun clean() { - stopKoin() - } - - @Test - fun editNameFolder() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[1] - - `when`( - ocShareViewModel.updatePublicShare( - 1, - updatedPublicShare.name!!, - "", - -1, - 1, - false - ) - ).thenReturn( - MutableLiveData>().apply { - postValue(Resource.success()) - } - ) - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkNameValue)).perform(replaceText(updatedPublicShare.name)) - - // 3. Save updated share - onView(withId(R.id.saveButton)).perform(scrollTo(), click()) - - // 4. Share properly updated - sharesLiveData.postValue( - Resource.success( - arrayListOf(updatedPublicShare) - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_edit_title)).check(doesNotExist()) - onView(withText(updatedPublicShare.name)).check(matches(isDisplayed())) - } - - @Test - fun editPermissionToDownloadViewUpload() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[2] - `when`( - ocShareViewModel.updatePublicShare( - 1, - updatedPublicShare.name!!, - "", - -1, - 15, - true - ) - ).thenReturn( - MutableLiveData>().apply { - postValue(Resource.success()) - } - ) - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkEditPermissionReadAndWrite)).perform(click()) - - // 3. Save updated share - onView(withId(R.id.saveButton)).perform(scrollTo(), click()) - - // 4. Share properly updated - sharesLiveData.postValue( - Resource.success( - arrayListOf(updatedPublicShare) - ) - ) - - // Open Dialog to check correct permission change - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkEditPermissionReadAndWrite)).check(matches(isChecked())) - - } - - @Test - fun editPermissionToUploadOnly() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[3] - `when`( - ocShareViewModel.updatePublicShare( - 1, - updatedPublicShare.name!!, - "", - -1, - 4, - true - ) - ).thenReturn( - MutableLiveData>().apply { - postValue(Resource.success()) - } - ) - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).perform(click()) - - // 3. Save updated share - onView(withId(R.id.saveButton)).perform(scrollTo(), click()) - - // 4. Share properly updated - sharesLiveData.postValue( - Resource.success( - arrayListOf(updatedPublicShare) - ) - ) - - // Open Dialog to check correct permission change - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).check(matches(isChecked())) - - } - - @Test - fun editPermissionToDownloadView() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[2] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[0] - `when`( - ocShareViewModel.updatePublicShare( - 1, - updatedPublicShare.name!!, - "", - -1, - 1, - false - ) - ).thenReturn( - MutableLiveData>().apply { - postValue(Resource.success()) - } - ) - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkEditPermissionReadOnly)).perform(click()) - - // 3. Save updated share - onView(withId(R.id.saveButton)).perform(scrollTo(), click()) - - // 4. Share properly updated - sharesLiveData.postValue( - Resource.success( - arrayListOf(updatedPublicShare) - ) - ) - - // Open Dialog to check correct permission change - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkEditPermissionReadOnly)).check(matches(isChecked())) - - } - - @Test - fun editPrivateShareSettingSharingPermissionLevelWithPasswordEnforced() { - loadCapabilitiesSuccessfully( - TestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value, - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE.value, - sharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE.value, - sharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicExpireDateEnabled = 1, - sharingPublicExpireDateDays = 10, - sharingPublicExpireDateEnforced = 1 - ) - ) - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - //Password not enforced with the set permission - onView(withId(R.id.shareViaLinkPasswordSwitch)).check(matches(not(isChecked()))) - - onView(withId(R.id.shareViaLinkPasswordLabel)) - .check(matches(withText(R.string.share_via_link_password_label))) - - //Changing permission makes the password to be enforced - onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).perform(click()) - - onView(withId(R.id.shareViaLinkPasswordLabel)) - .check(matches(withText(R.string.share_via_link_password_enforced_label))) - - onView(withId(R.id.shareViaLinkPasswordSwitch)).check(matches(isChecked())) - - } - - private fun getOCFileForTesting(name: String = "default"): OCFile { - val file = OCFile("/Photos") - file.availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - file.fileName = name - file.fileId = 9456985479 - file.remoteId = "1" - file.mimetype = "DIR" - file.privateLink = "private link" - return file - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapability = TestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value, - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - Resource.success( - capability - ) - ) - } - - private fun loadSharesSuccessfully(shares: ArrayList = publicShares) { - sharesLiveData.postValue(Resource.success(shares)) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/EditPublicShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/EditPublicShareTest.kt deleted file mode 100644 index 373776d5a40..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/domain/publicShares/EditPublicShareTest.kt +++ /dev/null @@ -1,474 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.shares.domain.publicShares - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import android.os.Parcelable -import android.widget.DatePicker -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.action.ViewActions.replaceText -import androidx.test.espresso.action.ViewActions.typeText -import androidx.test.espresso.assertion.ViewAssertions.doesNotExist -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.contrib.PickerActions -import androidx.test.espresso.matcher.ViewMatchers.isChecked -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.isNotChecked -import androidx.test.espresso.matcher.ViewMatchers.withClassName -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator.KEY_AUTH_TOKEN_TYPE -import com.owncloud.android.capabilities.db.OCCapability -import com.owncloud.android.capabilities.viewmodel.OCCapabilityViewModel -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.shares.domain.OCShare -import com.owncloud.android.shares.presentation.OCShareViewModel -import com.owncloud.android.shares.presentation.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.TestUtil -import com.owncloud.android.vo.Resource -import org.hamcrest.Matchers -import org.junit.After -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module -import org.mockito.Mockito.`when` -import org.mockito.Mockito.mock -import org.mockito.Mockito.spy -import java.text.DateFormat -import java.text.SimpleDateFormat -import java.util.Calendar - -class EditPublicShareTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val publicShares = arrayListOf( - TestUtil.createPublicShare( // With no expiration date - path = "/Photos/image.jpg", - expirationDate = 0L, - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1" - ), - TestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg updated link", - shareLink = "http://server:port/s/2" - ), - TestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg changed again link", - shareLink = "http://server:port/s/3" - ), - TestUtil.createPublicShare( // With password but not expiration date - path = "/Photos/image.jpg", - expirationDate = 0L, - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1", - shareWith = "1" - ), - TestUtil.createPublicShare( // With expiration date but not password - path = "/Photos/image.jpg", - expirationDate = 2587896257, - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1" - ) - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val sharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = mock(OCCapabilityViewModel::class.java) - private val ocShareViewModel = mock(OCShareViewModel::class.java) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = spy(Intent::class.java) - - file = getOCFileForTesting("image.jpg") - - `when`(intent.getParcelableExtra(FileActivity.EXTRA_FILE) as? Parcelable).thenReturn(file) - intent.putExtra(FileActivity.EXTRA_FILE, file) - - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(false)).thenReturn(capabilitiesLiveData) - `when`(ocCapabilityViewModel.getCapabilityForAccountAsLiveData(true)).thenReturn(capabilitiesLiveData) - `when`(ocShareViewModel.getPublicShares(file.remotePath)).thenReturn(sharesLiveData) - `when`(ocShareViewModel.getPrivateShares(file.remotePath)).thenReturn(MutableLiveData()) - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @After - fun clean() { - stopKoin() - } - - @Test - fun editName() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[1] - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkNameValue)).perform(replaceText(updatedPublicShare.name)) - - // 3. Edit public share with success - editPublicShare(updatedPublicShare, "", resource = Resource.success()) - - // 4. Share properly updated - sharesLiveData.postValue( - Resource.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_edit_title)).check(doesNotExist()) - onView(withText(updatedPublicShare.name)).check(matches(isDisplayed())) - } - - @Test - fun addPassword() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val password = "1234" - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Enable password and type it - onView(withId(R.id.shareViaLinkPasswordSwitch)).perform(click()) - onView(withId(R.id.shareViaLinkPasswordValue)).perform(typeText(password)) - - // 3. Edit public share with success - editPublicShare(existingPublicShare, "1234", resource = Resource.success()) - - // 4. Share properly updated - val updatedPublicShare = publicShares[3] - - sharesLiveData.postValue( - Resource.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Open dialog to check whether the password has been properly set - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkPasswordSwitch)).check(matches(isChecked())) - } - - @Test - fun removePassword() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[3] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Disable password - onView(withId(R.id.shareViaLinkPasswordSwitch)).perform(click()) - - // 3. Edit public share with success - editPublicShare(existingPublicShare, "", resource = Resource.success()) - - // 4. Share properly updated - val updatedPublicShare = publicShares[0] - - sharesLiveData.postValue( - Resource.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Open dialog to check whether the password has been properly disabled - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkPasswordSwitch)).check(matches(isNotChecked())) - } - - @Test - fun addExpirationDate() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val calendar = Calendar.getInstance() - calendar.add(Calendar.DAY_OF_YEAR, 1) - val formatter: DateFormat = SimpleDateFormat("MMM dd, yyyy"); - val expirationDate = formatter.format(calendar.time); - val publicLinkExpirationDateInMillis = formatter.parse(expirationDate).time - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Enable expiration date and set it - onView(withId(R.id.shareViaLinkExpirationSwitch)).perform(click()) - onView(withClassName(Matchers.equalTo(DatePicker::class.java.name))).perform( - PickerActions.setDate( - calendar.get(Calendar.YEAR), - calendar.get(Calendar.MONTH) + 1, // January code is 0, so let's add 1 - calendar.get(Calendar.DATE) - ) - ); - onView(withId(android.R.id.button1)).perform(click()) - - // 3. Edit public share with success - editPublicShare(existingPublicShare, "", publicLinkExpirationDateInMillis, Resource.success()) - - // 4. Share properly updated - val updatedPublicShare = publicShares[4] - - sharesLiveData.postValue( - Resource.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Open dialog to check whether the expiration date is enabled - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkExpirationSwitch)).check(matches(isChecked())) - } - - @Test - fun removeExpirationDate() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[4] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Disable expiration date - onView(withId(R.id.shareViaLinkExpirationSwitch)).perform(click()) - - // 3. Edit public share with success - editPublicShare(existingPublicShare, "", resource = Resource.success()) - - // 4. Share properly updated - val updatedPublicShare = publicShares[0] - - sharesLiveData.postValue( - Resource.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Open dialog to check whether the expiration date is disabled - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkExpirationSwitch)).check(matches(isNotChecked())) - } - - @Test - fun editShareLoading() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[3] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - editPublicShare(existingPublicShare, resource = Resource.loading()) - - onView(withText(R.string.common_loading)).check(matches(isDisplayed())) - } - - @Test - fun editShareError() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - editPublicShare( - existingPublicShare, - password = "", - resource = Resource.error( - RemoteOperationResult.ResultCode.FORBIDDEN, - exception = Exception("Error when retrieving shares") - ) - ) - - onView(withText(R.string.update_link_file_error)).check(matches(isDisplayed())) - } - - private fun getOCFileForTesting(name: String = "default") = OCFile("/Photos").apply { - availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - fileName = name - fileId = 9456985479 - remoteId = "1" - privateLink = "private link" - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapability = TestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - Resource.success( - capability - ) - ) - } - - private fun loadSharesSuccessfully(shares: ArrayList = publicShares) { - sharesLiveData.postValue(Resource.success(shares)) - } - - private fun editPublicShare( - share: OCShare, - password: String? = null, - publicLinkExpirationDateInMillis: Long = -1, - resource: Resource = Resource.success() // Expected result when editing the share - ) { - `when`( - ocShareViewModel.updatePublicShare( - 1, - share.name!!, - password, - publicLinkExpirationDateInMillis, - 1, - false - ) - ).thenReturn( - MutableLiveData>().apply { - postValue(resource) - } - ) - - onView(withId(R.id.saveButton)).perform(click()) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/sharees/views/SearchShareesFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt similarity index 97% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/sharees/views/SearchShareesFragmentTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt index 696868064c6..c62ba83cff4 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/sharees/views/SearchShareesFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.sharing.sharees.views +package com.owncloud.android.sharing.sharees.ui import android.accounts.Account import androidx.test.espresso.Espresso.onView @@ -36,7 +36,7 @@ import com.owncloud.android.datamodel.OCFile import com.owncloud.android.lib.resources.shares.ShareType import com.owncloud.android.lib.resources.status.OwnCloudVersion import com.owncloud.android.presentation.ui.sharing.fragments.SearchShareesFragment -import com.owncloud.android.presentation.sharing.shares.views.TestShareFileActivity +import com.owncloud.android.sharing.shares.ui.TestShareFileActivity import com.owncloud.android.utils.AppTestUtil import io.mockk.every import io.mockk.mockkClass diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt similarity index 98% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt index 74afe92c1e0..ecd950c2627 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.sharing.sharees.viewmodels +package com.owncloud.android.sharing.sharees.viewmodels import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/CreatePublicShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/CreatePublicShareTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/flow/CreatePublicShareTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/CreatePublicShareTest.kt index befb796b87b..c0bd2f115fc 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/CreatePublicShareTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/CreatePublicShareTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.flow +package com.owncloud.android.sharing.shares.flow import android.accounts.Account import android.accounts.AccountManager diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/DeletePublicShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/DeletePublicShareTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/flow/DeletePublicShareTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/DeletePublicShareTest.kt index f0add3dc617..fa2677a5c0c 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/DeletePublicShareTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/DeletePublicShareTest.kt @@ -18,7 +18,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.flow +package com.owncloud.android.sharing.shares.flow import android.accounts.Account import android.accounts.AccountManager diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/EditPublicShareFolderTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareFolderTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/flow/EditPublicShareFolderTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareFolderTest.kt index 36b255c0f74..8aeba032a74 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/EditPublicShareFolderTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareFolderTest.kt @@ -18,7 +18,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.flow +package com.owncloud.android.sharing.shares.flow import android.accounts.Account import android.accounts.AccountManager diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/EditPublicShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/flow/EditPublicShareTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareTest.kt index 59716aec6aa..91bfed0fa8c 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/EditPublicShareTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.flow +package com.owncloud.android.sharing.shares.flow import android.accounts.Account import android.accounts.AccountManager diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/LoadSharesTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/LoadSharesTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/flow/LoadSharesTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/LoadSharesTest.kt index bc69636c44b..31507cfa18b 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/flow/LoadSharesTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/LoadSharesTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.flow +package com.owncloud.android.sharing.shares.flow import android.accounts.Account import android.accounts.AccountManager diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/presentation/ui/EditPrivateShareFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/shares/presentation/ui/EditPrivateShareFragmentTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt index f4d8875233d..ee894fe1bc9 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/shares/presentation/ui/EditPrivateShareFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.shares.presentation.ui +package com.owncloud.android.sharing.shares.ui import android.accounts.Account import android.accounts.AccountManager @@ -37,7 +37,7 @@ import com.owncloud.android.authentication.AccountAuthenticator import com.owncloud.android.datamodel.OCFile import com.owncloud.android.lib.common.accounts.AccountUtils import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.shares.domain.OCShare +import com.owncloud.android.sharing.domain.OCShare import com.owncloud.android.presentation.ui.sharing.fragments.EditPrivateShareFragment import com.owncloud.android.utils.AccountsManager import com.owncloud.android.utils.Permissions diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/PublicShareCreationDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/PublicShareCreationDialogFragmentTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt index e285f5930d4..3e7ee398c13 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/PublicShareCreationDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.sharing.shares.views +package com.owncloud.android.sharing.shares.ui import android.text.InputType.TYPE_CLASS_TEXT import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/PublicShareEditionDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt similarity index 98% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/PublicShareEditionDialogFragmentTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt index 9b2bae9b121..2c2297e1854 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/PublicShareEditionDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.sharing.shares.views +package com.owncloud.android.sharing.shares.ui import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/ShareFileFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/ShareFileFragmentTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt index f09168994f2..c40722336bf 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/ShareFileFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.sharing.shares.views +package com.owncloud.android.sharing.shares.ui import android.accounts.Account import androidx.test.espresso.Espresso.onView diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/ShareFolderFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt similarity index 98% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/ShareFolderFragmentTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt index fc086479e7e..c252c8b1268 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/ShareFolderFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt @@ -18,7 +18,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.sharing.shares.views +package com.owncloud.android.sharing.shares.ui import android.accounts.Account import androidx.test.espresso.Espresso.onView diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/SharesContentProviderTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/SharesContentProviderTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/SharesContentProviderTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/SharesContentProviderTest.kt index 693e691bbb5..21b4504b484 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/SharesContentProviderTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/SharesContentProviderTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.sharing.shares.views +package com.owncloud.android.sharing.shares.ui import android.content.ContentResolver import android.content.ContentValues diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/TestShareFileActivity.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/TestShareFileActivity.kt similarity index 98% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/TestShareFileActivity.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/TestShareFileActivity.kt index c9279486743..0493320cdc5 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/views/TestShareFileActivity.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/TestShareFileActivity.kt @@ -18,7 +18,7 @@ * */ -package com.owncloud.android.presentation.sharing.shares.views +package com.owncloud.android.sharing.shares.ui import com.owncloud.android.data.capabilities.db.OCCapabilityEntity import com.owncloud.android.data.sharing.shares.db.OCShareEntity diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/viewmodels/OCShareViewModelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt similarity index 99% rename from owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/viewmodels/OCShareViewModelTest.kt rename to owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt index 2605e592929..3a406e95368 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/presentation/sharing/shares/viewmodels/OCShareViewModelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.sharing.shares.viewmodels +package com.owncloud.android.sharing.shares.viewmodels import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule diff --git a/owncloudApp/src/debug/AndroidManifest.xml b/owncloudApp/src/debug/AndroidManifest.xml index b688ed401e8..ba767eb41ae 100644 --- a/owncloudApp/src/debug/AndroidManifest.xml +++ b/owncloudApp/src/debug/AndroidManifest.xml @@ -20,7 +20,7 @@ - + \ No newline at end of file diff --git a/owncloudApp/src/test/java/com/owncloud/android/ErrorMessageAdapterUnitTest.java b/owncloudApp/src/test/java/com/owncloud/android/ErrorMessageAdapterUnitTest.java deleted file mode 100644 index 195c78bc005..00000000000 --- a/owncloudApp/src/test/java/com/owncloud/android/ErrorMessageAdapterUnitTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David A. Velasco - * Copyright (C) 2018 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - * - */ - -package com.owncloud.android; - -import android.content.res.Resources; - -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.operations.RemoveFileOperation; -import com.owncloud.android.ui.errorhandling.ErrorMessageAdapter; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.when; - -/** - * Local unit test, to be run out of Android emulator or device. - * - * At the moment, it's a sample to validate the automatic test environment, in the scope of local unit tests with - * mock Android dependencies. - * - * Don't take it as an example of completeness. - * - * See http://developer.android.com/intl/es/training/testing/unit-testing/local-unit-tests.html . - */ -@RunWith(MockitoJUnitRunner.class) -public class ErrorMessageAdapterUnitTest { - - private final static String MOCK_FORBIDDEN_PERMISSIONS = "You do not have permission %s"; - private final static String MOCK_TO_DELETE = "to delete this file"; - private final static String PATH_TO_DELETE = "/path/to/a.file"; - private final static String EXPECTED_ERROR_MESSAGE = "You do not have permission to delete this file"; - - @Mock - Resources mMockResources; - - @Test - public void getErrorCauseMessageForForbiddenRemoval() { - // Given a mocked set of resources passed to the object under test... - when(mMockResources.getString(R.string.forbidden_permissions)) - .thenReturn(MOCK_FORBIDDEN_PERMISSIONS); - when(mMockResources.getString(R.string.forbidden_permissions_delete)) - .thenReturn(MOCK_TO_DELETE); - - // ... when method under test is called ... - String errorMessage = ErrorMessageAdapter.Companion.getResultMessage( - new RemoteOperationResult(RemoteOperationResult.ResultCode.FORBIDDEN), - new RemoveFileOperation(PATH_TO_DELETE, false, false), - mMockResources - ); - - // ... then the result should be the expected one. - assertThat(errorMessage, is(EXPECTED_ERROR_MESSAGE)); - - } -} \ No newline at end of file diff --git a/owncloudApp/src/test/java/com/owncloud/android/shares/data/RemoteShareDataSourceTest.kt b/owncloudApp/src/test/java/com/owncloud/android/shares/data/RemoteShareDataSourceTest.kt deleted file mode 100644 index 25d83aad1ab..00000000000 --- a/owncloudApp/src/test/java/com/owncloud/android/shares/data/RemoteShareDataSourceTest.kt +++ /dev/null @@ -1,74 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.shares.data - -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.CreateRemoteShareOperation -import com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation -import com.owncloud.android.lib.resources.shares.RemoveRemoteShareOperation -import com.owncloud.android.lib.resources.shares.ShareParserResult -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.lib.resources.shares.UpdateRemoteShareOperation -import com.owncloud.android.shares.data.datasources.RemoteShareDataSource - -class RemoteShareDataSourceTest(private val remoteOperationResult: RemoteOperationResult) : - RemoteShareDataSource { - override fun getShares( - remoteFilePath: String, - reshares: Boolean, - subfiles: Boolean, - getRemoteSharesForFileOperation: GetRemoteSharesForFileOperation - ): RemoteOperationResult { - return remoteOperationResult - } - - override fun insertShare( - remoteFilePath: String, - shareType: ShareType, - shareWith: String, - permissions: Int, - name: String, - password: String, - expirationDate: Long, - publicUpload: Boolean, - createRemoteShareOperation: CreateRemoteShareOperation - ): RemoteOperationResult { - return remoteOperationResult - } - - override fun updateShare( - remoteId: Long, - name: String, - password: String?, - expirationDateInMillis: Long, - permissions: Int, - publicUpload: Boolean, - updateRemoteShareOperation: UpdateRemoteShareOperation - ): RemoteOperationResult { - return remoteOperationResult - } - - override fun deleteShare( - remoteId: Long, - removeRemoteShareOperation: RemoveRemoteShareOperation - ): RemoteOperationResult { - return remoteOperationResult - } -} From 743f84be533252097c3f6953d5ad782504fa8bc7 Mon Sep 17 00:00:00 2001 From: davigonz Date: Tue, 19 Nov 2019 09:37:17 +0100 Subject: [PATCH 10/41] Include viewmodels --- .../viewmodels/OCCapabilityViewModelTest.kt | 165 ++++-- .../viewmodels/OCShareeViewmodelTest.kt | 10 +- .../shares/viewmodels/OCShareViewModelTest.kt | 544 ++++++++++++------ 3 files changed, 473 insertions(+), 246 deletions(-) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt index 50239c15162..5ea27595e71 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt @@ -2,6 +2,7 @@ * ownCloud Android client application * * @author David González Verdugo + * @author Abel García de Prada * Copyright (C) 2019 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify @@ -17,21 +18,30 @@ * along with this program. If not, see . */ -package com.owncloud.android.capabilities.viewmodels +package com.owncloud.android.presentation.capabilities.viewmodel import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData -import androidx.test.platform.app.InstrumentationRegistry -import com.owncloud.android.data.DataResult -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.domain.capabilities.OCCapabilityRepository +import com.owncloud.android.domain.UseCaseResult +import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.domain.capabilities.usecases.GetStoredCapabilitiesUseCase +import com.owncloud.android.domain.capabilities.usecases.RefreshCapabilitiesFromServerAsyncUseCase +import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.utils.AppTestUtil +import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY +import com.owncloud.android.utils.LiveDataTestUtil.getOrAwaitValues +import com.owncloud.android.utils.TIMEOUT_TEST_LONG +import io.mockk.coEvery +import io.mockk.coVerify import io.mockk.every import io.mockk.mockkClass -import junit.framework.Assert.assertEquals -import org.junit.Before +import io.mockk.spyk +import io.mockk.unmockkAll +import io.mockk.verify +import org.junit.After +import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -39,72 +49,121 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class OCCapabilityViewModelTest { + private lateinit var ocCapabilityViewModel: OCCapabilityViewModel + + private lateinit var getStoredCapabilitiesUseCase: GetStoredCapabilitiesUseCase + private lateinit var refreshCapabilitiesFromServerUseCase: RefreshCapabilitiesFromServerAsyncUseCase + + private val capabilityLiveData = MutableLiveData() + private var testAccount: Account = AppTestUtil.createAccount("admin@server", "test") - private lateinit var capability: OCCapabilityEntity @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() - @Before - fun init() { - capability = AppTestUtil.createCapability("admin@server", 2, 1, 0) + @After + fun tearDown() { + unmockkAll() + } + + private fun initTest() { + getStoredCapabilitiesUseCase = spyk(mockkClass(GetStoredCapabilitiesUseCase::class)) + refreshCapabilitiesFromServerUseCase = spyk(mockkClass(RefreshCapabilitiesFromServerAsyncUseCase::class)) + + every { getStoredCapabilitiesUseCase.execute(any()) } returns capabilityLiveData + + ocCapabilityViewModel = OCCapabilityViewModel( + accountName = testAccount.name, + getStoredCapabilitiesUseCase = getStoredCapabilitiesUseCase, + refreshCapabilitiesFromServerUseCase = refreshCapabilitiesFromServerUseCase + ) } @Test - fun loadCapability() { - val ocCapabilityRepository = mockkClass(OCCapabilityRepository::class) - - every { - ocCapabilityRepository.refreshCapabilitiesForAccount( - "admin@server" - ) - } returns MutableLiveData>().apply { - value = DataResult.success(capability) - } - - val context = InstrumentationRegistry.getInstrumentation().targetContext - - val ocCapabilityViewModel = OCCapabilityViewModel( - context, - account = testAccount, - capabilityRepository = ocCapabilityRepository + fun getStoredCapabilitiesWithData() { + initTest() + + val capability = DUMMY_CAPABILITY.copy(accountName = testAccount.name) + + getStoredCapabilitiesVerification( + valueToTest = capability, + expectedValue = UIResult.Success(capability) ) + } - val resource: DataResult? = ocCapabilityViewModel.getCapabilityForAccount().value - val capability: OCCapabilityEntity? = resource?.data + @Test + fun getStoredCapabilitiesWithoutData() { + initTest() - assertEquals("admin@server", capability?.accountName) - assertEquals(2, capability?.versionMayor) - assertEquals(1, capability?.versionMinor) - assertEquals(0, capability?.versionMicro) + getStoredCapabilitiesVerification( + valueToTest = null, + expectedValue = null + ) } @Test - fun loadCapability() { - val ocCapabilityRepository = mock(OCCapabilityRepository::class.java) - - `when`( - ocCapabilityRepository.getStoredCapabilityForAccount( - "admin@server" - ) - ).thenReturn( - capability + fun fetchCapabilitiesLoading() { + initTest() + + fetchCapabilitiesVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Loading() ) + } - val context = InstrumentationRegistry.getInstrumentation().targetContext + @Test + fun fetchCapabilitiesError() { + initTest() + + val error = Throwable() + fetchCapabilitiesVerification( + valueToTest = UseCaseResult.Error(error), + expectedValue = UIResult.Error(error), + expectedOnPosition = 2 + ) + } - val ocCapabilityViewModel = OCCapabilityViewModel( - context, - account = testAccount, - capabilityRepository = ocCapabilityRepository + @Test + fun fetchCapabilitiesSuccess() { + initTest() + + //Expect a null since we are mocking refreshCapabilities and we are not storing new capabilities on db + fetchCapabilitiesVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = null, + expectedOnPosition = 2 ) + } + + private fun getStoredCapabilitiesVerification( + valueToTest: OCCapability?, + expectedValue: UIResult?, + expectedOnPosition: Int = 1 + ) { + capabilityLiveData.postValue(valueToTest) + + val value = ocCapabilityViewModel.capabilities.getOrAwaitValues() + assertEquals(expectedValue, value[expectedOnPosition - 1]) + + coVerify(exactly = 0) { refreshCapabilitiesFromServerUseCase.execute(any()) } + verify(exactly = 1) { getStoredCapabilitiesUseCase.execute(any()) } + } + + private fun fetchCapabilitiesVerification( + valueToTest: UseCaseResult, + expectedValue: UIResult?, + expectedOnPosition: Int = 1 + ) { + coEvery { refreshCapabilitiesFromServerUseCase.execute(any()) } returns valueToTest + + ocCapabilityViewModel.refreshCapabilitiesFromNetwork() - val capability: OCCapability? = ocCapabilityViewModel.getStoredCapabilityForAccount() + val value = ocCapabilityViewModel.capabilities.getOrAwaitValues(expectedOnPosition) + assertEquals(expectedValue, value[expectedOnPosition - 1]) - assertEquals("admin@server", capability?.accountName) - assertEquals(2, capability?.versionMayor) - assertEquals(1, capability?.versionMinor) - assertEquals(0, capability?.versionMicro) + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { refreshCapabilitiesFromServerUseCase.execute(any()) } + //Just once on init + verify(exactly = 1) { getStoredCapabilitiesUseCase.execute(any()) } } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt index ecd950c2627..8d42d5691f0 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt @@ -17,16 +17,13 @@ * along with this program. If not, see . */ -package com.owncloud.android.sharing.sharees.viewmodels +package com.owncloud.android.presentation.sharing.sharees.viewmodels import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.platform.app.InstrumentationRegistry -import com.owncloud.android.data.DataResult -import com.owncloud.android.domain.sharing.sharees.OCShareeRepository +import com.owncloud.android.data.sharing.sharees.repository.OCShareeRepository import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.presentation.viewmodels.sharing.OCShareeViewModel import com.owncloud.android.utils.AppTestUtil import io.mockk.every import io.mockk.mockkClass @@ -44,7 +41,8 @@ class OCShareeViewmodelTest { val instantExecutorRule = InstantTaskExecutorRule() private var testAccount: Account = AppTestUtil.createAccount("admin@server", "test") - private var ocShareeRepository: OCShareeRepository = mockkClass(OCShareeRepository::class) + private var ocShareeRepository: OCShareeRepository = mockkClass( + OCShareeRepository::class) @Test fun loadSharees() { diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt index 3a406e95368..ea02c137a97 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt @@ -2,6 +2,7 @@ * ownCloud Android client application * * @author David González Verdugo + * @author Abel García de Prada * Copyright (C) 2019 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify @@ -17,21 +18,35 @@ * along with this program. If not, see . */ -package com.owncloud.android.sharing.shares.viewmodels +package com.owncloud.android.presentation.sharing.shares.viewmodels import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData -import androidx.test.platform.app.InstrumentationRegistry -import com.owncloud.android.data.DataResult -import com.owncloud.android.data.Status -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.domain.sharing.shares.OCShareRepository -import com.owncloud.android.lib.resources.shares.ShareType +import com.owncloud.android.domain.UseCaseResult +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.usecases.CreatePrivateShareAsyncUseCase +import com.owncloud.android.domain.sharing.shares.usecases.CreatePublicShareAsyncUseCase +import com.owncloud.android.domain.sharing.shares.usecases.DeleteShareAsyncUseCase +import com.owncloud.android.domain.sharing.shares.usecases.EditPrivateShareAsyncUseCase +import com.owncloud.android.domain.sharing.shares.usecases.EditPublicShareAsyncUseCase +import com.owncloud.android.domain.sharing.shares.usecases.GetShareAsLiveDataUseCase +import com.owncloud.android.domain.sharing.shares.usecases.GetSharesAsLiveDataUseCase +import com.owncloud.android.domain.sharing.shares.usecases.RefreshSharesFromServerAsyncUseCase +import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel import com.owncloud.android.utils.AppTestUtil +import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE +import com.owncloud.android.utils.TIMEOUT_TEST_LONG +import com.owncloud.android.utils.LiveDataTestUtil.getOrAwaitValues +import io.mockk.coEvery +import io.mockk.coVerify import io.mockk.every import io.mockk.mockkClass +import io.mockk.spyk +import io.mockk.unmockkAll +import io.mockk.verify +import org.junit.After import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test @@ -40,106 +55,192 @@ import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class OCShareViewModelTest { + private lateinit var ocShareViewModel: OCShareViewModel + + private lateinit var getSharesAsLiveDataUseCase: GetSharesAsLiveDataUseCase + private lateinit var getShareAsLiveDataUseCase: GetShareAsLiveDataUseCase + private lateinit var refreshSharesFromServerAsyncUseCase: RefreshSharesFromServerAsyncUseCase + private lateinit var createPrivateShareAsyncUseCase: CreatePrivateShareAsyncUseCase + private lateinit var editPrivateShareAsyncUseCase: EditPrivateShareAsyncUseCase + private lateinit var createPublicShareAsyncUseCase: CreatePublicShareAsyncUseCase + private lateinit var editPublicShareAsyncUseCase: EditPublicShareAsyncUseCase + private lateinit var deletePublicShareAsyncUseCase: DeleteShareAsyncUseCase + + private val filePath = "/Photos/image.jpg" + + private var testAccount: Account = AppTestUtil.createAccount("admin@server", "test") + + private val sharesLiveData = MutableLiveData?>() + private val privateShareLiveData = MutableLiveData() + @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() - private val filePath = "/Photos/image.jpg" + @After + fun tearDown() { + unmockkAll() + } - private var testAccount: Account = AppTestUtil.createAccount("admin@server", "test") - private var ocShareRepository: OCShareRepository = mockkClass(OCShareRepository::class) + private fun initTest() { + getSharesAsLiveDataUseCase = spyk(mockkClass(GetSharesAsLiveDataUseCase::class)) + getShareAsLiveDataUseCase = spyk(mockkClass(GetShareAsLiveDataUseCase::class)) + refreshSharesFromServerAsyncUseCase = spyk(mockkClass(RefreshSharesFromServerAsyncUseCase::class)) + createPrivateShareAsyncUseCase = spyk(mockkClass(CreatePrivateShareAsyncUseCase::class)) + editPrivateShareAsyncUseCase = spyk(mockkClass(EditPrivateShareAsyncUseCase::class)) + createPublicShareAsyncUseCase = spyk(mockkClass(CreatePublicShareAsyncUseCase::class)) + editPublicShareAsyncUseCase = spyk(mockkClass(EditPublicShareAsyncUseCase::class)) + deletePublicShareAsyncUseCase = spyk(mockkClass(DeleteShareAsyncUseCase::class)) + + every { getSharesAsLiveDataUseCase.execute(any()) } returns sharesLiveData + every { getShareAsLiveDataUseCase.execute(any()) } returns privateShareLiveData + + ocShareViewModel = OCShareViewModel( + filePath, + testAccount.name, + getSharesAsLiveDataUseCase, + getShareAsLiveDataUseCase, + refreshSharesFromServerAsyncUseCase, + createPrivateShareAsyncUseCase, + editPrivateShareAsyncUseCase, + createPublicShareAsyncUseCase, + editPublicShareAsyncUseCase, + deletePublicShareAsyncUseCase + ) + } /****************************************************************************************************** ******************************************* PRIVATE SHARES ******************************************* ******************************************************************************************************/ @Test - fun loadPrivateShares() { - val privateShares = mutableListOf( - AppTestUtil.createPrivateShare( - path = filePath, - isFolder = false, - shareWith = "username1", - sharedWithDisplayName = "Tim" - ), - AppTestUtil.createPrivateShare( - path = filePath, - isFolder = false, - shareWith = "username2", - sharedWithDisplayName = "Tom" - ) + fun insertPrivateShareLoading() { + initTest() + + insertPrivateShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Loading(), + expectedOnPosition = 1 ) + } - every { ocShareRepository.refreshSharesFromNetwork(filePath) } returns - MutableLiveData>>().apply { - value = DataResult.success(privateShares) - } + @Test + fun insertPrivateShareSuccess() { + initTest() + + insertPrivateShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Success(), + expectedOnPosition = 2 + ) + } + + @Test + fun insertPrivateShareError() { + initTest() - // Viewmodel that will ask ocShareRepository for shares - val ocShareViewModel = createOCShareViewModel(ocShareRepository) + val error = Throwable() - val resource: DataResult>? = ocShareViewModel.getPrivateShares(filePath).value - assertPrivateShareParameters(resource?.data) + insertPrivateShareVerification( + valueToTest = UseCaseResult.Error(error), + expectedValue = UIResult.Error(error), + expectedOnPosition = 2 + ) } @Test - fun insertPrivateShare() { - every { - ocShareRepository.insertPrivateShare( - filePath, - ShareType.GROUP, - "user", - -1 - ) - } returns MutableLiveData>().apply { - value = DataResult.success() - } + fun updatePrivateShareLoading() { + initTest() - // Viewmodel that will ask ocShareRepository for shares - val ocShareViewModel = createOCShareViewModel(ocShareRepository) + updatePrivateShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Loading(), + expectedOnPosition = 1 + ) + } - val resource: DataResult? = ocShareViewModel.insertPrivateShare( - filePath, - ShareType.GROUP, - "user", - -1 - ).value + @Test + fun updatePrivateShareSuccess() { + initTest() - assertEquals(Status.SUCCESS, resource?.status) + updatePrivateShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Success(), + expectedOnPosition = 2 + ) } @Test - fun updatePrivateShare() { - `when`( - ocShareRepository.updatePrivateShare( - 1, - 17 - ) - ).thenReturn( - MutableLiveData>().apply { - value = Resource.success() - } + fun refreshPrivateShareSuccess() { + initTest() + + val ocShare = DUMMY_SHARE.copy(id = 123, name = "PhotoLink") + privateShareLiveData.postValue(ocShare) + + refreshPrivateShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Success(ocShare), + expectedOnPosition = 1 ) + } + + private fun refreshPrivateShareVerification( + valueToTest: UseCaseResult, + expectedValue: UIResult?, + expectedOnPosition: Int = 1 + ) { + coEvery { createPrivateShareAsyncUseCase.execute(any()) } returns valueToTest - // Viewmodel that will ask ocShareRepository for shares - val ocShareViewModel = createOCShareViewModel(ocShareRepository) + ocShareViewModel.refreshPrivateShare(DUMMY_SHARE.remoteId) - val resource: Resource? = ocShareViewModel.updatePrivateShare( - 1, - 17 - ).value + val value = ocShareViewModel.privateShare.getOrAwaitValues(expectedOnPosition) + assertEquals(expectedValue, value[expectedOnPosition - 1]) - assertEquals(Status.SUCCESS, resource?.status) + verify(exactly = 1) { getShareAsLiveDataUseCase.execute(GetShareAsLiveDataUseCase.Params(DUMMY_SHARE.remoteId)) } + // Just once on init + verify(exactly = 1) { getSharesAsLiveDataUseCase.execute(any()) } } - private fun assertPrivateShareParameters(shares: List?) { - assertCommonShareParameters(shares) + private fun insertPrivateShareVerification( + valueToTest: UseCaseResult, + expectedValue: UIResult?, + expectedOnPosition: Int = 1 + ) { + coEvery { createPrivateShareAsyncUseCase.execute(any()) } returns valueToTest + + ocShareViewModel.insertPrivateShare( + filePath = DUMMY_SHARE.path, + shareType = DUMMY_SHARE.shareType, + shareeName = DUMMY_SHARE.accountOwner, + permissions = DUMMY_SHARE.permissions, + accountName = DUMMY_SHARE.accountOwner + ) - assertEquals("username1", shares?.get(0)?.shareWith) - assertEquals("Tim", shares?.get(0)?.sharedWithDisplayName) + val value = ocShareViewModel.privateShareCreationStatus.getOrAwaitValues(expectedOnPosition) + assertEquals(expectedValue, value[expectedOnPosition - 1]) - assertEquals("username2", shares?.get(1)?.shareWith) - assertEquals("Tom", shares?.get(1)?.sharedWithDisplayName) + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { createPrivateShareAsyncUseCase.execute(any()) } + coVerify(exactly = 0) { createPublicShareAsyncUseCase.execute(any()) } + } + + private fun updatePrivateShareVerification( + valueToTest: UseCaseResult, + expectedValue: UIResult?, + expectedOnPosition: Int = 1 + ) { + coEvery { editPrivateShareAsyncUseCase.execute(any()) } returns valueToTest + + ocShareViewModel.updatePrivateShare( + remoteId = DUMMY_SHARE.remoteId, + permissions = DUMMY_SHARE.permissions, + accountName = DUMMY_SHARE.accountOwner + ) + + val value = ocShareViewModel.privateShareEditionStatus.getOrAwaitValues(expectedOnPosition) + assertEquals(expectedValue, value[expectedOnPosition - 1]) + + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { editPrivateShareAsyncUseCase.execute(any()) } + coVerify(exactly = 0) { editPublicShareAsyncUseCase.execute(any()) } } /****************************************************************************************************** @@ -147,102 +248,121 @@ class OCShareViewModelTest { ******************************************************************************************************/ @Test - fun loadPublicShares() { - val publicShares = mutableListOf( - AppTestUtil.createPublicShare( - path = filePath, - isFolder = false, - name = "Photos 1 link", - shareLink = "http://server:port/s/1" - ), - AppTestUtil.createPublicShare( - path = filePath, - isFolder = false, - name = "Photos 2 link", - shareLink = "http://server:port/s/2" - ) + fun insertPublicShareLoading() { + initTest() + + insertPublicShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Loading(), + expectedOnPosition = 1 + ) + } + + @Test + fun insertPublicShareSuccess() { + initTest() + + insertPublicShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Success(), + expectedOnPosition = 2 ) + } - every { ocShareRepository.refreshPublicShares(filePath) } returns - MutableLiveData>>().apply { - value = DataResult.success(publicShares) - } + @Test + fun insertPublicShareError() { + initTest() - // Viewmodel that will ask ocShareRepository for shares - val ocShareViewModel = createOCShareViewModel(ocShareRepository) + val error = Throwable() - val resource: DataResult>? = ocShareViewModel.getPublicShares(filePath).value - assertPublicShareParameters(resource?.data) + insertPublicShareVerification( + valueToTest = UseCaseResult.Error(error), + expectedValue = UIResult.Error(error), + expectedOnPosition = 2 + ) } @Test - fun insertPublicShare() { - every { - ocShareRepository.insertPublicShare( - filePath, - 1, - "Photos 2 link", - "1234", - -1, - false - ) - } returns MutableLiveData>().apply { - value = DataResult.success() - } + fun updatePublicShareLoading() { + initTest() + + updatePublicShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Loading(), + expectedOnPosition = 1 + ) + } - // Viewmodel that will ask ocShareRepository for shares - val ocShareViewModel = createOCShareViewModel(ocShareRepository) + @Test + fun updatePublicShareSuccess() { + initTest() - val resource: DataResult? = ocShareViewModel.insertPublicShare( - filePath, - 1, - "Photos 2 link", - "1234", - -1, - false - ).value - - assertEquals(Status.SUCCESS, resource?.status) + updatePublicShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Success(), + expectedOnPosition = 2 + ) } @Test - fun updatePublicShare() { - every { - ocShareRepository.updatePublicShare( - 1, - "Photos 1 link", - "123456", - 1000, - 1, - false - ) - } returns MutableLiveData>().apply { - value = DataResult.success() - } + fun updatePublicShareError() { + initTest() - // Viewmodel that will ask ocShareRepository for shares - val ocShareViewModel = createOCShareViewModel(ocShareRepository) + val error = Throwable() - val resource: DataResult? = ocShareViewModel.updatePublicShare( - 1, - "Photos 1 link", - "123456", - 1000, - 1, - false - ).value + updatePublicShareVerification( + valueToTest = UseCaseResult.Error(error), + expectedValue = UIResult.Error(error), + expectedOnPosition = 2 + ) + } + + private fun insertPublicShareVerification( + valueToTest: UseCaseResult, + expectedValue: UIResult?, + expectedOnPosition: Int = 1 + ) { + coEvery { createPublicShareAsyncUseCase.execute(any()) } returns valueToTest + + ocShareViewModel.insertPublicShare( + filePath = DUMMY_SHARE.path, + name = "Photos 2 link", + password = "1234", + expirationTimeInMillis = -1, + publicUpload = false, + permissions = DUMMY_SHARE.permissions, + accountName = DUMMY_SHARE.accountOwner + ) - assertEquals(Status.SUCCESS, resource?.status) + val value = ocShareViewModel.publicShareCreationStatus.getOrAwaitValues(expectedOnPosition) + assertEquals(expectedValue, value[expectedOnPosition - 1]) + + coVerify(exactly = 0) { createPrivateShareAsyncUseCase.execute(any()) } + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { createPublicShareAsyncUseCase.execute(any()) } } - private fun assertPublicShareParameters(shares: List?) { - assertCommonShareParameters(shares) + private fun updatePublicShareVerification( + valueToTest: UseCaseResult, + expectedValue: UIResult?, + expectedOnPosition: Int = 1 + ) { + coEvery { editPublicShareAsyncUseCase.execute(any()) } returns valueToTest + + ocShareViewModel.updatePublicShare( + remoteId = 1, + name = "Photos 2 link", + password = "1234", + expirationDateInMillis = -1, + publicUpload = false, + permissions = -1, + accountName = "Carlos" + ) - assertEquals("Photos 1 link", shares?.get(0)?.name) - assertEquals("http://server:port/s/1", shares?.get(0)?.shareLink) + val value = ocShareViewModel.publicShareEditionStatus.getOrAwaitValues(expectedOnPosition) + assertEquals(expectedValue, value[expectedOnPosition - 1]) - assertEquals("Photos 2 link", shares?.get(1)?.name) - assertEquals("http://server:port/s/2", shares?.get(1)?.shareLink) + coVerify(exactly = 0) { editPrivateShareAsyncUseCase.execute(any()) } + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { editPublicShareAsyncUseCase.execute(any()) } } /****************************************************************************************************** @@ -250,56 +370,106 @@ class OCShareViewModelTest { ******************************************************************************************************/ @Test - fun deletePublicShare() { - every { - ocShareRepository.deleteShare( - 3 - ) - } returns MutableLiveData>().apply { - value = DataResult.success() - } + fun deletePublicShareLoading() { + initTest() - // Viewmodel that will ask ocShareRepository for shares - val ocShareViewModel = createOCShareViewModel(ocShareRepository) + deleteShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Loading(), + expectedOnPosition = 1 + ) + } - val resource: DataResult? = ocShareViewModel.deleteShare( - 3 - ).value + @Test + fun deletePublicShareSuccess() { + initTest() - assertEquals(Status.SUCCESS, resource?.status) + deleteShareVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Success(), + expectedOnPosition = 2 + ) } - private fun assertPublicShareParameters(shares: List?) { - assertCommonShareParameters(shares) + @Test + fun deletePublicShareError() { + initTest() + + val error = Throwable() + + deleteShareVerification( + valueToTest = UseCaseResult.Error(error), + expectedValue = UIResult.Error(error), + expectedOnPosition = 2 + ) + } - assertEquals("Photos 1 link", shares?.get(0)?.name) - assertEquals("http://server:port/s/1", shares?.get(0)?.shareLink) + @Test + fun getSharesAsLiveDataLoading() { + initTest() - assertEquals("Photos 2 link", shares?.get(1)?.name) - assertEquals("http://server:port/s/2", shares?.get(1)?.shareLink) + getSharesAsLiveDataVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = UIResult.Loading(sharesLiveData.value), + expectedOnPosition = 1 + ) } - /****************************************************************************************************** - *********************************************** COMMON *********************************************** - ******************************************************************************************************/ + @Test + fun getSharesAsLiveDataError() { + initTest() - private fun createOCShareViewModel(ocShareRepository: OCShareRepository): OCShareViewModel { - val context = InstrumentationRegistry.getInstrumentation().targetContext + val error = Throwable() - return OCShareViewModel( - context, - testAccount, - ocShareRepository + getSharesAsLiveDataVerification( + valueToTest = UseCaseResult.Error(error), + expectedValue = UIResult.Error(error, sharesLiveData.value), + expectedOnPosition = 2 ) } - private fun assertCommonShareParameters(shares: List?) { - assertEquals(2, shares?.size) + @Test + fun getSharesAsLiveDataWithData() { + initTest() - assertEquals(filePath, shares?.get(0)?.path) - assertEquals(false, shares?.get(0)?.isFolder) + getSharesAsLiveDataVerification( + valueToTest = UseCaseResult.Success(Unit), + expectedValue = null, + expectedOnPosition = 2 + ) + } + + private fun getSharesAsLiveDataVerification( + valueToTest: UseCaseResult, + expectedValue: UIResult>?, + expectedOnPosition: Int = 1 + ) { + coEvery { refreshSharesFromServerAsyncUseCase.execute(any()) } returns valueToTest + + ocShareViewModel.refreshSharesFromNetwork() + + val value = ocShareViewModel.shares.getOrAwaitValues(expectedOnPosition) + assertEquals(expectedValue, value[expectedOnPosition - 1]) + + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { refreshSharesFromServerAsyncUseCase.execute(any()) } + } - assertEquals(filePath, shares?.get(1)?.path) - assertEquals(false, shares?.get(1)?.isFolder) + private fun deleteShareVerification( + valueToTest: UseCaseResult, + expectedValue: UIResult?, + expectedOnPosition: Int = 1 + ) { + coEvery { deletePublicShareAsyncUseCase.execute(any()) } returns valueToTest + + ocShareViewModel.deleteShare( + remoteId = DUMMY_SHARE.remoteId + ) + + val value = ocShareViewModel.shareDeletionStatus.getOrAwaitValues(expectedOnPosition) + assertEquals(expectedValue, value[expectedOnPosition - 1]) + + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { + deletePublicShareAsyncUseCase.execute(any()) + } } } From ecb6bff3f7a289ea2c54f3672610baa87786fd70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Tue, 19 Nov 2019 09:43:20 +0100 Subject: [PATCH 11/41] Add new tests to OCCapabilityDaoTest --- owncloudData/build.gradle | 4 +- .../capabilities/db/OCCapabilityDaoTest.kt | 192 ++++++++---------- .../data/capabilities/db/OCCapabilityDao.kt | 25 +-- 3 files changed, 95 insertions(+), 126 deletions(-) diff --git a/owncloudData/build.gradle b/owncloudData/build.gradle index 02d407a7c78..3805353ad20 100644 --- a/owncloudData/build.gradle +++ b/owncloudData/build.gradle @@ -40,14 +40,14 @@ android { } dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) implementation project(':owncloudDomain') testImplementation project(':owncloudTestUtil') + androidTestImplementation project(':owncloudTestUtil') // Owncloud Android Library api project(':owncloud-android-library:owncloudComLibrary') - implementation fileTree(dir: 'libs', include: ['*.jar']) - implementation 'androidx.appcompat:appcompat:1.0.2' // Kotlin diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt index bae7007e512..e57d5e62515 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt @@ -2,6 +2,7 @@ * ownCloud Android client application * * @author David González Verdugo + * @author Abel García de Prada * Copyright (C) 2019 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify @@ -23,13 +24,13 @@ import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.OwncloudDatabase -import com.owncloud.android.data.utils.DataTestUtil +import com.owncloud.android.data.capabilities.datasources.mapper.OCCapabilityMapper import com.owncloud.android.data.utils.LiveDataTestUtil.getValue import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType -import junit.framework.Assert.assertEquals -import org.hamcrest.CoreMatchers.notNullValue -import org.hamcrest.CoreMatchers.nullValue -import org.hamcrest.MatcherAssert.assertThat +import com.owncloud.android.testutil.OC_CAPABILITY +import org.junit.Assert.assertNull +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Rule import org.junit.Test @@ -37,6 +38,7 @@ import org.junit.Test @SmallTest class OCCapabilityDaoTest { private lateinit var ocCapabilityDao: OCCapabilityDao + private val ocCapabilityMapper = OCCapabilityMapper() @Rule @JvmField @@ -51,132 +53,98 @@ class OCCapabilityDaoTest { } @Test - fun insertCapabilitiesAndRead() { - ocCapabilityDao.insert( - listOf( - DataTestUtil.createCapabilityEntity("user1@server", 3, 2, 1, "3.1"), - DataTestUtil.createCapabilityEntity("user2@server", 6, 5, 4, "6.0") - ) + fun insertCapabilitiesListAndRead() { + val entityList: List = listOf( + ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user1@server"))!!, + ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user2@server"))!! ) - val capability = getValue( - ocCapabilityDao.getCapabilitiesForAccountAsLiveData( - "user2@server" - ) - ) - assertThat(capability, notNullValue()) - assertEquals("user2@server", capability.accountName) - assertEquals(6, capability.versionMayor) - assertEquals(5, capability.versionMinor) - assertEquals(4, capability.versionMicro) - assertEquals("6.0", capability.versionString) + ocCapabilityDao.insert(entityList) + + val capability = ocCapabilityDao.getCapabilitiesForAccount("user2@server") + val capabilityAsLiveData = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user2@server")) + + assertNotNull(capability) + assertNotNull(capabilityAsLiveData) + assertEquals(entityList[1], capability) + assertEquals(entityList[1], capabilityAsLiveData) + } + + @Test + fun insertCapabilitiesAndRead() { + val entity1 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user1@server"))!! + val entity2 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user2@server"))!! + + ocCapabilityDao.insert(entity1) + ocCapabilityDao.insert(entity2) + + val capability = ocCapabilityDao.getCapabilitiesForAccount("user2@server") + val capabilityAsLiveData = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user2@server")) + + assertNotNull(capability) + assertNotNull(capabilityAsLiveData) + assertEquals(entity2, capability) + assertEquals(entity2, capabilityAsLiveData) } @Test fun getNonExistingCapabilities() { - ocCapabilityDao.insert( - DataTestUtil.createCapabilityEntity("user@server", 10, 9, 8, "10.1.4") - ) + ocCapabilityDao.insert(ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user@server"))!!) - val capability = getValue( - ocCapabilityDao.getCapabilitiesForAccountAsLiveData( - "user@server2" - ) - ) - assertThat(capability, nullValue()) + val capability = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user@server2")) + + assertNull(capability) } @Test fun replaceCapabilityIfAlreadyExists_exists() { - ocCapabilityDao.insert( - DataTestUtil.createCapabilityEntity( - "admin@server", - 3, - 2, - 1, - "3.7.5", - sharingPublicPasswordEnforced = CapabilityBooleanType.FALSE.value - ) - ) + val entity1 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(filesVersioning = CapabilityBooleanType.FALSE))!! + val entity2 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(filesVersioning = CapabilityBooleanType.TRUE))!! - ocCapabilityDao.replace( - listOf( // Update capability - DataTestUtil.createCapabilityEntity( - "admin@server", - 3, - 2, - 1, - "3.7.5", - sharingPublicPasswordEnforced = CapabilityBooleanType.TRUE.value - ) - ) - ) + ocCapabilityDao.insert(entity1) + ocCapabilityDao.replace(listOf(entity2)) - val capability = getValue( - ocCapabilityDao.getCapabilitiesForAccountAsLiveData( - "admin@server" - ) - ) - assertThat(capability, notNullValue()) - assertEquals("admin@server", capability.accountName) - assertEquals(3, capability.versionMayor) - assertEquals(2, capability.versionMinor) - assertEquals(1, capability.versionMicro) - assertEquals("3.7.5", capability.versionString) - assertEquals(1, capability.filesSharingPublicPasswordEnforced) + val capability = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!)) + + assertNotNull(capability) + assertEquals(entity2, capability) } @Test - fun replacePublicShareIfAlreadyExists_doesNotExist() { - ocCapabilityDao.insert( - DataTestUtil.createCapabilityEntity( - "cto@server", - 10, - 8, - 6, - "10.0.2", - sharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE.value - ) - ) + fun replaceCapabilityIfAlreadyExists_doesNotExist() { + val entity1 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user1@server"))!! + val entity2 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user2@server"))!! - ocCapabilityDao.replace( - listOf( // Update capability - DataTestUtil.createCapabilityEntity( - "seo@server", - 14, - 13, - 12, - "14.3.8", - sharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.TRUE.value - ) - ) - ) + ocCapabilityDao.insert(entity1) - val capability1 = getValue( - ocCapabilityDao.getCapabilitiesForAccountAsLiveData( - "cto@server" - ) - ) - assertThat(capability1, notNullValue()) - assertEquals("cto@server", capability1.accountName) - assertEquals(10, capability1.versionMayor) - assertEquals(8, capability1.versionMinor) - assertEquals(6, capability1.versionMicro) - assertEquals("10.0.2", capability1.versionString) - assertEquals(CapabilityBooleanType.FALSE.value, capability1.filesSharingPublicPasswordEnforcedReadOnly) + ocCapabilityDao.replace(listOf(entity2)) + + val capability1 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user1@server")) + + assertNotNull(capability1) + assertEquals(entity1, capability1) // capability2 didn't exist before, it should not replace the old one but got created - val capability2 = getValue( - ocCapabilityDao.getCapabilitiesForAccountAsLiveData( - "seo@server" - ) - ) - assertThat(capability2, notNullValue()) - assertEquals("seo@server", capability2.accountName) - assertEquals(14, capability2.versionMayor) - assertEquals(13, capability2.versionMinor) - assertEquals(12, capability2.versionMicro) - assertEquals("14.3.8", capability2.versionString) - assertEquals(CapabilityBooleanType.TRUE.value, capability2.filesSharingPublicPasswordEnforcedReadOnly) + val capability2 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user2@server")) + + assertNotNull(capability2) + assertEquals(entity2, capability2) + } + + @Test + fun deleteCapability() { + val entity = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user1@server"))!! + + ocCapabilityDao.insert(entity) + + val capability1 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user1@server")) + + assertNotNull(capability1) + + ocCapabilityDao.delete("user1@server") + + val capability2 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user1@server")) + + assertNull(capability2) } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityDao.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityDao.kt index b37b833906f..23ec8d643a4 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityDao.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityDao.kt @@ -29,19 +29,23 @@ import com.owncloud.android.data.ProviderMeta.ProviderTableMeta @Dao abstract class OCCapabilityDao { - @Query( - "SELECT * from " + ProviderTableMeta.CAPABILITIES_TABLE_NAME + " WHERE " + - ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + " = :accountName" - ) + companion object { + private const val SELECT = + "SELECT * " + + "FROM ${ProviderTableMeta.CAPABILITIES_TABLE_NAME} " + + "WHERE ${ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME} = :accountName" + private const val DELETE = + "DELETE FROM ${ProviderTableMeta.CAPABILITIES_TABLE_NAME} " + + "WHERE ${ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME} = :accountName" + } + + @Query(SELECT) abstract fun getCapabilitiesForAccountAsLiveData( accountName: String ): LiveData - @Query( - "SELECT * from " + ProviderTableMeta.CAPABILITIES_TABLE_NAME + " WHERE " + - ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + " = :accountName" - ) + @Query(SELECT) abstract fun getCapabilitiesForAccount( accountName: String ): OCCapabilityEntity @@ -52,10 +56,7 @@ abstract class OCCapabilityDao { @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insert(ocCapabilities: List): List - @Query( - "DELETE from " + ProviderTableMeta.CAPABILITIES_TABLE_NAME + " WHERE " + - ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + " = :accountName" - ) + @Query(DELETE) abstract fun delete(accountName: String) @Transaction From 42928daf592d8797b03ffe3a6b5474e67ac5489e Mon Sep 17 00:00:00 2001 From: davigonz Date: Tue, 19 Nov 2019 09:48:14 +0100 Subject: [PATCH 12/41] Include some utils for viewmodel tests --- .../viewmodels/OCCapabilityViewModelTest.kt | 3 +- .../shares/viewmodels/OCShareViewModelTest.kt | 3 +- .../android/utils/LiveDataTestUtil.kt | 52 +++++++++++++++++++ .../android/utils/TestTimeOutConstants.kt | 23 ++++++++ 4 files changed, 77 insertions(+), 4 deletions(-) create mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/utils/LiveDataTestUtil.kt create mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/utils/TestTimeOutConstants.kt diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt index 5ea27595e71..2770879705d 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt @@ -27,11 +27,10 @@ import com.owncloud.android.domain.UseCaseResult import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.capabilities.usecases.GetStoredCapabilitiesUseCase import com.owncloud.android.domain.capabilities.usecases.RefreshCapabilitiesFromServerAsyncUseCase +import com.owncloud.android.domain.utils.DomainTestUtil.DUMMY_CAPABILITY import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.utils.AppTestUtil -import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY -import com.owncloud.android.utils.LiveDataTestUtil.getOrAwaitValues import com.owncloud.android.utils.TIMEOUT_TEST_LONG import io.mockk.coEvery import io.mockk.coVerify diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt index ea02c137a97..f93dbc09e3a 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt @@ -33,12 +33,11 @@ import com.owncloud.android.domain.sharing.shares.usecases.EditPublicShareAsyncU import com.owncloud.android.domain.sharing.shares.usecases.GetShareAsLiveDataUseCase import com.owncloud.android.domain.sharing.shares.usecases.GetSharesAsLiveDataUseCase import com.owncloud.android.domain.sharing.shares.usecases.RefreshSharesFromServerAsyncUseCase +import com.owncloud.android.domain.utils.DomainTestUtil.DUMMY_SHARE import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel import com.owncloud.android.utils.AppTestUtil -import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE import com.owncloud.android.utils.TIMEOUT_TEST_LONG -import com.owncloud.android.utils.LiveDataTestUtil.getOrAwaitValues import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/LiveDataTestUtil.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/LiveDataTestUtil.kt new file mode 100644 index 00000000000..d5667143fb1 --- /dev/null +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/LiveDataTestUtil.kt @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.owncloud.android.utils + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +object LiveDataTestUtil { + + /** + * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds. + * Once we got a notification via onChanged, we stop observing. + */ + inline fun LiveData.getOrAwaitValues( + expectedValues: Int = 1 + ): List { + var currentValue: Int = 0 + val data = arrayOfNulls(expectedValues) + val latch = CountDownLatch(expectedValues) + val observer = object : Observer { + override fun onChanged(o: T?) { + data[currentValue] = o + currentValue++ + latch.countDown() + if (currentValue == expectedValues) { + this@getOrAwaitValues.removeObserver(this) + } + } + } + this.observeForever(observer) + latch.await(TIMEOUT_TEST_SHORT, TimeUnit.MILLISECONDS) + + @Suppress("UNCHECKED_CAST") + return data.toList() + } +} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/TestTimeOutConstants.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/TestTimeOutConstants.kt new file mode 100644 index 00000000000..0c585d099a4 --- /dev/null +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/TestTimeOutConstants.kt @@ -0,0 +1,23 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.utils + +const val TIMEOUT_TEST_LONG = 5_000L +const val TIMEOUT_TEST_SHORT = 2_000L \ No newline at end of file From da72dc21d7d84d054c18e12a0e2bfbd359d58194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Thu, 31 Oct 2019 11:11:06 +0100 Subject: [PATCH 13/41] Move business logic from repository to usecase and test it --- .../sharing/shares/repository/OCShareRepository.kt | 6 +----- .../android/domain/sharing/shares/ShareRepository.kt | 2 +- .../usecases/CreatePrivateShareAsyncUseCase.kt | 12 +++++++++++- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/repository/OCShareRepository.kt b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/repository/OCShareRepository.kt index a2c61682e21..825bfc0db16 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/repository/OCShareRepository.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/repository/OCShareRepository.kt @@ -38,15 +38,11 @@ class OCShareRepository( override fun insertPrivateShare( filePath: String, - shareType: ShareType?, + shareType: ShareType, shareeName: String, // User or group name of the target sharee. permissions: Int, // See https://doc.owncloud.com/server/developer_manual/core/apis/ocs-share-api.html accountName: String ) { - if (!(shareType == ShareType.USER || shareType == ShareType.GROUP || shareType == ShareType.FEDERATED)) { - throw IllegalArgumentException("Illegal share type $shareType"); - } - insertShare( filePath = filePath, shareType = shareType, diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/ShareRepository.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/ShareRepository.kt index 7a633d854ae..523320d2e57 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/ShareRepository.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/ShareRepository.kt @@ -31,7 +31,7 @@ interface ShareRepository { fun insertPrivateShare( filePath: String, - shareType: ShareType?, + shareType: ShareType, shareeName: String, permissions: Int, accountName: String diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/CreatePrivateShareAsyncUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/CreatePrivateShareAsyncUseCase.kt index ae09316ba07..2421c10b7d7 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/CreatePrivateShareAsyncUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/sharing/shares/usecases/CreatePrivateShareAsyncUseCase.kt @@ -27,7 +27,16 @@ class CreatePrivateShareAsyncUseCase( private val shareRepository: ShareRepository ) : BaseUseCaseWithResult() { - override fun run(params: Params) = + override fun run(params: Params) { + require( + params.shareType != null && + (params.shareType == ShareType.USER || + params.shareType == ShareType.GROUP || + params.shareType == ShareType.FEDERATED) + ) { + "Illegal share type ${params.shareType}" + } + shareRepository.insertPrivateShare( params.filePath, params.shareType, @@ -35,6 +44,7 @@ class CreatePrivateShareAsyncUseCase( params.permissions, params.accountName ) + } data class Params( val filePath: String, From 48794ee116b41d5f10f5411bd43d033fdd3b192d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Tue, 19 Nov 2019 09:59:23 +0100 Subject: [PATCH 14/41] Fix OCCapabilityTest --- .../android/domain/capabilities/model/OCCapabilityTest.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt index 1d9b8789ada..32915f484dc 100644 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt @@ -75,6 +75,7 @@ class OCCapabilityTest { assertEquals("1.0.0", item.versionEdition) assertEquals(0, item.corePollInterval) assertEquals(TRUE, item.filesSharingApiEnabled) + assertEquals(3, item.filesSharingSearchMinLength) assertEquals(TRUE, item.filesSharingPublicEnabled) assertEquals(FALSE, item.filesSharingPublicPasswordEnforced) assertEquals(FALSE, item.filesSharingPublicPasswordEnforcedReadOnly) @@ -108,6 +109,7 @@ class OCCapabilityTest { versionEdition = "1.0.0", corePollInterval = 0, filesSharingApiEnabled = TRUE, + filesSharingSearchMinLength = 3, filesSharingPublicEnabled = TRUE, filesSharingPublicPasswordEnforced = FALSE, filesSharingPublicPasswordEnforcedReadOnly = FALSE, @@ -177,6 +179,7 @@ class OCCapabilityTest { versionEdition = "1.0.0", corePollInterval = 0, filesSharingApiEnabled = TRUE, + filesSharingSearchMinLength = 3, filesSharingPublicEnabled = TRUE, filesSharingPublicPasswordEnforced = FALSE, filesSharingPublicPasswordEnforcedReadOnly = FALSE, From df811a240dfede9bf893fa7f07fa86cfd833bd57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Tue, 19 Nov 2019 11:48:25 +0100 Subject: [PATCH 15/41] Fix and add tests to GetStoredCapabilities --- .../capabilities/db/OCCapabilityDaoTest.kt | 38 +++--- .../OCLocalCapabilitiesDataSourceTest.kt | 109 ++++++++---------- .../usecases/GetStoredCapabilitiesUseCase.kt | 7 +- .../GetStoredCapabilitiesUseCaseTest.kt | 57 +++++++++ .../owncloud/android/testutil/OCCapability.kt | 1 + 5 files changed, 129 insertions(+), 83 deletions(-) create mode 100644 owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetStoredCapabilitiesUseCaseTest.kt diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt index e57d5e62515..b9b5a1b4f6a 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt @@ -39,6 +39,8 @@ import org.junit.Test class OCCapabilityDaoTest { private lateinit var ocCapabilityDao: OCCapabilityDao private val ocCapabilityMapper = OCCapabilityMapper() + private val user1 = "user1@server" + private val user2 = "user2@server" @Rule @JvmField @@ -55,14 +57,14 @@ class OCCapabilityDaoTest { @Test fun insertCapabilitiesListAndRead() { val entityList: List = listOf( - ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user1@server"))!!, - ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user2@server"))!! + ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = user1))!!, + ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = user2))!! ) ocCapabilityDao.insert(entityList) - val capability = ocCapabilityDao.getCapabilitiesForAccount("user2@server") - val capabilityAsLiveData = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user2@server")) + val capability = ocCapabilityDao.getCapabilitiesForAccount(user2) + val capabilityAsLiveData = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2)) assertNotNull(capability) assertNotNull(capabilityAsLiveData) @@ -72,14 +74,14 @@ class OCCapabilityDaoTest { @Test fun insertCapabilitiesAndRead() { - val entity1 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user1@server"))!! - val entity2 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user2@server"))!! + val entity1 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = user1))!! + val entity2 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = user2))!! ocCapabilityDao.insert(entity1) ocCapabilityDao.insert(entity2) - val capability = ocCapabilityDao.getCapabilitiesForAccount("user2@server") - val capabilityAsLiveData = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user2@server")) + val capability = ocCapabilityDao.getCapabilitiesForAccount(user2) + val capabilityAsLiveData = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2)) assertNotNull(capability) assertNotNull(capabilityAsLiveData) @@ -89,9 +91,9 @@ class OCCapabilityDaoTest { @Test fun getNonExistingCapabilities() { - ocCapabilityDao.insert(ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user@server"))!!) + ocCapabilityDao.insert(ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = user1))!!) - val capability = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user@server2")) + val capability = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2)) assertNull(capability) } @@ -112,20 +114,20 @@ class OCCapabilityDaoTest { @Test fun replaceCapabilityIfAlreadyExists_doesNotExist() { - val entity1 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user1@server"))!! - val entity2 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user2@server"))!! + val entity1 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = user1))!! + val entity2 = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = user2))!! ocCapabilityDao.insert(entity1) ocCapabilityDao.replace(listOf(entity2)) - val capability1 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user1@server")) + val capability1 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1)) assertNotNull(capability1) assertEquals(entity1, capability1) // capability2 didn't exist before, it should not replace the old one but got created - val capability2 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user2@server")) + val capability2 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2)) assertNotNull(capability2) assertEquals(entity2, capability2) @@ -133,17 +135,17 @@ class OCCapabilityDaoTest { @Test fun deleteCapability() { - val entity = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = "user1@server"))!! + val entity = ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = user1))!! ocCapabilityDao.insert(entity) - val capability1 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user1@server")) + val capability1 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1)) assertNotNull(capability1) - ocCapabilityDao.delete("user1@server") + ocCapabilityDao.delete(user1) - val capability2 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData("user1@server")) + val capability2 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1)) assertNull(capability2) } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt index 496241948e6..5c517263627 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt @@ -2,6 +2,7 @@ * ownCloud Android client application * * @author David González Verdugo + * @author Abel García de Prada * Copyright (C) 2019 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify @@ -21,17 +22,17 @@ package com.owncloud.android.data.capabilities.datasources import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData -import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.capabilities.datasources.implementation.OCLocalCapabilitiesDataSource import com.owncloud.android.data.capabilities.datasources.mapper.OCCapabilityMapper import com.owncloud.android.data.capabilities.db.OCCapabilityDao import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.utils.DataTestUtil import com.owncloud.android.data.utils.LiveDataTestUtil.getValue +import com.owncloud.android.testutil.OC_CAPABILITY import io.mockk.every import io.mockk.mockk -import io.mockk.mockkClass +import io.mockk.verify import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Before import org.junit.Rule import org.junit.Test @@ -40,6 +41,7 @@ import org.junit.rules.TestRule class OCLocalCapabilitiesDataSourceTest { private lateinit var ocLocalCapabilitiesDataSource: OCLocalCapabilitiesDataSource private val ocCapabilityDao = mockk(relaxed = true) + private val ocCapabilityMapper = OCCapabilityMapper() @Rule @JvmField @@ -47,75 +49,62 @@ class OCLocalCapabilitiesDataSourceTest { @Before fun init() { - val db = mockkClass(OwncloudDatabase::class) + ocLocalCapabilitiesDataSource = + OCLocalCapabilitiesDataSource( + ocCapabilityDao, + ocCapabilityMapper + ) + } - every { - db.capabilityDao() - } returns ocCapabilityDao + @Test + fun getCapabilitiesForAccountAsLiveData() { + val capabilitiesLiveData = MutableLiveData() + every { ocCapabilityDao.getCapabilitiesForAccountAsLiveData(any()) } returns capabilitiesLiveData - val capabilityAsLiveData: MutableLiveData = MutableLiveData() - capabilityAsLiveData.value = DataTestUtil.createCapabilityEntity( - "user@server1", 5, 4, 3 - ) + capabilitiesLiveData.postValue(ocCapabilityMapper.toEntity(OC_CAPABILITY)) - every { - ocCapabilityDao.getCapabilitiesForAccountAsLiveData( - "user@server1" - ) - } returns capabilityAsLiveData + val capabilityEmitted = + getValue(ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!)) - val newCapabilityAsLiveData: MutableLiveData = MutableLiveData() - newCapabilityAsLiveData.value = DataTestUtil.createCapabilityEntity( - "user@server2", 2, 1, 0 - ) + assertEquals(OC_CAPABILITY, capabilityEmitted) + } - every { - ocCapabilityDao.getCapabilitiesForAccountAsLiveData( - "user@server2" - ) - } returns newCapabilityAsLiveData + @Test + fun getCapabilitiesForAccountAsLiveDataNull() { + val capabilitiesLiveData = MutableLiveData() + every { ocCapabilityDao.getCapabilitiesForAccountAsLiveData(any()) } returns capabilitiesLiveData - ocLocalCapabilitiesDataSource = - OCLocalCapabilitiesDataSource( - ocCapabilityDao, - OCCapabilityMapper() - ) + val capabilityEmitted = + getValue(ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!)) + + assertNull(capabilityEmitted) } @Test - fun readLocalCapability() { - val capability = getValue( - ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData( - "user@server1" - ) - ) - assertEquals("user@server1", capability?.accountName) - assertEquals(5, capability?.versionMayor) - assertEquals(4, capability?.versionMinor) - assertEquals(3, capability?.versionMicro) + fun getCapabilitiesForAccount() { + every { ocCapabilityDao.getCapabilitiesForAccount(any()) } returns ocCapabilityMapper.toEntity(OC_CAPABILITY)!! + + val capabilityEmitted = ocLocalCapabilitiesDataSource.getCapabilityForAccount(OC_CAPABILITY.accountName!!) + + assertEquals(OC_CAPABILITY, capabilityEmitted) } @Test - fun insertCapabilityAndRead() { - ocLocalCapabilitiesDataSource.insert( - listOf( - DataTestUtil.createCapability( - "user@server1", 7, 6, 5 - ), - DataTestUtil.createCapability( - "user@server2", 2, 1, 0 - ) - ) - ) + fun getCapabilitiesForAccountNull() { + every { ocCapabilityDao.getCapabilitiesForAccountAsLiveData(any()) } returns MutableLiveData() - val capability = getValue( - ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData( - "user@server2" - ) - ) - assertEquals("user@server2", capability?.accountName) - assertEquals(2, capability?.versionMayor) - assertEquals(1, capability?.versionMinor) - assertEquals(0, capability?.versionMicro) + val capabilityEmitted = + getValue(ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!)) + + assertNull(capabilityEmitted) + } + + @Test + fun insertCapabilities() { + every { ocCapabilityDao.replace(any()) } returns Unit + + ocLocalCapabilitiesDataSource.insert(listOf(OC_CAPABILITY)) + + verify(exactly = 1) { ocCapabilityDao.replace(listOf(ocCapabilityMapper.toEntity(OC_CAPABILITY)!!)) } } } diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/usecases/GetStoredCapabilitiesUseCase.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/usecases/GetStoredCapabilitiesUseCase.kt index 2750d47c8b6..b9e116c4761 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/usecases/GetStoredCapabilitiesUseCase.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/usecases/GetStoredCapabilitiesUseCase.kt @@ -26,11 +26,8 @@ import com.owncloud.android.domain.sharing.shares.usecases.BaseUseCase class GetStoredCapabilitiesUseCase( private val capabilityRepository: CapabilityRepository ) : BaseUseCase() { - override fun run(params: Params): OCCapability? { - return capabilityRepository.getStoredCapabilities( - params.accountName - ) - } + override fun run(params: Params): OCCapability? = + capabilityRepository.getStoredCapabilities(params.accountName) data class Params( val accountName: String diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetStoredCapabilitiesUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetStoredCapabilitiesUseCaseTest.kt new file mode 100644 index 00000000000..846cf87e168 --- /dev/null +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetStoredCapabilitiesUseCaseTest.kt @@ -0,0 +1,57 @@ +/** + * ownCloud Android client application + * + * @author Abel García de Prada + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ + +package com.owncloud.android.domain.capabilities.usecases + +import com.owncloud.android.domain.capabilities.CapabilityRepository +import com.owncloud.android.testutil.OC_CAPABILITY +import io.mockk.every +import io.mockk.spyk +import io.mockk.verify +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class GetStoredCapabilitiesUseCaseTest { + private val capabilityRepository: CapabilityRepository = spyk() + private val useCase = GetStoredCapabilitiesUseCase((capabilityRepository)) + private val useCaseParams = GetStoredCapabilitiesUseCase.Params("user@server") + + @Test + fun getStoredCapabilities() { + every { capabilityRepository.getStoredCapabilities(any()) } returns OC_CAPABILITY + + val capability = useCase.execute(useCaseParams) + + assertEquals(OC_CAPABILITY, capability) + + verify(exactly = 1) { capabilityRepository.getStoredCapabilities(any()) } + } + + @Test + fun getStoredCapabilitiesNull() { + every { capabilityRepository.getStoredCapabilities(any()) } returns null + + val capability = useCase.execute(useCaseParams) + + assertNull(capability) + + verify(exactly = 1) { capabilityRepository.getStoredCapabilities(any()) } + } +} diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt index 392bfc4fad4..47a70dabff1 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt @@ -5,6 +5,7 @@ import com.owncloud.android.domain.capabilities.model.OCCapability val OC_CAPABILITY = OCCapability( + id = 0, accountName = "user@server", versionMayor = 2, versionMinor = 1, From 569c81bbd8ea1b7b5d2240d372fb59e7abdc30c1 Mon Sep 17 00:00:00 2001 From: davigonz Date: Tue, 19 Nov 2019 13:39:53 +0100 Subject: [PATCH 16/41] Fix SearchShareesFragmentTest tests and use variables in build.gradle files --- build.gradle | 21 ++- owncloudApp/build.gradle | 39 +++--- .../sharees/ui/SearchShareesFragmentTest.kt | 131 ++++++++---------- .../shares/ui/TestShareFileActivity.kt | 99 +++---------- .../com/owncloud/android/utils/AppTestUtil.kt | 24 ++++ .../presentation/ui/sharing/ShareActivity.kt | 1 - .../fragments/SearchShareesFragment.kt | 4 +- owncloudData/build.gradle | 8 +- owncloudDomain/build.gradle | 8 +- 9 files changed, 139 insertions(+), 196 deletions(-) diff --git a/build.gradle b/build.gradle index 3f650095fc6..fabbba73020 100644 --- a/build.gradle +++ b/build.gradle @@ -1,25 +1,34 @@ buildscript { ext { + + // Android jetpack - archLifecycleVersion = '2.1.0' - roomVersion = '2.1.0' + archLifecycleVersion = "2.1.0" + roomVersion = "2.2.1" + appCompat = "1.1.0" // Kotlin - kotlinVersion = '1.3.50' + kotlinVersion = "1.3.50" // Koin - koinVersion = '2.0.1' - mockkVersion = '1.9.3' + koinVersion = "2.0.1" + mockkVersion = "1.9.3" // Testing junitVersion = "4.12" + extJunitVersion = "1.1.1" + androidTestVersion = "1.2.0" mockitoVersion = "2.24.0" + espressoTestVersion = "3.2.0" + fragmentTestVersion = "1.1.0" + uiAutomatorTestVersion = "2.2.0" + annotationTestVersion = "1.1.0" // Extensions ktxVersion = "1.1.0" // KTX extensions - ktxCoreVersion = "1.0.2" + ktxCoreVersion = "1.1.0" ktxViewModelVersion = "2.2.0-alpha01" ktxFragmentVersion = "1.0.0" } diff --git a/owncloudApp/build.gradle b/owncloudApp/build.gradle index 2f2e45b30c2..057ead71aca 100644 --- a/owncloudApp/build.gradle +++ b/owncloudApp/build.gradle @@ -20,33 +20,32 @@ dependencies { implementation 'com.jakewharton:disklrucache:2.0.2' implementation 'com.google.android.exoplayer:exoplayer:r2.2.0' implementation 'com.andrognito.patternlockview:patternlockview:1.0.0' - implementation 'androidx.appcompat:appcompat:1.1.0' + implementation "androidx.appcompat:appcompat:$appCompat" implementation 'com.getbase:floatingactionbutton:1.10.1' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation "androidx.browser:browser:$androidX" implementation 'commons-io:commons-io:2.6' - // Dependencies for unit tests + // Tests testImplementation "junit:junit:$junitVersion" testImplementation "androidx.arch.core:core-testing:$archLifecycleVersion" testImplementation "io.mockk:mockk:$mockkVersion" - // Dependencies for instrumented tests - androidTestImplementation 'androidx.test.ext:junit:1.1.1' - // JUnit4 Rules - androidTestImplementation 'androidx.test:rules:1.2.0' - androidTestImplementation 'androidx.test.ext:junit:1.1.1' - // Android JUnit Runner - androidTestImplementation 'androidx.test:runner:1.2.0' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' - androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0' - androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0' - androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0' - androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' - androidTestImplementation 'androidx.annotation:annotation:1.1.0' + // Instrumented tests + androidTestImplementation "androidx.test:core:$androidTestVersion" + androidTestImplementation "androidx.test:rules:$androidTestVersion" + androidTestImplementation "androidx.test:runner:$androidTestVersion" + androidTestImplementation "androidx.test:runner:$androidTestVersion" + androidTestImplementation "androidx.test.ext:junit:$extJunitVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$espressoTestVersion" + androidTestImplementation "androidx.test.espresso:espresso-contrib:$espressoTestVersion" + androidTestImplementation "androidx.test.espresso:espresso-intents:$espressoTestVersion" + androidTestImplementation "androidx.test.espresso:espresso-web:$espressoTestVersion" + androidTestImplementation "androidx.test.uiautomator:uiautomator:$uiAutomatorTestVersion" + androidTestImplementation "androidx.annotation:annotation:$annotationTestVersion" androidTestImplementation "androidx.room:room-testing:$roomVersion" androidTestImplementation "androidx.arch.core:core-testing:$archLifecycleVersion" - androidTestImplementation ("io.mockk:mockk-android:$mockkVersion") { + androidTestImplementation("io.mockk:mockk-android:$mockkVersion") { exclude module: 'objenesis' } @@ -65,7 +64,7 @@ dependencies { implementation "androidx.lifecycle:lifecycle-extensions:$archLifecycleVersion" implementation "androidx.lifecycle:lifecycle-viewmodel:$archLifecycleVersion" - kapt "androidx.lifecycle:lifecycle-compiler:$archLifecycleVersion" + kapt "androidx.lifecycle:lifecycle-common-java8:$archLifecycleVersion" implementation "androidx.room:room-runtime:$roomVersion" kapt "androidx.room:room-compiler:$roomVersion" @@ -77,12 +76,6 @@ dependencies { implementation "androidx.core:core-ktx:$ktxCoreVersion" implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$ktxViewModelVersion" implementation "androidx.fragment:fragment-ktx:$ktxFragmentVersion" - - // Kotlin library to mock - testImplementation "io.mockk:mockk:$mockkVersion" - androidTestImplementation ("io.mockk:mockk-android:$mockkVersion") { - exclude module: 'objenesis' - } } tasks.withType(Test) { diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt index c62ba83cff4..68f72a7f147 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt @@ -19,7 +19,10 @@ package com.owncloud.android.sharing.sharees.ui -import android.accounts.Account +import android.content.Context +import androidx.lifecycle.MutableLiveData +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers @@ -28,70 +31,71 @@ import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.rule.ActivityTestRule import com.owncloud.android.R -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.lib.resources.status.OwnCloudVersion +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.SearchShareesFragment +import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel import com.owncloud.android.sharing.shares.ui.TestShareFileActivity -import com.owncloud.android.utils.AppTestUtil +import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE import io.mockk.every -import io.mockk.mockkClass +import io.mockk.mockk import org.hamcrest.CoreMatchers -import org.junit.Rule +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.koin.android.ext.koin.androidContext +import org.koin.androidx.viewmodel.dsl.viewModel +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.dsl.module @RunWith(AndroidJUnit4::class) class SearchShareesFragmentTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - TestShareFileActivity::class.java, - true, - true - ) + private val ocShareViewModel = mockk(relaxed = true) + private val sharesLiveData = MutableLiveData>>() - private var userSharesList = arrayListOf( - AppTestUtil.createPrivateShare( - shareType = ShareType.USER.value, - path = "/Docs", - isFolder = true, - shareWith = "sheldon", - sharedWithDisplayName = "Sheldon" - ), - AppTestUtil.createPrivateShare( - shareType = ShareType.USER.value, - path = "/Docs", - isFolder = true, - shareWith = "penny", - sharedWithDisplayName = "Penny" - ) - ) + @Before + fun init() { + every { ocShareViewModel.shares } returns sharesLiveData - private var groupSharesList = arrayListOf( - AppTestUtil.createPrivateShare( - shareType = ShareType.GROUP.value, - path = "/Photos", - isFolder = false, - shareWith = "friends", - sharedWithDisplayName = "Friends" - ) - ) + stopKoin() + + startKoin { + androidContext(ApplicationProvider.getApplicationContext()) + modules( + module(override = true) { + viewModel { + ocShareViewModel + } + } + ) + } + + ActivityScenario.launch(TestShareFileActivity::class.java).onActivity { + val searchShareesFragment = SearchShareesFragment() + it.startFragment(searchShareesFragment) + } + } @Test fun showSearchBar() { - loadSearchShareesFragment() onView(withId(R.id.search_mag_icon)).check(matches(isDisplayed())) onView(withId(R.id.search_plate)).check(matches(isDisplayed())) } @Test fun showUserShares() { - loadSearchShareesFragment(privateShares = userSharesList) + sharesLiveData.postValue( + UIResult.Success( + listOf( + DUMMY_SHARE.copy(sharedWithDisplayName = "Sheldon"), + DUMMY_SHARE.copy(sharedWithDisplayName = "Penny") + ) + ) + ) + onView(withText("Sheldon")).check(matches(isDisplayed())) onView(withText("Sheldon")).check(matches(hasSibling(withId(R.id.unshareButton)))) .check(matches(isDisplayed())) @@ -102,37 +106,20 @@ class SearchShareesFragmentTest { @Test fun showGroupShares() { - loadSearchShareesFragment(privateShares = groupSharesList) + sharesLiveData.postValue( + UIResult.Success( + listOf( + DUMMY_SHARE.copy( + shareType = ShareType.GROUP, + sharedWithDisplayName = "Friends" + ) + ) + ) + ) + onView(withText("Friends (group)")).check(matches(isDisplayed())) onView(withText("Friends (group)")).check(matches(hasSibling(withId(R.id.icon)))) .check(matches(isDisplayed())) onView(ViewMatchers.withTagValue(CoreMatchers.equalTo(R.drawable.ic_group))).check(matches(isDisplayed())) } - - private fun loadSearchShareesFragment( - capabilities: OCCapabilityEntity = AppTestUtil.createCapability(), - privateShares: ArrayList = arrayListOf() - ) { - val account = mockkClass(Account::class) - val ownCloudVersion = mockkClass(OwnCloudVersion::class) - every { ownCloudVersion.isSearchUsersSupported } returns true - - val searchShareesFragment = - SearchShareesFragment.newInstance( - getOCFileForTesting("image.jpg"), - account - ) - - activityRule.activity.capabilities = capabilities - activityRule.activity.privateShares = privateShares - activityRule.activity.setFragment(searchShareesFragment) - } - - private fun getOCFileForTesting(name: String = "default") = OCFile("/Docs").apply { - availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - fileName = name - fileId = 9456985479 - remoteId = "1" - privateLink = "private link" - } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/TestShareFileActivity.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/TestShareFileActivity.kt index 0493320cdc5..66eb07a33cf 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/TestShareFileActivity.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/TestShareFileActivity.kt @@ -20,49 +20,32 @@ package com.owncloud.android.sharing.shares.ui -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity +import androidx.fragment.app.Fragment +import androidx.fragment.app.transaction +import com.owncloud.android.R import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.presentation.ui.sharing.fragments.SearchShareesFragment -import com.owncloud.android.presentation.ui.sharing.fragments.PublicShareDialogFragment -import com.owncloud.android.presentation.ui.sharing.fragments.ShareFileFragment +import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.presentation.ui.sharing.fragments.ShareFragmentListener import com.owncloud.android.testing.SingleFragmentActivity -class TestShareFileActivity : SingleFragmentActivity(), - ShareFragmentListener { - lateinit var capabilities: OCCapabilityEntity - lateinit var privateShares: ArrayList - lateinit var publicShares: ArrayList - lateinit var errorMessage: String - - override fun startObserving() { - val shareFileFragment: ShareFileFragment = - supportFragmentManager.findFragmentByTag("TEST FRAGMENT") as ShareFileFragment - shareFileFragment.updateCapabilities(capabilities) - shareFileFragment.updatePrivateShares(privateShares) - shareFileFragment.updatePublicShares(publicShares) +class TestShareFileActivity : SingleFragmentActivity(), ShareFragmentListener { + fun startFragment(fragment: Fragment) { + supportFragmentManager.transaction(allowStateLoss = true) { + add(R.id.container, fragment, "TEST FRAGMENT") + } } - override fun refreshPrivateShares() { - val searchShareesFragment: SearchShareesFragment = - supportFragmentManager.findFragmentByTag("TEST FRAGMENT") as SearchShareesFragment - searchShareesFragment.updatePrivateShares(privateShares) + override fun copyOrSendPrivateLink(file: OCFile) { } - override fun refreshPrivateShare(remoteId: Long) { - val editPrivateShareFragment: EditPrivateShareFragment = - supportFragmentManager.findFragmentByTag("TEST FRAGMENT") as EditPrivateShareFragment - editPrivateShareFragment.updateShare(privateShares[0]) + override fun deleteShare(remoteId: Long) { } - override fun updatePrivateShare(remoteId: Long, permissions: Int) { - return + override fun showLoading() { } - /****************************************************************************************************** - ******************************************* PUBLIC SHARES ******************************************** - ******************************************************************************************************/ + override fun dismissLoading() { + } override fun showAddPublicShare(defaultLinkName: String) { } @@ -70,65 +53,15 @@ class TestShareFileActivity : SingleFragmentActivity(), override fun showEditPublicShare(share: OCShare) { } - override fun showRemovePublicShare(share: OCShare) { + override fun showRemoveShare(share: OCShare) { } override fun copyOrSendPublicLink(share: OCShare) { } - override fun createPublicShare( - permissions: Int, - name: String, - password: String, - expirationTimeInMillis: Long, - publicUpload: Boolean - ) { - val publicShareDialogFragment: PublicShareDialogFragment = - supportFragmentManager.findFragmentByTag("TEST FRAGMENT") as PublicShareDialogFragment - publicShareDialogFragment.showError(errorMessage) - } - - override fun updatePublicShare( - remoteId: Long, - name: String, - password: String?, - expirationDateInMillis: Long, - permissions: Int, - publicUpload: Boolean - ) { - } - - override fun removePublicShare(share: OCShareEntity) { - } - - override fun observeCapabilities(shouldFetchFromNetwork: Boolean) { - val publicShareDialogFragment: PublicShareDialogFragment = - supportFragmentManager.findFragmentByTag("TEST FRAGMENT") as PublicShareDialogFragment - publicShareDialogFragment.updateCapabilities(capabilities) - } - - override fun copyOrSendPrivateLink(file: OCFile) { - } - override fun showSearchUsersAndGroups() { } - override fun showEditPrivateShare(share: OCShareEntity) { - } - - override fun refreshAllShares() { - val shareFileFragment: ShareFileFragment = - supportFragmentManager.findFragmentByTag("TEST FRAGMENT") as ShareFileFragment - shareFileFragment.updateCapabilities(capabilities) - shareFileFragment.updatePrivateShares(privateShares) - shareFileFragment.updatePublicShares(publicShares) - } - - override fun removeShare(shareRemoteId: Long) { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } - - - override fun copyOrSendPrivateLink(file: OCFile) { + override fun showEditPrivateShare(share: OCShare) { } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt index 907c7432b48..ffd0c799357 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt @@ -22,6 +22,8 @@ package com.owncloud.android.utils import android.accounts.Account import com.owncloud.android.data.capabilities.db.OCCapabilityEntity import com.owncloud.android.data.sharing.shares.db.OCShareEntity +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation import org.json.JSONObject @@ -29,6 +31,26 @@ object AppTestUtil { /** * Shares */ + val DUMMY_SHARE = OCShare( + fileSource = 7, + itemSource = 7, + shareType = ShareType.USER, // Private share by default + shareWith = "", + path = "/Photos/image.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "AnyToken", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = "", + shareLink = "" + ) + private fun createShare( fileSource: Long = 7, itemSource: Long = 7, @@ -141,6 +163,7 @@ object AppTestUtil { versionEdition: String = "1.0.0", corePollinterval: Int = 0, sharingApiEnabled: Int = 0, + sharingSearchMinLength: Int = 3, sharingPublicEnabled: Int = 1, sharingPublicPasswordEnforced: Int = 0, sharingPublicPasswordEnforcedReadOnly: Int = 0, @@ -169,6 +192,7 @@ object AppTestUtil { versionEdition, corePollinterval, sharingApiEnabled, + sharingSearchMinLength, sharingPublicEnabled, sharingPublicPasswordEnforced, sharingPublicPasswordEnforcedReadOnly, diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/ShareActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/ShareActivity.kt index 77c6696a72b..823266795a7 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/ShareActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/ShareActivity.kt @@ -27,7 +27,6 @@ package com.owncloud.android.presentation.ui.sharing import android.app.SearchManager import android.content.Intent import android.os.Bundle -import android.util.Log import android.view.MenuItem import androidx.fragment.app.transaction import androidx.lifecycle.Observer diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/SearchShareesFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/SearchShareesFragment.kt index 6c91c5f3ac1..b4be0af6843 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/SearchShareesFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/SearchShareesFragment.kt @@ -175,10 +175,9 @@ class SearchShareesFragment : Fragment(), // Show data val usersList = view!!.findViewById(R.id.searchUsersListView) - if (privateShares.size > 0) { + if (privateShares.isNotEmpty()) { usersList.visibility = View.VISIBLE usersList.adapter = userGroupsAdapter - } else { usersList.visibility = View.GONE } @@ -191,7 +190,6 @@ class SearchShareesFragment : Fragment(), } catch (e: ClassCastException) { throw ClassCastException(requireActivity().toString() + " must implement OnFragmentInteractionListener") } - } override fun onStart() { diff --git a/owncloudData/build.gradle b/owncloudData/build.gradle index 3805353ad20..8ee9e3c23c9 100644 --- a/owncloudData/build.gradle +++ b/owncloudData/build.gradle @@ -48,7 +48,7 @@ dependencies { // Owncloud Android Library api project(':owncloud-android-library:owncloudComLibrary') - implementation 'androidx.appcompat:appcompat:1.0.2' + implementation "androidx.appcompat:appcompat:$appCompat" // Kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" @@ -63,9 +63,9 @@ dependencies { testImplementation "io.mockk:mockk:$mockkVersion" // Dependencies for instrumented tests - androidTestImplementation 'androidx.test:runner:1.2.0' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' - androidTestImplementation 'androidx.test.ext:junit:1.1.1' + androidTestImplementation "androidx.test:runner:$androidTestVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$espressoTestVersion" + androidTestImplementation "androidx.test.ext:junit:$extJunitVersion" androidTestImplementation "androidx.arch.core:core-testing:$archLifecycleVersion" androidTestImplementation ("io.mockk:mockk-android:$mockkVersion") { exclude module: 'objenesis' diff --git a/owncloudDomain/build.gradle b/owncloudDomain/build.gradle index 45a0e19fa00..c2c75d9fefb 100644 --- a/owncloudDomain/build.gradle +++ b/owncloudDomain/build.gradle @@ -43,7 +43,7 @@ dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) testImplementation project(':owncloudTestUtil') - implementation 'androidx.appcompat:appcompat:1.0.2' + implementation "androidx.appcompat:appcompat:$appCompat" // Kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" @@ -55,8 +55,8 @@ dependencies { // Dependencies for instrumented tests androidTestImplementation "androidx.arch.core:core-testing:$archLifecycleVersion" - androidTestImplementation 'androidx.test:runner:1.2.0' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' + androidTestImplementation "androidx.test:runner:$androidTestVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$espressoTestVersion" androidTestImplementation ("io.mockk:mockk-android:$mockkVersion") { exclude module: 'objenesis' } @@ -73,4 +73,4 @@ configurations.all { details.useVersion "2.0.0" } } -} \ No newline at end of file +} From c3a3e63962855dd5cede808f3059c69cf6a88ed5 Mon Sep 17 00:00:00 2001 From: davigonz Date: Tue, 19 Nov 2019 16:25:51 +0100 Subject: [PATCH 17/41] Adapt PublicShareCreationDialogFragmentTest tests --- .../sharees/ui/SearchShareesFragmentTest.kt | 2 - .../PublicShareCreationDialogFragmentTest.kt | 312 ++++++++++++------ .../com/owncloud/android/utils/AppTestUtil.kt | 34 ++ .../dependecyinjection/ViewModelModule.kt | 8 +- 4 files changed, 254 insertions(+), 102 deletions(-) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt index 68f72a7f147..fa2f3004c65 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt @@ -30,7 +30,6 @@ import androidx.test.espresso.matcher.ViewMatchers.hasSibling import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 import com.owncloud.android.R import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType @@ -51,7 +50,6 @@ import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.dsl.module -@RunWith(AndroidJUnit4::class) class SearchShareesFragmentTest { private val ocShareViewModel = mockk(relaxed = true) private val sharesLiveData = MutableLiveData>>() diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt index 3e7ee398c13..c3833e9bea2 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt @@ -19,8 +19,14 @@ package com.owncloud.android.sharing.shares.ui +import android.accounts.Account +import android.accounts.AccountManager +import android.content.Context import android.text.InputType.TYPE_CLASS_TEXT import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD +import androidx.lifecycle.MutableLiveData +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.scrollTo @@ -33,28 +39,116 @@ import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withInputType import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.rule.ActivityTestRule +import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.R -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity +import com.owncloud.android.authentication.AccountAuthenticator import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.resources.status.CapabilityBooleanType +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType +import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.lib.common.accounts.AccountUtils +import com.owncloud.android.lib.resources.status.OwnCloudVersion +import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.PublicShareDialogFragment -import com.owncloud.android.utils.AppTestUtil +import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel +import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel +import com.owncloud.android.utils.AccountsManager +import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY import com.owncloud.android.utils.DateUtils import io.mockk.every +import io.mockk.mockk import io.mockk.mockkClass import org.hamcrest.CoreMatchers.not -import org.junit.Rule +import org.junit.AfterClass +import org.junit.Before +import org.junit.BeforeClass import org.junit.Test +import org.koin.android.ext.koin.androidContext +import org.koin.androidx.viewmodel.dsl.viewModel +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.dsl.module import java.text.SimpleDateFormat import java.util.Date class PublicShareCreationDialogFragmentTest { - @Rule - @JvmField - val activityRule = ActivityTestRule(TestShareFileActivity::class.java, true, true) + private val ocCapabilityViewModel = mockk(relaxed = true) + private val capabilitiesLiveData = MutableLiveData>() + private val ocShareViewModel = mockk(relaxed = true) + private val publicShareCreationStatus = MutableLiveData>() + + companion object { + private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext + private val account = Account("admin", "owncloud") + + @BeforeClass + @JvmStatic + fun init() { + addAccount() + } + + @AfterClass + @JvmStatic + fun cleanUp() { + AccountsManager.deleteAllAccounts(targetContext) + } + + private fun addAccount() { + // obtaining an AccountManager instance + val accountManager = AccountManager.get(targetContext) + + accountManager.addAccountExplicitly(account, "1234", null) + + // include account version, user, server version and token with the new account + accountManager.setUserData( + account, + AccountUtils.Constants.KEY_OC_VERSION, + OwnCloudVersion("10.2").toString() + ) + accountManager.setUserData( + account, + AccountUtils.Constants.KEY_OC_BASE_URL, + "serverUrl:port" + ) + accountManager.setUserData( + account, + AccountUtils.Constants.KEY_DISPLAY_NAME, + "admin" + ) + accountManager.setUserData( + account, + AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, + "1" + ) + + accountManager.setAuthToken( + account, + AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, + "AUTH_TOKEN" + ) + } + } - private val file = mockkClass(OCFile::class) + @Before + fun setUp() { + every { ocCapabilityViewModel.capabilities } returns capabilitiesLiveData + every { ocShareViewModel.publicShareCreationStatus } returns publicShareCreationStatus + + stopKoin() + + startKoin { + androidContext(ApplicationProvider.getApplicationContext()) + modules( + module(override = true) { + viewModel { + ocCapabilityViewModel + } + viewModel { + ocShareViewModel + } + } + ) + } + } @Test fun showDialogTitle() { @@ -80,12 +174,12 @@ class PublicShareCreationDialogFragmentTest { @Test fun showFolderAdditionalFields() { loadPublicShareDialogFragment( - AppTestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.0.1", - sharingPublicUpload = CapabilityBooleanType.TRUE.value, - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value - ), - isFolder = true + filesSharingPublicUpload = CapabilityBooleanType.TRUE, + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE + ) ) onView(withId(R.id.shareViaLinkEditPermissionGroup)).check(matches(isDisplayed())) } @@ -120,7 +214,9 @@ class PublicShareCreationDialogFragmentTest { @Test fun checkPasswordEnforced() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability(sharingPublicPasswordEnforced = CapabilityBooleanType.TRUE.value) + capabilities = DUMMY_CAPABILITY.copy( + filesSharingPublicPasswordEnforced = CapabilityBooleanType.TRUE + ) ) onView(withId(R.id.shareViaLinkPasswordLabel)).check( matches(withText(R.string.share_via_link_password_enforced_label)) @@ -134,8 +230,8 @@ class PublicShareCreationDialogFragmentTest { @Test fun checkExpireDateEnforced() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( - sharingPublicExpireDateEnforced = CapabilityBooleanType.TRUE.value + capabilities = DUMMY_CAPABILITY.copy( + filesSharingPublicExpireDateEnforced = CapabilityBooleanType.TRUE ) ) onView(withId(R.id.shareViaLinkExpirationLabel)) @@ -149,8 +245,8 @@ class PublicShareCreationDialogFragmentTest { @Test fun checkExpireDateNotEnforced() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( - sharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE.value + capabilities = DUMMY_CAPABILITY.copy( + filesSharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE ) ) onView(withId(R.id.shareViaLinkExpirationLabel)) @@ -182,41 +278,49 @@ class PublicShareCreationDialogFragmentTest { @Test fun showError() { - loadPublicShareDialogFragment( - errorMessage = "Unable to share. Please check whether the file exists" - ) + loadPublicShareDialogFragment() + onView(withId(R.id.saveButton)).perform(click()) + + publicShareCreationStatus.postValue( + UIResult.Error( + error = Throwable("It was not possible to share this file or folder") + ) + ) + onView(withId(R.id.public_link_error_message)).check(matches(isDisplayed())) - onView(withId(R.id.public_link_error_message)).check(matches(withText(R.string.share_link_file_no_exist))) + onView(withId(R.id.public_link_error_message)).check( + matches( + withText(R.string.share_link_file_error) + ) + ) } @Test fun uploadPermissionsWithFolderDisplayed() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicUpload = CapabilityBooleanType.TRUE ) ) - every { file.isFolder } returns true - onView(withId(R.id.shareViaLinkEditPermissionGroup)).check(matches(isDisplayed())) } @Test fun uploadPermissionsWithFolderNotDisplayed() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.FALSE.value + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicUpload = CapabilityBooleanType.FALSE ) ) - every { file.isFolder } returns true - onView(withId(R.id.shareViaLinkEditPermissionGroup)).check(matches(not(isDisplayed()))) } @@ -224,9 +328,9 @@ class PublicShareCreationDialogFragmentTest { fun expirationDateDays() { val daysToTest = 15 loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicExpireDateDays = daysToTest + filesSharingPublicExpireDateDays = daysToTest ) ) val formattedDate = SimpleDateFormat.getDateInstance().format( @@ -244,9 +348,9 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordNotEnforced() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicPasswordEnforced = CapabilityBooleanType.FALSE.value + filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE ) ) onView(withId(R.id.shareViaLinkPasswordLabel)) @@ -256,9 +360,9 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordEnforced() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicPasswordEnforced = CapabilityBooleanType.TRUE.value + filesSharingPublicPasswordEnforced = CapabilityBooleanType.TRUE ) ) onView(withId(R.id.shareViaLinkPasswordLabel)) @@ -268,15 +372,15 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordEnforcedReadOnlyFolders() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforced = CapabilityBooleanType.TRUE.value + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicUpload = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.TRUE ) ) - every { file.isFolder } returns true onView(withId(R.id.shareViaLinkEditPermissionReadOnly)).check(matches(isDisplayed())) onView(withId(R.id.shareViaLinkEditPermissionReadOnly)).perform(click()) onView(withId(R.id.shareViaLinkPasswordLabel)) @@ -286,15 +390,15 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordNotEnforcedReadOnlyFolders() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE.value, - sharingPublicPasswordEnforced = CapabilityBooleanType.FALSE.value + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicUpload = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE ) ) - every { file.isFolder } returns true onView(withId(R.id.shareViaLinkEditPermissionReadOnly)).check(matches(isDisplayed())) onView(withId(R.id.shareViaLinkEditPermissionReadOnly)).perform(click()) onView(withId(R.id.shareViaLinkPasswordLabel)) @@ -304,15 +408,15 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordEnforcedReadWriteFolders() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforced = CapabilityBooleanType.TRUE.value + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicUpload = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.TRUE ) ) - every { file.isFolder } returns true onView(withId(R.id.shareViaLinkEditPermissionReadAndWrite)).check(matches(isDisplayed())) onView(withId(R.id.shareViaLinkEditPermissionReadAndWrite)).perform(click()) onView(withId(R.id.shareViaLinkPasswordLabel)) @@ -322,15 +426,15 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordNotEnforcedReadWriteFolders() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE.value, - sharingPublicPasswordEnforced = CapabilityBooleanType.FALSE.value + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicUpload = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE ) ) - every { file.isFolder } returns true onView(withId(R.id.shareViaLinkEditPermissionReadAndWrite)).check(matches(isDisplayed())) onView(withId(R.id.shareViaLinkEditPermissionReadAndWrite)).perform(click()) onView(withId(R.id.shareViaLinkPasswordLabel)) @@ -340,15 +444,15 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordEnforcedUploadOnlyFolders() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforced = CapabilityBooleanType.FALSE.value + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicUpload = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE ) ) - every { file.isFolder } returns true onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).check(matches(isDisplayed())) onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).perform(click()) onView(withId(R.id.shareViaLinkPasswordLabel)) @@ -358,15 +462,15 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordNotEnforcedUploadOnlyFolders() { loadPublicShareDialogFragment( - capabilities = AppTestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE.value, - sharingPublicPasswordEnforced = CapabilityBooleanType.FALSE.value + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicUpload = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE ) ) - every { file.isFolder } returns true onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).check(matches(isDisplayed())) onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).perform(click()) onView(withId(R.id.shareViaLinkPasswordLabel)) @@ -375,32 +479,47 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordEnforcedClearErrorMessageIfSwitchsToNotEnforced() { + val commonError = "Common error" + //One permission with password enforced. Error is cleaned after switching permission //to a non-forced one loadPublicShareDialogFragment( - capabilities = TestUtil.createCapability( + isFolder = true, + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value, - sharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE.value, - sharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE.value, - sharingPublicPasswordEnforced = CapabilityBooleanType.TRUE.value + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, + filesSharingPublicUpload = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.TRUE ) ) - `when`(file.isFolder).thenReturn(true) - onView(withId(R.id.saveButton)).perform(scrollTo(),click()) - onView(withText("Common error")).check(matches(isDisplayed())) + onView(withId(R.id.saveButton)).perform(scrollTo(), click()) + + publicShareCreationStatus.postValue( + UIResult.Error( + error = Throwable(commonError) + ) + ) + + onView(withText(commonError)).check(matches(isDisplayed())) onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).perform(click()) - onView(withText("Common error")).check(matches(not(isDisplayed()))) + onView(withText(commonError)).check(matches(not(isDisplayed()))) } private fun loadPublicShareDialogFragment( - capabilities: OCCapabilityEntity = AppTestUtil.createCapability(), - errorMessage: String = "Common error", - isFolder: Boolean = false + isFolder: Boolean = false, + capabilities: OCCapability = DUMMY_CAPABILITY ) { - val defaultLinkName = "DOC_12112018.jpg link" + val file = mockkClass(OCFile::class) + + val publicShareDialogFragment = PublicShareDialogFragment.newInstanceToCreate( + file, + account, + "DOC_12112018.jpg link" + ) + val filePath = "/Documents/doc3" val fileMimeType = ".txt" @@ -408,13 +527,14 @@ class PublicShareCreationDialogFragmentTest { every { file.mimetype } returns fileMimeType every { file.isFolder } returns isFolder - val publicShareDialogFragment = PublicShareDialogFragment.newInstanceToCreate( - file, - defaultLinkName - ) + ActivityScenario.launch(TestShareFileActivity::class.java).onActivity { + it.startFragment(publicShareDialogFragment) + } - activityRule.activity.capabilities = capabilities - activityRule.activity.errorMessage = errorMessage - activityRule.activity.setFragment(publicShareDialogFragment) + capabilitiesLiveData.postValue( + UIResult.Success( + capabilities + ) + ) } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt index ffd0c799357..cb2cdb3f388 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt @@ -22,6 +22,8 @@ package com.owncloud.android.utils import android.accounts.Account import com.owncloud.android.data.capabilities.db.OCCapabilityEntity import com.owncloud.android.data.sharing.shares.db.OCShareEntity +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType +import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation @@ -154,6 +156,38 @@ object AppTestUtil { /** * Capabilities */ + val DUMMY_CAPABILITY = + OCCapability( + accountName = "user@server", + versionMayor = 2, + versionMinor = 1, + versionMicro = 0, + versionString = "1.0.0", + versionEdition = "1.0.0", + corePollInterval = 0, + filesSharingApiEnabled = CapabilityBooleanType.TRUE, + filesSharingSearchMinLength = 3, + filesSharingPublicEnabled = CapabilityBooleanType.TRUE, + filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE, + filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE, + filesSharingPublicExpireDateEnabled = CapabilityBooleanType.FALSE, + filesSharingPublicExpireDateDays = 0, + filesSharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE, + filesSharingPublicSendMail = CapabilityBooleanType.FALSE, + filesSharingPublicUpload = CapabilityBooleanType.FALSE, + filesSharingPublicMultiple = CapabilityBooleanType.FALSE, + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.FALSE, + filesSharingUserSendMail = CapabilityBooleanType.FALSE, + filesSharingResharing = CapabilityBooleanType.FALSE, + filesSharingFederationOutgoing = CapabilityBooleanType.FALSE, + filesSharingFederationIncoming = CapabilityBooleanType.FALSE, + filesBigFileChunking = CapabilityBooleanType.FALSE, + filesUndelete = CapabilityBooleanType.FALSE, + filesVersioning = CapabilityBooleanType.FALSE + ) + fun createCapability( accountName: String = "user@server", versionMayor: Int = 2, diff --git a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt index b50c3a30eeb..9d941891ce5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt @@ -25,11 +25,11 @@ import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModelModule = module { - viewModel { (filePath: String, accountName: String) -> - OCShareViewModel(filePath, accountName, get(), get(), get(), get(), get(), get(), get(), get()) - } - viewModel { (accountName: String) -> OCCapabilityViewModel(accountName, get(), get(), get()) } + + viewModel { (filePath: String, accountName: String) -> + OCShareViewModel(filePath, accountName, get(), get(), get(), get(), get(), get(), get(), get()) + } } From 01fbe7c901794d1e4f02d67e127d335ae1231ba9 Mon Sep 17 00:00:00 2001 From: davigonz Date: Tue, 19 Nov 2019 18:31:28 +0100 Subject: [PATCH 18/41] Keep adapting UI tests to modularization --- .../PublicShareCreationDialogFragmentTest.kt | 77 +------- .../PublicShareEditionDialogFragmentTest.kt | 73 +++++-- .../shares/ui/ShareFileFragmentTest.kt | 185 ++++++++++-------- .../shares/ui/ShareFolderFragmentTest.kt | 95 +++++---- .../android/utils/AccountsManager.java | 128 ------------ .../android/utils/AccountsTestManager.kt | 102 ++++++++++ .../com/owncloud/android/utils/AppTestUtil.kt | 167 ++-------------- 7 files changed, 341 insertions(+), 486 deletions(-) delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsManager.java create mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsTestManager.kt diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt index c3833e9bea2..804ccab7cf4 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt @@ -19,8 +19,6 @@ package com.owncloud.android.sharing.shares.ui -import android.accounts.Account -import android.accounts.AccountManager import android.content.Context import android.text.InputType.TYPE_CLASS_TEXT import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD @@ -39,28 +37,22 @@ import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withInputType import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator -import com.owncloud.android.datamodel.OCFile import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.resources.status.OwnCloudVersion import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.PublicShareDialogFragment import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.utils.AccountsManager +import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY +import com.owncloud.android.utils.AppTestUtil.DUMMY_FILE +import com.owncloud.android.utils.AppTestUtil.DUMMY_FOLDER import com.owncloud.android.utils.DateUtils import io.mockk.every import io.mockk.mockk -import io.mockk.mockkClass import org.hamcrest.CoreMatchers.not -import org.junit.AfterClass import org.junit.Before -import org.junit.BeforeClass import org.junit.Test import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel @@ -76,58 +68,6 @@ class PublicShareCreationDialogFragmentTest { private val ocShareViewModel = mockk(relaxed = true) private val publicShareCreationStatus = MutableLiveData>() - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "1234", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - @Before fun setUp() { every { ocCapabilityViewModel.capabilities } returns capabilitiesLiveData @@ -512,21 +452,14 @@ class PublicShareCreationDialogFragmentTest { isFolder: Boolean = false, capabilities: OCCapability = DUMMY_CAPABILITY ) { - val file = mockkClass(OCFile::class) + val file = if (isFolder) DUMMY_FOLDER else DUMMY_FILE val publicShareDialogFragment = PublicShareDialogFragment.newInstanceToCreate( file, - account, + DUMMY_ACCOUNT, "DOC_12112018.jpg link" ) - val filePath = "/Documents/doc3" - val fileMimeType = ".txt" - - every { file.remotePath } returns filePath - every { file.mimetype } returns fileMimeType - every { file.isFolder } returns isFolder - ActivityScenario.launch(TestShareFileActivity::class.java).onActivity { it.startFragment(publicShareDialogFragment) } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt index 2c2297e1854..fd51e20f5d4 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt @@ -19,6 +19,10 @@ package com.owncloud.android.sharing.shares.ui +import android.content.Context +import androidx.lifecycle.MutableLiveData +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers @@ -28,19 +32,30 @@ import androidx.test.espresso.matcher.ViewMatchers.withHint import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.rule.ActivityTestRule import com.owncloud.android.R -import com.owncloud.android.data.sharing.shares.db.OCShareEntity import com.owncloud.android.datamodel.OCFile +import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.resources.shares.RemoteShare +import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.PublicShareDialogFragment -import com.owncloud.android.utils.AppTestUtil +import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel +import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel +import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT +import com.owncloud.android.utils.AppTestUtil.DUMMY_FILE +import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE import io.mockk.every +import io.mockk.mockk import io.mockk.mockkClass import org.junit.Before -import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith +import org.koin.android.ext.koin.androidContext +import org.koin.androidx.viewmodel.dsl.viewModel +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.dsl.module import java.text.DateFormat import java.text.SimpleDateFormat import java.util.GregorianCalendar @@ -48,33 +63,49 @@ import java.util.TimeZone @RunWith(AndroidJUnit4::class) class PublicShareEditionDialogFragmentTest { - @Rule - @JvmField - val activityRule = ActivityTestRule(TestShareFileActivity::class.java, true, true) + private val ocCapabilityViewModel = mockk(relaxed = true) + private val capabilitiesLiveData = MutableLiveData>() + private val ocShareViewModel = mockk(relaxed = true) private val file = mockkClass(OCFile::class) - private val publicShare = mockkClass(OCShareEntity::class) private val expirationDate = 1556575200000 // GMT: Monday, April 29, 2019 10:00:00 PM @Before fun setUp() { - every { file.mimetype } returns ".txt" - every { file.remotePath } returns "/Documents/doc3" - every { file.isFolder } returns false - - every { publicShare.name } returns "Docs link" - every { publicShare.permissions } returns RemoteShare.CREATE_PERMISSION_FLAG - every { publicShare.isPasswordProtected } returns true - every { publicShare.expirationDate } returns expirationDate - every { publicShare.isFolder } returns false + every { ocCapabilityViewModel.capabilities } returns capabilitiesLiveData val publicShareDialogFragment = PublicShareDialogFragment.newInstanceToUpdate( - file, - publicShare + DUMMY_FILE, + DUMMY_ACCOUNT, + DUMMY_SHARE.copy( + shareType = ShareType.PUBLIC_LINK, + shareWith = "user", + name = "Docs link", + permissions = RemoteShare.CREATE_PERMISSION_FLAG, + expirationDate = expirationDate, + isFolder = true + ) ) - activityRule.activity.capabilities = AppTestUtil.createCapability() - activityRule.activity.setFragment(publicShareDialogFragment) + stopKoin() + + startKoin { + androidContext(ApplicationProvider.getApplicationContext()) + modules( + module(override = true) { + viewModel { + ocCapabilityViewModel + } + viewModel { + ocShareViewModel + } + } + ) + } + + ActivityScenario.launch(TestShareFileActivity::class.java).onActivity { + it.startFragment(publicShareDialogFragment) + } } @Test diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt index c40722336bf..4f3ff225fb4 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt @@ -19,7 +19,10 @@ package com.owncloud.android.sharing.shares.ui -import android.accounts.Account +import android.content.Context +import androidx.lifecycle.MutableLiveData +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers @@ -29,38 +32,64 @@ import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withTagValue import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.rule.ActivityTestRule import com.owncloud.android.R -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.resources.shares.ShareType -import com.owncloud.android.lib.resources.status.CapabilityBooleanType +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType +import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.resources.status.OwnCloudVersion +import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.ShareFileFragment -import com.owncloud.android.utils.AppTestUtil +import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel +import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel +import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT +import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY +import com.owncloud.android.utils.AppTestUtil.DUMMY_FILE +import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE import io.mockk.every +import io.mockk.mockk import io.mockk.mockkClass import org.hamcrest.CoreMatchers -import org.junit.Rule +import org.junit.Before import org.junit.Test -import org.junit.runner.RunWith +import org.koin.android.ext.koin.androidContext +import org.koin.androidx.viewmodel.dsl.viewModel +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.dsl.module -@RunWith(AndroidJUnit4::class) class ShareFileFragmentTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - TestShareFileActivity::class.java, - true, - true - ) + private val ocCapabilityViewModel = mockk(relaxed = true) + private val capabilitiesLiveData = MutableLiveData>() + private val ocShareViewModel = mockk(relaxed = true) + private val sharesLiveData = MutableLiveData>>() + + @Before + fun setUp() { + every { ocCapabilityViewModel.capabilities } returns capabilitiesLiveData + every { ocShareViewModel.shares } returns sharesLiveData + + stopKoin() + + startKoin { + androidContext(ApplicationProvider.getApplicationContext()) + modules( + module(override = true) { + viewModel { + ocCapabilityViewModel + } + viewModel { + ocShareViewModel + } + } + ) + } + } @Test fun showHeader() { loadShareFileFragment() - onView(withId(R.id.shareFileName)).check(matches(withText("image.jpg"))) + onView(withId(R.id.shareFileName)).check(matches(withText("img.png"))) } @Test @@ -79,55 +108,41 @@ class ShareFileFragmentTest { ******************************************* PRIVATE SHARES ******************************************* ******************************************************************************************************/ - private var userSharesList = arrayListOf( - AppTestUtil.createPrivateShare( - shareType = ShareType.USER.value, - path = "/Photos/image.jpg", - isFolder = false, - shareWith = "batman", + private var userSharesList = listOf( + DUMMY_SHARE.copy( sharedWithDisplayName = "Batman" ), - AppTestUtil.createPrivateShare( - shareType = ShareType.USER.value, - path = "/Photos/image.jpg", - isFolder = false, - shareWith = "jocker", + DUMMY_SHARE.copy( sharedWithDisplayName = "Jocker" ) ) - private var groupSharesList = arrayListOf( - AppTestUtil.createPrivateShare( - shareType = ShareType.GROUP.value, - path = "/Photos/image.jpg", - isFolder = false, - shareWith = "suicideSquad", + private var groupSharesList = listOf( + DUMMY_SHARE.copy( + shareType = ShareType.GROUP, sharedWithDisplayName = "Suicide Squad" ), - AppTestUtil.createPrivateShare( - shareType = ShareType.GROUP.value, - path = "/Photos/image.jpg", - isFolder = false, - shareWith = "avengers", + DUMMY_SHARE.copy( + shareType = ShareType.GROUP, sharedWithDisplayName = "Avengers" ) ) @Test fun showUsersAndGroupsSectionTitle() { - loadShareFileFragment(privateShares = userSharesList) + loadShareFileFragment(shares = userSharesList) onView(withText(R.string.share_with_user_section_title)).check(matches(isDisplayed())) } @Test fun showNoPrivateShares() { - loadShareFileFragment() + loadShareFileFragment(shares = listOf()) onView(withText(R.string.share_no_users)).check(matches(isDisplayed())) } @Test fun showUserShares() { - loadShareFileFragment(privateShares = userSharesList) + loadShareFileFragment(shares = userSharesList) onView(withText("Batman")).check(matches(isDisplayed())) onView(withText("Batman")).check(matches(hasSibling(withId(R.id.unshareButton)))) .check(matches(isDisplayed())) @@ -138,7 +153,7 @@ class ShareFileFragmentTest { @Test fun showGroupShares() { - loadShareFileFragment(privateShares = arrayListOf(groupSharesList[0])) + loadShareFileFragment(shares = listOf(groupSharesList.first())) onView(withText("Suicide Squad (group)")).check(matches(isDisplayed())) onView(withText("Suicide Squad (group)")).check(matches(hasSibling(withId(R.id.icon)))) .check(matches(isDisplayed())) @@ -149,20 +164,23 @@ class ShareFileFragmentTest { ******************************************* PUBLIC SHARES ******************************************** ******************************************************************************************************/ - private var publicShareList = arrayListOf( - AppTestUtil.createPublicShare( + private var publicShareList = listOf( + DUMMY_SHARE.copy( + shareType = ShareType.PUBLIC_LINK, path = "/Photos/image.jpg", isFolder = false, name = "Image link", shareLink = "http://server:port/s/1" ), - AppTestUtil.createPublicShare( + DUMMY_SHARE.copy( + shareType = ShareType.PUBLIC_LINK, path = "/Photos/image.jpg", isFolder = false, name = "Image link 2", shareLink = "http://server:port/s/2" ), - AppTestUtil.createPublicShare( + DUMMY_SHARE.copy( + shareType = ShareType.PUBLIC_LINK, path = "/Photos/image.jpg", isFolder = false, name = "Image link 3", @@ -172,13 +190,13 @@ class ShareFileFragmentTest { @Test fun showNoPublicShares() { - loadShareFileFragment(publicShares = arrayListOf()) + loadShareFileFragment(shares = listOf()) onView(withText(R.string.share_no_public_links)).check(matches(isDisplayed())) } @Test fun showPublicShares() { - loadShareFileFragment() + loadShareFileFragment(shares = publicShareList) onView(withText("Image link")).check(matches(isDisplayed())) onView(withText("Image link")).check(matches(hasSibling(withId(R.id.getPublicLinkButton)))) .check(matches(isDisplayed())) @@ -193,7 +211,8 @@ class ShareFileFragmentTest { @Test fun showPublicSharesSharingEnabled() { loadShareFileFragment( - capabilities = AppTestUtil.createCapability(sharingPublicEnabled = CapabilityBooleanType.TRUE.value) + capabilities = DUMMY_CAPABILITY.copy(filesSharingPublicEnabled = CapabilityBooleanType.TRUE), + shares = publicShareList ) onView(withText("Image link")).check(matches(isDisplayed())) @@ -204,7 +223,8 @@ class ShareFileFragmentTest { @Test fun hidePublicSharesSharingDisabled() { loadShareFileFragment( - capabilities = AppTestUtil.createCapability(sharingPublicEnabled = CapabilityBooleanType.FALSE.value) + capabilities = DUMMY_CAPABILITY.copy(filesSharingPublicEnabled = CapabilityBooleanType.FALSE), + shares = publicShareList ) onView(withId(R.id.shareViaLinkSection)) @@ -214,11 +234,11 @@ class ShareFileFragmentTest { @Test fun createPublicShareMultipleCapability() { loadShareFileFragment( - capabilities = AppTestUtil.createCapability( + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value + filesSharingPublicMultiple = CapabilityBooleanType.TRUE ), - publicShares = arrayListOf(publicShareList.get(0)) + shares = listOf(publicShareList.get(0)) ) onView(withId(R.id.addPublicLinkButton)) @@ -228,11 +248,11 @@ class ShareFileFragmentTest { @Test fun cannotCreatePublicShareMultipleCapability() { loadShareFileFragment( - capabilities = AppTestUtil.createCapability( + capabilities = DUMMY_CAPABILITY.copy( versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.FALSE.value + filesSharingPublicMultiple = CapabilityBooleanType.FALSE ), - publicShares = arrayListOf(publicShareList.get(0)) + shares = listOf(publicShareList.get(0)) ) onView(withId(R.id.addPublicLinkButton)) @@ -242,10 +262,10 @@ class ShareFileFragmentTest { @Test fun cannotCreatePublicShareServerCapability() { loadShareFileFragment( - capabilities = AppTestUtil.createCapability( + capabilities = DUMMY_CAPABILITY.copy( versionString = "9.3.1" ), - publicShares = arrayListOf(publicShareList.get(0)) + shares = listOf(publicShareList.get(0)) ) onView(withId(R.id.addPublicLinkButton)) @@ -259,7 +279,9 @@ class ShareFileFragmentTest { @Test fun hideSharesSharingApiDisabled() { loadShareFileFragment( - capabilities = TestUtil.createCapability(sharingApiEnabled = CapabilityBooleanType.FALSE.value) + capabilities = DUMMY_CAPABILITY.copy( + filesSharingApiEnabled = CapabilityBooleanType.FALSE + ) ) onView(withId(R.id.shareWithUsersSection)) .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE))) @@ -268,33 +290,34 @@ class ShareFileFragmentTest { .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE))) } - private fun getOCFileForTesting(name: String = "default") = OCFile("/Photos").apply { - availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - fileName = name - fileId = 9456985479 - remoteId = "1" - privateLink = "private link" - } - private fun loadShareFileFragment( - capabilities: OCCapabilityEntity = AppTestUtil.createCapability(), - privateShares: ArrayList = arrayListOf(), - publicShares: ArrayList = publicShareList + capabilities: OCCapability = DUMMY_CAPABILITY, + shares: List = listOf(DUMMY_SHARE) ) { - val account = mockkClass(Account::class) val ownCloudVersion = mockkClass(OwnCloudVersion::class) every { ownCloudVersion.isSearchUsersSupported } returns true val shareFileFragment = ShareFileFragment.newInstance( - getOCFileForTesting("image.jpg"), - account, + DUMMY_FILE, + DUMMY_ACCOUNT, ownCloudVersion ) - activityRule.activity.capabilities = capabilities - activityRule.activity.privateShares = privateShares - activityRule.activity.publicShares = publicShares - activityRule.activity.setFragment(shareFileFragment) + ActivityScenario.launch(TestShareFileActivity::class.java).onActivity { + it.startFragment(shareFileFragment) + } + + capabilitiesLiveData.postValue( + UIResult.Success( + capabilities + ) + ) + + sharesLiveData.postValue( + UIResult.Success( + shares + ) + ) } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt index c252c8b1268..f3fabc19c21 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt @@ -21,63 +21,93 @@ package com.owncloud.android.sharing.shares.ui import android.accounts.Account +import android.content.Context +import androidx.lifecycle.MutableLiveData +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.rule.ActivityTestRule import com.owncloud.android.R -import com.owncloud.android.datamodel.OCFile +import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.lib.resources.status.OwnCloudVersion +import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.ShareFileFragment +import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel +import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel import com.owncloud.android.utils.AppTestUtil +import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT +import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY +import com.owncloud.android.utils.AppTestUtil.DUMMY_FOLDER +import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE import io.mockk.every +import io.mockk.mockk import io.mockk.mockkClass -import org.hamcrest.Matchers.not +import org.hamcrest.CoreMatchers.not import org.junit.Before -import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith +import org.koin.android.ext.koin.androidContext +import org.koin.androidx.viewmodel.dsl.viewModel +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.dsl.module @RunWith(AndroidJUnit4::class) class ShareFolderFragmentTest { - @Rule - @JvmField - val activityRule = ActivityTestRule(TestShareFileActivity::class.java, true, true) - - private lateinit var shareFragment: ShareFileFragment + private val ocCapabilityViewModel = mockk(relaxed = true) + private val capabilitiesLiveData = MutableLiveData>() + private val ocShareViewModel = mockk(relaxed = true) + private val sharesLiveData = MutableLiveData>>() @Before fun setUp() { - val account = mockkClass(Account::class) + every { ocCapabilityViewModel.capabilities } returns capabilitiesLiveData + every { ocShareViewModel.shares } returns sharesLiveData + + stopKoin() + + startKoin { + androidContext(ApplicationProvider.getApplicationContext()) + modules( + module(override = true) { + viewModel { + ocCapabilityViewModel + } + viewModel { + ocShareViewModel + } + } + ) + } + val ownCloudVersion = mockkClass(OwnCloudVersion::class) every { ownCloudVersion.isSearchUsersSupported } returns true - shareFragment = ShareFileFragment.newInstance( - getOCFolderForTesting("Photos"), - account, + val shareFileFragment = ShareFileFragment.newInstance( + DUMMY_FOLDER, + DUMMY_ACCOUNT, ownCloudVersion ) - activityRule.activity.capabilities = AppTestUtil.createCapability() - activityRule.activity.publicShares = arrayListOf( - AppTestUtil.createPublicShare( - path = "/Photos", - isFolder = true, - name = "Photos link 1", - shareLink = "http://server:port/s/1" + ActivityScenario.launch(TestShareFileActivity::class.java).onActivity { + it.startFragment(shareFileFragment) + } + + capabilitiesLiveData.postValue( + UIResult.Success( + DUMMY_CAPABILITY ) ) - activityRule.activity.privateShares = arrayListOf( - AppTestUtil.createPrivateShare( - path = "/Photos", - isFolder = true, - shareWith = "username", - sharedWithDisplayName = "Bob" + + sharesLiveData.postValue( + UIResult.Success( + listOf(DUMMY_SHARE) ) ) - activityRule.activity.setFragment(shareFragment) } @Test @@ -89,15 +119,4 @@ class ShareFolderFragmentTest { fun hidePrivateLink() { onView(withId(R.id.getPrivateLinkButton)).check(matches(not(isDisplayed()))) } - - private fun getOCFolderForTesting(name: String = "default"): OCFile { - val file = OCFile("/Photos") - file.availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - file.fileName = name - file.fileId = 9456985479 - file.remoteId = "1" - file.mimetype = "DIR" - file.privateLink = null - return file - } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsManager.java b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsManager.java deleted file mode 100644 index dbd0db68826..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsManager.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * ownCloud Android client application - *

- * Copyright (C) 2016 ownCloud GmbH. - *

- *

- *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - *

- * This program 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 this program. If not, see . - */ - -package com.owncloud.android.utils; - -import android.accounts.Account; -import android.accounts.AccountManager; -import android.content.Context; -import android.os.SystemClock; - -import com.owncloud.android.MainApp; -import com.owncloud.android.datamodel.FileDataStorageManager; -import com.owncloud.android.lib.common.accounts.AccountUtils; -import com.owncloud.android.lib.resources.status.RemoteCapability; -import com.owncloud.android.lib.resources.status.OwnCloudVersion; - -public class AccountsManager { - - private static String accountType = "owncloud"; - private static final String KEY_AUTH_TOKEN_TYPE = "AUTH_TOKEN_TYPE"; - private static final String KEY_AUTH_TOKEN = "AUTH_TOKEN"; - private static String version = ""; - private static int WAIT_UNTIL_ACCOUNT_CREATED_MS = 1000; - private static final String HTTP_SCHEME = "http://"; - private static final String HTTPS_SCHEME = "https://"; - - public static void addAccount(Context context, String baseUrl, String username, String password) { - - // obtaining an AccountManager instance - AccountManager accountManager = AccountManager.get(context); - Account account = new Account(username + "@" + regularURL(baseUrl), accountType); - accountManager.addAccountExplicitly(account, password, null); - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - new OwnCloudVersion(version).toString() - ); - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - baseUrl - ); - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - username - ); - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - KEY_AUTH_TOKEN - ); - - } - - //Remove an account from the device - public static void deleteAccount(Context context, String accountDel) { - AccountManager accountManager = AccountManager.get(context); - Account account = new Account(accountDel, accountType); - accountManager.removeAccount(account, null, null); - } - - //Remove all accounts from the device - public static void deleteAllAccounts(Context context) { - AccountManager accountManager = AccountManager.get(context); - Account[] accounts = accountManager.getAccounts(); - for (int i = 0; i < accounts.length; i++) { - if (accounts[i].type.compareTo(accountType) == 0) { - accountManager.removeAccount(accounts[i], null, null); - SystemClock.sleep(WAIT_UNTIL_ACCOUNT_CREATED_MS); - } - } - } - - //To regularize the URL to build the URL inserted in the account device - public static String regularURL(String url) { - String url_regularized = null; - if (url.startsWith(HTTPS_SCHEME)) { - url_regularized = url.substring(8, url.length()); //skipping the protocol - } else if (url.startsWith(HTTP_SCHEME)) { - url_regularized = url.substring(7, url.length()); //skipping the protocol - } else { - return url; - } - return url_regularized; - } - - //Get server capabilities - public static RemoteCapability getCapabilities(String server, String user, String pass) { - //REDO -> need mocks or integration with new networking stuff - return new RemoteCapability(); - - } - - //Save capabilities (in device DB) - public static void saveCapabilities(Context context, RemoteCapability capabilities, String server, String user) { - FileDataStorageManager fm = new FileDataStorageManager(context, new Account(buildAccountName(user, server), - accountType), - MainApp.Companion.getAppContext().getContentResolver()); - fm.saveCapabilities(capabilities); - } - - //Build account name - private static String buildAccountName(String user, String server) { - return user + "@" + regularURL(server); - } - -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsTestManager.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsTestManager.kt new file mode 100644 index 00000000000..18ecd0f949e --- /dev/null +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsTestManager.kt @@ -0,0 +1,102 @@ +/** + * ownCloud Android client application + * + * + * Copyright (C) 2016 ownCloud GmbH. + * + * + * + * + * + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * + * This program 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 this program. If not, see //www.gnu.org/licenses/>. + */ +package com.owncloud.android.utils + +import android.accounts.Account +import android.accounts.AccountManager +import android.content.Context +import android.os.SystemClock +import com.owncloud.android.authentication.AccountAuthenticator +import com.owncloud.android.lib.common.accounts.AccountUtils +import com.owncloud.android.lib.resources.status.OwnCloudVersion + +object AccountsTestManager { + private const val accountType = "owncloud" + private const val KEY_AUTH_TOKEN_TYPE = "AUTH_TOKEN_TYPE" + private const val KEY_AUTH_TOKEN = "AUTH_TOKEN" + private const val version = "" + private const val WAIT_UNTIL_ACCOUNT_CREATED_MS = 1000 + private const val HTTP_SCHEME = "http://" + private const val HTTPS_SCHEME = "https://" + + fun addAccount( + context: Context?, + account: Account, + password: String? + ) { // obtaining an AccountManager instance + // obtaining an AccountManager instance + val accountManager = AccountManager.get(context) + + accountManager.addAccountExplicitly(account, password, null) + + // include account version, user, server version and token with the new account + accountManager.setUserData( + account, + AccountUtils.Constants.KEY_OC_VERSION, + OwnCloudVersion("10.2").toString() + ) + accountManager.setUserData( + account, + AccountUtils.Constants.KEY_OC_BASE_URL, + "serverUrl:port" + ) + accountManager.setUserData( + account, + AccountUtils.Constants.KEY_DISPLAY_NAME, + "admin" + ) + accountManager.setUserData( + account, + AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, + "1" + ) + + accountManager.setAuthToken( + account, + AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, + "AUTH_TOKEN" + ) + } + + //Remove an account from the device + fun deleteAccount(context: Context?, accountDel: String?) { + val accountManager = AccountManager.get(context) + val account = Account(accountDel, accountType) + accountManager.removeAccount(account, null, null) + } + + //Remove all accounts from the device + fun deleteAllAccounts(context: Context?) { + val accountManager = AccountManager.get(context) + val accounts = accountManager.accounts + for (account in accounts) { + if (account.type.compareTo(accountType) == 0) { + accountManager.removeAccount(account, null, null) + SystemClock.sleep(WAIT_UNTIL_ACCOUNT_CREATED_MS.toLong()) + } + } + } +} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt index cb2cdb3f388..9813defbdb1 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt @@ -22,6 +22,7 @@ package com.owncloud.android.utils import android.accounts.Account import com.owncloud.android.data.capabilities.db.OCCapabilityEntity import com.owncloud.android.data.sharing.shares.db.OCShareEntity +import com.owncloud.android.datamodel.OCFile import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.OCShare @@ -53,83 +54,6 @@ object AppTestUtil { shareLink = "" ) - private fun createShare( - fileSource: Long = 7, - itemSource: Long = 7, - shareType: Int, // Public share by default - shareWith: String = "", - path: String, - permissions: Int = 1, - sharedDate: Long = 1542628397, - expirationDate: Long = 0, - token: String = "pwdasd12dasdWZ", - sharedWithDisplayName: String = "", - sharedWithAdditionalInfo: String = "", - isFolder: Boolean, - userId: Long = -1, - remoteId: Long = 1, - accountOwner: String = "admin@server", - name: String = "", - shareLink: String = "" - ) = OCShareEntity( - fileSource, - itemSource, - shareType, - shareWith, - path, - permissions, - sharedDate, - expirationDate, - token, - sharedWithDisplayName, - sharedWithAdditionalInfo, - isFolder, - userId, - remoteId, - accountOwner, - name, - shareLink - ) - - fun createPrivateShare( - shareType: Int = 0, - shareWith: String, - path: String, - isFolder: Boolean, - sharedWithDisplayName: String, - accountOwner: String = "admin@server" - ) = createShare( - shareType = shareType, - shareWith = shareWith, - path = path, - isFolder = isFolder, - sharedWithDisplayName = sharedWithDisplayName, - accountOwner = accountOwner - ) - - fun createPublicShare( - shareWith: String = "", - path: String, - expirationDate: Long = 1000, - isFolder: Boolean, - permissions: Int = 1, - remoteId: Long = 1, - accountOwner: String = "admin@server", - name: String, - shareLink: String - ) = createShare( - shareWith = shareWith, - shareType = 3, - path = path, - permissions = permissions, - expirationDate = expirationDate, - isFolder = isFolder, - remoteId = remoteId, - accountOwner = accountOwner, - name = name, - shareLink = shareLink - ) - /** * Sharees */ @@ -188,76 +112,27 @@ object AppTestUtil { filesVersioning = CapabilityBooleanType.FALSE ) - fun createCapability( - accountName: String = "user@server", - versionMayor: Int = 2, - versionMinor: Int = 1, - versionMicro: Int = 0, - versionString: String = "1.0.0", - versionEdition: String = "1.0.0", - corePollinterval: Int = 0, - sharingApiEnabled: Int = 0, - sharingSearchMinLength: Int = 3, - sharingPublicEnabled: Int = 1, - sharingPublicPasswordEnforced: Int = 0, - sharingPublicPasswordEnforcedReadOnly: Int = 0, - sharingPublicPasswordEnforcedReadWrite: Int = 0, - sharingPublicPasswordEnforcedUploadOnly: Int = 0, - sharingPublicExpireDateEnabled: Int = 0, - sharingPublicExpireDateDays: Int = 0, - sharingPublicExpireDateEnforced: Int = 0, - sharingPublicSendMail: Int = 0, - sharingPublicUpload: Int = 0, - sharingPublicMultiple: Int = 0, - sharingPublicSupportsUploadOnly: Int = 0, - sharingUserSendMail: Int = 0, - sharingResharing: Int = 0, - sharingFederationOutgoing: Int = 0, - sharingFederationIncoming: Int = 0, - filesBigFileChunking: Int = 0, - filesUndelete: Int = 0, - filesVersioning: Int = 0 - ) = OCCapabilityEntity( - accountName, - versionMayor, - versionMinor, - versionMicro, - versionString, - versionEdition, - corePollinterval, - sharingApiEnabled, - sharingSearchMinLength, - sharingPublicEnabled, - sharingPublicPasswordEnforced, - sharingPublicPasswordEnforcedReadOnly, - sharingPublicPasswordEnforcedReadWrite, - sharingPublicPasswordEnforcedUploadOnly, - sharingPublicExpireDateEnabled, - sharingPublicExpireDateDays, - sharingPublicExpireDateEnforced, - sharingPublicSendMail, - sharingPublicUpload, - sharingPublicMultiple, - sharingPublicSupportsUploadOnly, - sharingUserSendMail, - sharingResharing, - sharingFederationOutgoing, - sharingFederationIncoming, - filesBigFileChunking, - filesUndelete, - filesVersioning - ) - - fun createAccount(name: String, type: String): Account { - val account = Account("MyAccount", "SomeType") - val nameField = account.javaClass.getDeclaredField("name") - nameField.isAccessible = true - nameField.set(account, name) + /** + * Accounts + */ + val DUMMY_ACCOUNT = Account("test", "ownCloudTest") - val typeField = account.javaClass.getDeclaredField("type") - typeField.isAccessible = true - typeField.set(account, type) + /** + * Files + */ + val DUMMY_FILE = OCFile( + "/Images/img.png" + ).apply { + fileId = 1 + fileName = "img.png" + mimetype = ".png" + privateLink = "privateLink" + } - return account + val DUMMY_FOLDER = OCFile( + "/Images/img.png" + ).apply { + fileName = "/Documents/" + mimetype = "DIR" } } From 7065a96d8c7ffecaa74d0168fdefca2c758de5c7 Mon Sep 17 00:00:00 2001 From: davigonz Date: Wed, 20 Nov 2019 09:39:19 +0100 Subject: [PATCH 19/41] Complete fragment and provider tests --- .../shares/ui/EditPrivateShareFragmentTest.kt | 146 +++++++----------- .../com/owncloud/android/utils/AppTestUtil.kt | 2 +- .../owncloud/android/testutil/OCAccount.kt | 2 +- 3 files changed, 62 insertions(+), 88 deletions(-) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt index ee894fe1bc9..65249be496a 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt @@ -19,8 +19,10 @@ package com.owncloud.android.sharing.shares.ui -import android.accounts.Account -import android.accounts.AccountManager +import android.content.Context +import androidx.lifecycle.MutableLiveData +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches @@ -31,86 +33,49 @@ import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.sharing.domain.OCShare +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.EditPrivateShareFragment -import com.owncloud.android.utils.AccountsManager +import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel +import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT +import com.owncloud.android.utils.AppTestUtil.DUMMY_FILE +import com.owncloud.android.utils.AppTestUtil.DUMMY_FOLDER +import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE import com.owncloud.android.utils.Permissions -import com.owncloud.android.utils.TestUtil +import io.mockk.every +import io.mockk.mockk import org.hamcrest.CoreMatchers.not -import org.junit.AfterClass -import org.junit.BeforeClass -import org.junit.Rule +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.Mockito.`when` -import org.mockito.Mockito.mock +import org.koin.android.ext.koin.androidContext +import org.koin.androidx.viewmodel.dsl.viewModel +import org.koin.core.context.startKoin +import org.koin.core.context.stopKoin +import org.koin.dsl.module @RunWith(AndroidJUnit4::class) class EditPrivateShareFragmentTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - TestShareFileActivity::class.java, - true, - true - ) - + private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext private val defaultSharedWithDisplayName = "user" - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "1234", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" + private val ocShareViewModel = mockk(relaxed = true) + private val privateShareAsLiveData = MutableLiveData>() + + @Before + fun setUp() { + every { ocShareViewModel.privateShare } returns privateShareAsLiveData + + stopKoin() + + startKoin { + androidContext(ApplicationProvider.getApplicationContext()) + modules( + module(override = true) { + viewModel { + ocShareViewModel + } + } ) } } @@ -270,24 +235,33 @@ class EditPrivateShareFragmentTest { isFolder: Boolean = false, permissions: Int = Permissions.READ_PERMISSIONS.value ) { - val shareToEdit = mock(OCShare::class.java) - `when`(shareToEdit.sharedWithDisplayName).thenReturn(defaultSharedWithDisplayName) - `when`(shareToEdit.permissions).thenReturn(permissions) + val shareToEdit = DUMMY_SHARE.copy( + sharedWithDisplayName = defaultSharedWithDisplayName, + permissions = permissions + ) - val sharedFile = mock(OCFile::class.java) - `when`(sharedFile.isFolder).thenReturn(isFolder) + val sharedFile = if (isFolder) DUMMY_FOLDER else DUMMY_FILE - val editPrivateShareFragment = EditPrivateShareFragment.newInstance(shareToEdit, sharedFile, account) + val editPrivateShareFragment = EditPrivateShareFragment.newInstance( + shareToEdit, + sharedFile, + DUMMY_ACCOUNT + ) + + ActivityScenario.launch(TestShareFileActivity::class.java).onActivity { + it.startFragment(editPrivateShareFragment) + } - activityRule.activity.privateShares = arrayListOf( - TestUtil.createPrivateShare( - shareWith = "user", - sharedWithDisplayName = "User", - path = "/Videos", - isFolder = isFolder, - permissions = permissions + privateShareAsLiveData.postValue( + UIResult.Success( + DUMMY_SHARE.copy( + shareWith = "user", + sharedWithDisplayName = "User", + path = "/Videos", + isFolder = isFolder, + permissions = permissions + ) ) ) - activityRule.activity.setFragment(editPrivateShareFragment) } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt index 9813defbdb1..e57766b3182 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt @@ -115,7 +115,7 @@ object AppTestUtil { /** * Accounts */ - val DUMMY_ACCOUNT = Account("test", "ownCloudTest") + val DUMMY_ACCOUNT = Account("test", "owncloud") /** * Files diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt index 757b137265a..d2f7f0af636 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt @@ -1,3 +1,3 @@ package com.owncloud.android.testutil -const val OC_ACCOUNT_NAME = "admin@server" \ No newline at end of file +const val OC_ACCOUNT_NAME = "admin@server" From baa0592e985ec9d184d5425c7fdc36d090439d61 Mon Sep 17 00:00:00 2001 From: davigonz Date: Wed, 20 Nov 2019 12:47:23 +0100 Subject: [PATCH 20/41] Fix some error tests --- .../shares/flow/CreatePublicShareTest.kt | 370 -------------- .../shares/flow/DeletePublicShareTest.kt | 309 ------------ .../shares/flow/EditPublicShareFolderTest.kt | 416 ---------------- .../shares/flow/EditPublicShareTest.kt | 462 ------------------ .../sharing/shares/flow/LoadSharesTest.kt | 279 ----------- .../PublicShareCreationDialogFragmentTest.kt | 2 + .../shares/ui/ShareFileFragmentTest.kt | 28 +- 7 files changed, 18 insertions(+), 1848 deletions(-) delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/CreatePublicShareTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/DeletePublicShareTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareFolderTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/LoadSharesTest.kt diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/CreatePublicShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/CreatePublicShareTest.kt deleted file mode 100644 index c0bd2f115fc..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/CreatePublicShareTest.kt +++ /dev/null @@ -1,370 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.sharing.shares.flow - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.assertion.ViewAssertions.doesNotExist -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator.KEY_AUTH_TOKEN_TYPE -import com.owncloud.android.data.DataResult -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel -import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.presentation.ui.sharing.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.AppTestUtil -import io.mockk.every -import io.mockk.mockk -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module - -class CreatePublicShareTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val publicShares = arrayListOf( - AppTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1" - ), - AppTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg link (2)", - shareLink = "http://server:port/s/2" - ), - AppTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg link (3)", - shareLink = "http://server:port/s/3" - ) - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val sharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = mockk(relaxed = true) - private val ocShareViewModel = mockk(relaxed = true) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = Intent() - - file = getOCFileForTesting("image.jpg") - intent.putExtra(FileActivity.EXTRA_FILE, file) - - every { ocCapabilityViewModel.getCapabilityForAccount(false) } returns capabilitiesLiveData - every { ocCapabilityViewModel.getCapabilityForAccount(true) } returns capabilitiesLiveData - every { ocShareViewModel.getPublicShares(file.remotePath) } returns sharesLiveData - every { ocShareViewModel.getPrivateShares(file.remotePath) } returns MutableLiveData() - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @Test - fun createPublicShareWithNoPublicSharesYet() { - loadCapabilitiesSuccessfully() - loadSharesSuccessfully(arrayListOf()) - - // Create share - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare = publicShares[0] - savePublicShare(newPublicShare) - - // New share properly created - sharesLiveData.postValue( - DataResult.success( - arrayListOf(newPublicShare) - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare.name)).check(matches(isDisplayed())) - } - - @Test - fun createPublicShareWithAlreadyExistingShares() { - loadCapabilitiesSuccessfully() - val existingPublicShares = publicShares.take(2) as ArrayList - loadSharesSuccessfully( - existingPublicShares - ) - - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare = publicShares[2] - savePublicShare(newPublicShare) - - // New share properly created - sharesLiveData.postValue( - DataResult.success( - publicShares - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare.name)).check(matches(isDisplayed())) - } - - @Test - fun createMultiplePublicShares() { - loadCapabilitiesSuccessfully() - loadSharesSuccessfully(arrayListOf()) - - /** - * 1st public share - */ - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare1 = publicShares[0] - savePublicShare(newPublicShare1) - - // New share properly created - sharesLiveData.postValue( - DataResult.success( - arrayListOf(newPublicShare1) - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare1.name)).check(matches(isDisplayed())) - - /** - * 2nd public share - */ - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare2 = publicShares[1] - savePublicShare(newPublicShare2) - - // New share properly created - sharesLiveData.postValue( - DataResult.success( - publicShares.take(2) - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare2.name)).check(matches(isDisplayed())) - - /** - * 3rd public share - */ - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - val newPublicShare3 = publicShares[2] - savePublicShare(newPublicShare3) - - // New share properly created - sharesLiveData.postValue( - DataResult.success( - publicShares - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_create_title)).check(doesNotExist()) - onView(withText(newPublicShare3.name)).check(matches(isDisplayed())) - } - - @Test - fun createShareLoading() { - loadCapabilitiesSuccessfully() - loadSharesSuccessfully(arrayListOf()) - - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - savePublicShare(publicShares[0], DataResult.loading()) - - onView(withText(R.string.common_loading)).check(matches(isDisplayed())) - } - - @Test - fun createShareError() { - loadCapabilitiesSuccessfully() - loadSharesSuccessfully(arrayListOf()) - - onView(withId(R.id.addPublicLinkButton)).perform(click()) - - savePublicShare( - publicShares[0], - DataResult.error( - RemoteOperationResult.ResultCode.FORBIDDEN, - exception = Exception("Error when retrieving shares") - ) - ) - - onView(withText(R.string.share_link_file_error)).check(matches(isDisplayed())) - } - - private fun getOCFileForTesting(name: String = "default") = OCFile("/Photos").apply { - availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - fileName = name - fileId = 9456985479 - remoteId = "1" - privateLink = "private link" - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapabilityEntity = AppTestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - DataResult.success( - capability - ) - ) - } - - private fun loadSharesSuccessfully(shares: ArrayList = publicShares) { - sharesLiveData.postValue(DataResult.success(shares)) - } - - private fun savePublicShare(newShare: OCShareEntity, resource: DataResult = DataResult.success()) { - - every { - ocShareViewModel.insertPublicShare( - file.remotePath, - 1, - newShare.name!!, - "", - -1, - false - ) - } returns MutableLiveData>().apply { - postValue(resource) - } - - onView(withId(R.id.saveButton)).perform(click()) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/DeletePublicShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/DeletePublicShareTest.kt deleted file mode 100644 index fa2677a5c0c..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/DeletePublicShareTest.kt +++ /dev/null @@ -1,309 +0,0 @@ -/** - * ownCloud Android client application - * - * @author Jesus Recio (@jesmrec) - * @author David González (@davigonz) - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.sharing.shares.flow - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.assertion.ViewAssertions.doesNotExist -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.hasSibling -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator.KEY_AUTH_TOKEN_TYPE -import com.owncloud.android.data.DataResult -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel -import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.presentation.ui.sharing.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.AppTestUtil -import io.mockk.every -import io.mockk.mockk -import org.hamcrest.Matchers.allOf -import org.hamcrest.Matchers.not -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module - -class DeletePublicShareTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val publicShares = arrayListOf( - AppTestUtil.createPublicShare( // With no expiration date - path = "/Photos/image.jpg", - expirationDate = 0L, - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1" - ), - AppTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg updated link", - shareLink = "http://server:port/s/2" - ) - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val sharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = mockk(relaxed = true) - private val ocShareViewModel = mockk(relaxed = true) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = Intent() - - file = getOCFileForTesting("image.jpg") - intent.putExtra(FileActivity.EXTRA_FILE, file) - - every { ocCapabilityViewModel.getCapabilityForAccount(false) } returns capabilitiesLiveData - every { ocCapabilityViewModel.getCapabilityForAccount(true) } returns capabilitiesLiveData - every { ocShareViewModel.getPublicShares(file.remotePath) } returns sharesLiveData - every { ocShareViewModel.getPrivateShares(file.remotePath) } returns MutableLiveData() - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @Test - fun deletePublicLink() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares.take(2) as ArrayList - loadSharesSuccessfully(existingPublicShare) - - every { - ocShareViewModel.deleteShare(any()) - } returns MutableLiveData>().apply { - postValue(DataResult.success()) - - } - - onView(allOf(withId(R.id.deletePublicLinkButton), hasSibling(withText(existingPublicShare[0].name)))) - .perform(click()) - onView(withId(android.R.id.button1)).perform(click()) - - sharesLiveData.postValue( - DataResult.success( - arrayListOf(existingPublicShare[1]) - ) - ) - - onView(withText(existingPublicShare[0].name)).check(doesNotExist()) - onView(withText(existingPublicShare[1].name)).check(matches(isDisplayed())) - } - - @Test - fun deleteLastPublicLink() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - every { - ocShareViewModel.deleteShare(any()) - } returns MutableLiveData>().apply { - postValue(DataResult.success()) - } - - onView(withId(R.id.deletePublicLinkButton)).perform(click()) - onView(withId(android.R.id.button1)).perform(click()) - - sharesLiveData.postValue( - DataResult.success( - arrayListOf() - ) - ) - - onView(withText(existingPublicShare.name)).check(matches(not(isDisplayed()))) - onView(withText(R.string.share_no_public_links)).check(matches(isDisplayed())) - - } - - @Test - fun deleteShareLoading() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - onView(withId(R.id.deletePublicLinkButton)).perform(click()) - - sharesLiveData.postValue( - DataResult.loading( - publicShares - ) - ) - - onView(withText(R.string.common_loading)).check(matches(isDisplayed())) - } - - @Test - fun deleteShareError() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - every { - ocShareViewModel.deleteShare(any()) - } returns MutableLiveData>().apply { - postValue( - DataResult.error( - RemoteOperationResult.ResultCode.FORBIDDEN, - exception = Exception("Error when retrieving shares") - ) - ) - } - - onView(withId(R.id.deletePublicLinkButton)).perform(click()) - onView(withId(android.R.id.button1)).perform(click()) - - onView(withText(R.string.unshare_link_file_error)).check(matches(isDisplayed())) - } - - private fun getOCFileForTesting(name: String = "default"): OCFile { - val file = OCFile("/Photos/image.jpg") - file.availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - file.fileName = name - file.fileId = 9456985479 - file.remoteId = "1" - file.privateLink = "image link" - return file - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapabilityEntity = AppTestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - DataResult.success( - capability - ) - ) - } - - private fun loadSharesSuccessfully(shares: ArrayList = publicShares) { - sharesLiveData.postValue(DataResult.success(shares)) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareFolderTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareFolderTest.kt deleted file mode 100644 index 8aeba032a74..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareFolderTest.kt +++ /dev/null @@ -1,416 +0,0 @@ -/** - * ownCloud Android client application - * - * @author Jesús Recio (@jesmrec) - * @author David González (@davigonz) - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.sharing.shares.flow - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.action.ViewActions.replaceText -import androidx.test.espresso.action.ViewActions.scrollTo -import androidx.test.espresso.assertion.ViewAssertions.doesNotExist -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.isChecked -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator.KEY_AUTH_TOKEN_TYPE -import com.owncloud.android.data.DataResult -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel -import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.presentation.ui.sharing.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.AppTestUtil -import io.mockk.every -import io.mockk.mockk -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module - -class EditPublicShareFolderTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val publicShares = arrayListOf( - AppTestUtil.createPublicShare( - path = "/Photos/", - expirationDate = 0L, - permissions = 1, - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1" - ), - AppTestUtil.createPublicShare( // With name updated - path = "/Photos/", - expirationDate = 0L, - permissions = 1, - isFolder = true, - name = "Photos updated link", - shareLink = "http://server:port/s/1" - ), - AppTestUtil.createPublicShare( // With permission Download/View/Upload - path = "/Photos/", - expirationDate = 0L, - permissions = 15, - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1" - ), - AppTestUtil.createPublicShare( // With permission Upload only - path = "/Photos/", - expirationDate = 0L, - permissions = 4, - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1" - ), - AppTestUtil.createPublicShare( // With password - path = "/Photos/", - expirationDate = 0L, - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1", - shareWith = "1" - ) - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val sharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = mockk(relaxed = true) - private val ocShareViewModel = mockk(relaxed = true) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = Intent() - - file = getOCFileForTesting("Photos") - intent.putExtra(FileActivity.EXTRA_FILE, file) - - every { ocCapabilityViewModel.getCapabilityForAccount(false) } returns capabilitiesLiveData - every { ocCapabilityViewModel.getCapabilityForAccount(true) } returns capabilitiesLiveData - every { ocShareViewModel.getPublicShares(file.remotePath) } returns sharesLiveData - every { ocShareViewModel.getPrivateShares(file.remotePath) } returns MutableLiveData() - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @Test - fun editNameFolder() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[1] - - every { - ocShareViewModel.updatePublicShare( - 1, - updatedPublicShare.name!!, - "", - -1, - 1, - false - ) - } returns MutableLiveData>().apply { - postValue(DataResult.success()) - } - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkNameValue)).perform(replaceText(updatedPublicShare.name)) - - // 3. Save updated share - onView(withId(R.id.saveButton)).perform(scrollTo(), click()) - - // 4. Share properly updated - sharesLiveData.postValue( - DataResult.success( - arrayListOf(updatedPublicShare) - ) - ) - - // Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_edit_title)).check(doesNotExist()) - onView(withText(updatedPublicShare.name)).check(matches(isDisplayed())) - } - - @Test - fun editPermissionToDownloadViewUpload() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[2] - - every { - ocShareViewModel.updatePublicShare( - 1, - updatedPublicShare.name!!, - "", - -1, - 15, - true - ) - } returns MutableLiveData>().apply { - postValue(DataResult.success()) - } - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkEditPermissionReadAndWrite)).perform(click()) - - // 3. Save updated share - onView(withId(R.id.saveButton)).perform(scrollTo(), click()) - - // 4. Share properly updated - sharesLiveData.postValue( - DataResult.success( - arrayListOf(updatedPublicShare) - ) - ) - - // Open Dialog to check correct permission change - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkEditPermissionReadAndWrite)).check(matches(isChecked())) - - } - - @Test - fun editPermissionToUploadOnly() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[3] - - every { - ocShareViewModel.updatePublicShare( - 1, - updatedPublicShare.name!!, - "", - -1, - 4, - true - ) - } returns MutableLiveData>().apply { - postValue(DataResult.success()) - } - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).perform(click()) - - // 3. Save updated share - onView(withId(R.id.saveButton)).perform(scrollTo(), click()) - - // 4. Share properly updated - sharesLiveData.postValue( - DataResult.success( - arrayListOf(updatedPublicShare) - ) - ) - - // Open Dialog to check correct permission change - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).check(matches(isChecked())) - - } - - @Test - fun editPermissionToDownloadView() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[2] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[0] - - every { - ocShareViewModel.updatePublicShare( - 1, - updatedPublicShare.name!!, - "", - -1, - 1, - false - ) - } returns MutableLiveData>().apply { - postValue(DataResult.success()) - } - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkEditPermissionReadOnly)).perform(click()) - - // 3. Save updated share - onView(withId(R.id.saveButton)).perform(scrollTo(), click()) - - // 4. Share properly updated - sharesLiveData.postValue( - DataResult.success( - arrayListOf(updatedPublicShare) - ) - ) - - // Open Dialog to check correct permission change - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkEditPermissionReadOnly)).check(matches(isChecked())) - - } - - private fun getOCFileForTesting(name: String = "default"): OCFile { - val file = OCFile("/Photos") - file.availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - file.fileName = name - file.fileId = 9456985479 - file.remoteId = "1" - file.mimetype = "DIR" - file.privateLink = "private link" - return file - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapabilityEntity = AppTestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value, - sharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE.value, - sharingPublicUpload = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - DataResult.success( - capability - ) - ) - } - - private fun loadSharesSuccessfully(shares: ArrayList = publicShares) { - sharesLiveData.postValue(DataResult.success(shares)) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareTest.kt deleted file mode 100644 index 91bfed0fa8c..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/EditPublicShareTest.kt +++ /dev/null @@ -1,462 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.sharing.shares.flow - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import android.widget.DatePicker -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.action.ViewActions.replaceText -import androidx.test.espresso.action.ViewActions.typeText -import androidx.test.espresso.assertion.ViewAssertions.doesNotExist -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.contrib.PickerActions -import androidx.test.espresso.matcher.ViewMatchers.isChecked -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.isNotChecked -import androidx.test.espresso.matcher.ViewMatchers.withClassName -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator.KEY_AUTH_TOKEN_TYPE -import com.owncloud.android.data.DataResult -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.status.CapabilityBooleanType -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel -import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.presentation.ui.sharing.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.AppTestUtil -import io.mockk.every -import io.mockk.mockk -import org.hamcrest.Matchers -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module -import java.text.DateFormat -import java.text.SimpleDateFormat -import java.util.Calendar - -class EditPublicShareTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private lateinit var file: OCFile - - private val publicShares = arrayListOf( - AppTestUtil.createPublicShare( // With no expiration date - path = "/Photos/image.jpg", - expirationDate = 0L, - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1" - ), - AppTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg updated link", - shareLink = "http://server:port/s/2" - ), - AppTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "image.jpg changed again link", - shareLink = "http://server:port/s/3" - ), - AppTestUtil.createPublicShare( // With password but not expiration date - path = "/Photos/image.jpg", - expirationDate = 0L, - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1", - shareWith = "1" - ), - AppTestUtil.createPublicShare( // With expiration date but not password - path = "/Photos/image.jpg", - expirationDate = 2587896257, - isFolder = false, - name = "image.jpg link", - shareLink = "http://server:port/s/1" - ) - ) - - private val capabilitiesLiveData = MutableLiveData>() - private val sharesLiveData = MutableLiveData>>() - - private val ocCapabilityViewModel = mockk(relaxed = true) - private val ocShareViewModel = mockk(relaxed = true) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = Intent() - - file = getOCFileForTesting("image.jpg") - intent.putExtra(FileActivity.EXTRA_FILE, file) - - every { ocCapabilityViewModel.getCapabilityForAccount(false) } returns capabilitiesLiveData - every { ocCapabilityViewModel.getCapabilityForAccount(true) } returns capabilitiesLiveData - every { ocShareViewModel.getPublicShares(file.remotePath) } returns sharesLiveData - every { ocShareViewModel.getPrivateShares(file.remotePath) } returns MutableLiveData() - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - @Test - fun editName() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val updatedPublicShare = publicShares[1] - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Update fields - onView(withId(R.id.shareViaLinkNameValue)).perform(replaceText(updatedPublicShare.name)) - - // 3. Edit public share with success - editPublicShare(updatedPublicShare, "", resource = DataResult.success()) - - // 4. Share properly updated - sharesLiveData.postValue( - DataResult.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Check whether the dialog to create the public share has been properly closed - onView(withText(R.string.share_via_link_edit_title)).check(doesNotExist()) - onView(withText(updatedPublicShare.name)).check(matches(isDisplayed())) - } - - @Test - fun addPassword() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val password = "1234" - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Enable password and type it - onView(withId(R.id.shareViaLinkPasswordSwitch)).perform(click()) - onView(withId(R.id.shareViaLinkPasswordValue)).perform(typeText(password)) - - // 3. Edit public share with success - editPublicShare(existingPublicShare, "1234", resource = DataResult.success()) - - // 4. Share properly updated - val updatedPublicShare = publicShares[3] - - sharesLiveData.postValue( - DataResult.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Open dialog to check whether the password has been properly set - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkPasswordSwitch)).check(matches(isChecked())) - } - - @Test - fun removePassword() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[3] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Disable password - onView(withId(R.id.shareViaLinkPasswordSwitch)).perform(click()) - - // 3. Edit public share with success - editPublicShare(existingPublicShare, "", resource = DataResult.success()) - - // 4. Share properly updated - val updatedPublicShare = publicShares[0] - - sharesLiveData.postValue( - DataResult.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Open dialog to check whether the password has been properly disabled - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkPasswordSwitch)).check(matches(isNotChecked())) - } - - @Test - fun addExpirationDate() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - val calendar = Calendar.getInstance() - calendar.add(Calendar.DAY_OF_YEAR, 1) - val formatter: DateFormat = SimpleDateFormat("MMM dd, yyyy"); - val expirationDate = formatter.format(calendar.time); - val publicLinkExpirationDateInMillis = SimpleDateFormat.getDateInstance().parse(expirationDate).time - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Enable expiration date and set it - onView(withId(R.id.shareViaLinkExpirationSwitch)).perform(click()) - onView(withClassName(Matchers.equalTo(DatePicker::class.java.name))).perform( - PickerActions.setDate( - calendar.get(Calendar.YEAR), - calendar.get(Calendar.MONTH) + 1, // January code is 0, so let's add 1 - calendar.get(Calendar.DATE) - ) - ); - onView(withId(android.R.id.button1)).perform(click()) - - // 3. Edit public share with success - editPublicShare(existingPublicShare, "", publicLinkExpirationDateInMillis, DataResult.success()) - - // 4. Share properly updated - val updatedPublicShare = publicShares[4] - - sharesLiveData.postValue( - DataResult.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Open dialog to check whether the expiration date is enabled - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkExpirationSwitch)).check(matches(isChecked())) - } - - @Test - fun removeExpirationDate() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[4] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - // 1. Open dialog to edit an existing public share - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - // 2. Disable expiration date - onView(withId(R.id.shareViaLinkExpirationSwitch)).perform(click()) - - // 3. Edit public share with success - editPublicShare(existingPublicShare, "", resource = DataResult.success()) - - // 4. Share properly updated - val updatedPublicShare = publicShares[0] - - sharesLiveData.postValue( - DataResult.success( - arrayListOf(updatedPublicShare) - ) - ) - - // 5. Open dialog to check whether the expiration date is disabled - onView(withId(R.id.editPublicLinkButton)).perform(click()) - onView(withId(R.id.shareViaLinkExpirationSwitch)).check(matches(isNotChecked())) - } - - @Test - fun editShareLoading() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[3] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - editPublicShare(existingPublicShare, resource = DataResult.loading()) - - onView(withText(R.string.common_loading)).check(matches(isDisplayed())) - } - - @Test - fun editShareError() { - loadCapabilitiesSuccessfully() - - val existingPublicShare = publicShares[0] - loadSharesSuccessfully(arrayListOf(existingPublicShare)) - - onView(withId(R.id.editPublicLinkButton)).perform(click()) - - editPublicShare( - existingPublicShare, - password = "", - resource = DataResult.error( - RemoteOperationResult.ResultCode.FORBIDDEN, - exception = Exception("Error when retrieving shares") - ) - ) - - onView(withText(R.string.update_link_file_error)).check(matches(isDisplayed())) - } - - private fun getOCFileForTesting(name: String = "default") = OCFile("/Photos").apply { - availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - fileName = name - fileId = 9456985479 - remoteId = "1" - privateLink = "private link" - } - - private fun loadCapabilitiesSuccessfully( - capability: OCCapabilityEntity = AppTestUtil.createCapability( - versionString = "10.1.1", - sharingPublicMultiple = CapabilityBooleanType.TRUE.value - ) - ) { - capabilitiesLiveData.postValue( - DataResult.success( - capability - ) - ) - } - - private fun loadSharesSuccessfully(shares: ArrayList = publicShares) { - sharesLiveData.postValue(DataResult.success(shares)) - } - - private fun editPublicShare( - share: OCShareEntity, - password: String? = null, - publicLinkExpirationDateInMillis: Long = -1, - resource: DataResult = DataResult.success() // Expected result when editing the share - ) { - every { - ocShareViewModel.updatePublicShare( - 1, - share.name!!, - password, - publicLinkExpirationDateInMillis, - 1, - false - ) - } returns MutableLiveData>().apply { - postValue(resource) - } - - onView(withId(R.id.saveButton)).perform(click()) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/LoadSharesTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/LoadSharesTest.kt deleted file mode 100644 index 31507cfa18b..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/flow/LoadSharesTest.kt +++ /dev/null @@ -1,279 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.sharing.shares.flow - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.content.Intent -import androidx.lifecycle.MutableLiveData -import androidx.test.core.app.ApplicationProvider -import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.rule.ActivityTestRule -import com.owncloud.android.R -import com.owncloud.android.authentication.AccountAuthenticator.KEY_AUTH_TOKEN_TYPE -import com.owncloud.android.data.DataResult -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.status.OwnCloudVersion -import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel -import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.presentation.ui.sharing.ShareActivity -import com.owncloud.android.ui.activity.FileActivity -import com.owncloud.android.utils.AccountsManager -import com.owncloud.android.utils.AppTestUtil -import io.mockk.every -import io.mockk.mockk -import org.junit.AfterClass -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.koin.android.ext.koin.androidContext -import org.koin.androidx.viewmodel.dsl.viewModel -import org.koin.core.context.startKoin -import org.koin.core.context.stopKoin -import org.koin.dsl.module - -class LoadSharesTest { - @Rule - @JvmField - val activityRule = ActivityTestRule( - ShareActivity::class.java, - true, - false - ) - - private val ocShareViewModel = mockk(relaxed = true) - - companion object { - private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext - private val account = Account("admin", "owncloud") - - @BeforeClass - @JvmStatic - fun init() { - addAccount() - } - - @AfterClass - @JvmStatic - fun cleanUp() { - AccountsManager.deleteAllAccounts(targetContext) - } - - private fun addAccount() { - // obtaining an AccountManager instance - val accountManager = AccountManager.get(targetContext) - - accountManager.addAccountExplicitly(account, "a", null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - } - - @Before - fun setUp() { - val intent = Intent() - - val file = getOCFileForTesting("image.jpg") - intent.putExtra(FileActivity.EXTRA_FILE, file) - - every { ocCapabilityViewModel.getCapabilityForAccountAsLiveData() } returns capabilitiesLiveData - every { ocShareViewModel.getPublicShares(file.remotePath) } returns publicSharesLiveData - every { ocShareViewModel.getPrivateShares(file.remotePath) } returns privateSharesLiveData - - stopKoin() - - startKoin { - androidContext(ApplicationProvider.getApplicationContext()) - modules( - module(override = true) { - viewModel { - ocCapabilityViewModel - } - viewModel { - ocShareViewModel - } - } - ) - } - - activityRule.launchActivity(intent) - } - - /****************************************************************************************************** - ******************************************** CAPABILITIES ******************************************** - ******************************************************************************************************/ - - private val ocCapabilityViewModel = mockk(relaxed = true) - private val capabilitiesLiveData = MutableLiveData>() - - @Test - fun showLoadingCapabilitiesDialog() { - capabilitiesLiveData.postValue(DataResult.loading(AppTestUtil.createCapability())) - onView(withId(R.id.loadingLayout)).check(matches(isDisplayed())) - } - - @Test - fun showErrorWhenLoadingCapabilities() { - capabilitiesLiveData.postValue( - DataResult.error( - RemoteOperationResult.ResultCode.SERVICE_UNAVAILABLE - ) - ) - - onView(withId(R.id.snackbar_text)).check(matches(withText(R.string.service_unavailable))) - } - - /****************************************************************************************************** - ******************************************* PRIVATE SHARES ******************************************* - ******************************************************************************************************/ - - private val privateSharesLiveData = MutableLiveData>>() - private val privateShares = arrayListOf( - AppTestUtil.createPrivateShare( - path = "/Photos/image.jpg", - isFolder = false, - shareWith = "work", - sharedWithDisplayName = "Work" - ), - AppTestUtil.createPrivateShare( - path = "/Photos/image.jpg", - isFolder = false, - shareWith = "family", - sharedWithDisplayName = "Family" - ) - ) - - @Test - fun showLoadingPrivateSharesDialog() { - loadCapabilitiesSuccessfully() - privateSharesLiveData.postValue(DataResult.loading(privateShares)) - onView(withId(R.id.loadingLayout)).check(matches(isDisplayed())) - } - - @Test - fun showErrorWhenLoadingPrivateShares() { - loadCapabilitiesSuccessfully() - - privateSharesLiveData.postValue( - DataResult.error( - RemoteOperationResult.ResultCode.FORBIDDEN, - data = privateShares - ) - ) - onView(withId(R.id.snackbar_text)).check(matches(withText(R.string.get_shares_error))) - } - - /****************************************************************************************************** - ******************************************* PUBLIC SHARES ******************************************** - ******************************************************************************************************/ - - private val publicSharesLiveData = MutableLiveData>>() - private val publicShares = arrayListOf( - AppTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "Image link", - shareLink = "http://server:port/s/1" - ), - AppTestUtil.createPublicShare( - path = "/Photos/image.jpg", - isFolder = false, - name = "Image link 2", - shareLink = "http://server:port/s/2" - ) - ) - - @Test - fun showLoadingPublicSharesDialog() { - loadCapabilitiesSuccessfully() - publicSharesLiveData.postValue(DataResult.loading(publicShares)) - onView(withId(R.id.loadingLayout)).check(matches(isDisplayed())) - } - - @Test - fun showErrorWhenLoadingPublicShares() { - loadCapabilitiesSuccessfully() - - publicSharesLiveData.postValue( - DataResult.error( - RemoteOperationResult.ResultCode.SERVICE_UNAVAILABLE, - data = publicShares - ) - ) - onView(withId(R.id.snackbar_text)).check(matches(withText(R.string.service_unavailable))) - } - - /****************************************************************************************************** - *********************************************** COMMON *********************************************** - ******************************************************************************************************/ - - private fun getOCFileForTesting(name: String = "default") = OCFile("/Photos").apply { - availableOfflineStatus = OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE - fileName = name - fileId = 9456985479 - remoteId = "1" - privateLink = "private link" - } - - private fun loadCapabilitiesSuccessfully(capability: OCCapabilityEntity = AppTestUtil.createCapability()) { - capabilitiesLiveData.postValue( - DataResult.success( - capability - ) - ) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt index 804ccab7cf4..019427ce537 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt @@ -443,6 +443,8 @@ class PublicShareCreationDialogFragmentTest { ) ) + onView(withId(R.id.public_link_error_message)).perform(scrollTo()) + onView(withText(commonError)).check(matches(isDisplayed())) onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).perform(click()) onView(withText(commonError)).check(matches(not(isDisplayed()))) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt index 4f3ff225fb4..eca36f6bb1c 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt @@ -290,9 +290,22 @@ class ShareFileFragmentTest { .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.GONE))) } + @Test + fun showError() { + loadShareFileFragment( + sharesUIResult = UIResult.Error( + error = Throwable("It was not possible to retrieve the shares from server") + ) + ) + onView(withId(com.google.android.material.R.id.snackbar_text)). + check(matches(withText(R.string.get_shares_error))) + } + private fun loadShareFileFragment( capabilities: OCCapability = DUMMY_CAPABILITY, - shares: List = listOf(DUMMY_SHARE) + capabilitiesUIResult: UIResult = UIResult.Success(capabilities), + shares: List = listOf(DUMMY_SHARE), + sharesUIResult: UIResult> = UIResult.Success(shares) ) { val ownCloudVersion = mockkClass(OwnCloudVersion::class) @@ -308,16 +321,7 @@ class ShareFileFragmentTest { it.startFragment(shareFileFragment) } - capabilitiesLiveData.postValue( - UIResult.Success( - capabilities - ) - ) - - sharesLiveData.postValue( - UIResult.Success( - shares - ) - ) + capabilitiesLiveData.postValue(capabilitiesUIResult) + sharesLiveData.postValue(sharesUIResult) } } From 4b1c53c526375524c90c460a36441ad3eea888aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Wed, 20 Nov 2019 15:03:21 +0100 Subject: [PATCH 21/41] Wrap Shares UIResult inside Event --- .../sharees/ui/SearchShareesFragmentTest.kt | 26 ++++--- .../shares/ui/EditPrivateShareFragmentTest.kt | 19 +++-- .../PublicShareCreationDialogFragmentTest.kt | 17 +++-- .../PublicShareEditionDialogFragmentTest.kt | 12 +-- .../shares/ui/ShareFileFragmentTest.kt | 11 +-- .../shares/ui/ShareFolderFragmentTest.kt | 17 +---- .../fragments/EditPrivateShareFragment.kt | 25 +++---- .../fragments/PublicShareDialogFragment.kt | 26 ++----- .../ui/sharing/fragments/ShareFileFragment.kt | 34 ++++----- .../viewmodels/sharing/OCShareViewModel.kt | 73 +++++++++---------- .../owncloud/android/domain/utils/Event.kt | 59 +++++++++++++++ 11 files changed, 176 insertions(+), 143 deletions(-) create mode 100644 owncloudDomain/src/main/java/com/owncloud/android/domain/utils/Event.kt diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt index fa2f3004c65..b42ef58c760 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt @@ -33,6 +33,7 @@ import androidx.test.espresso.matcher.ViewMatchers.withText import com.owncloud.android.R import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.SearchShareesFragment import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel @@ -43,7 +44,6 @@ import io.mockk.mockk import org.hamcrest.CoreMatchers import org.junit.Before import org.junit.Test -import org.junit.runner.RunWith import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin @@ -52,7 +52,7 @@ import org.koin.dsl.module class SearchShareesFragmentTest { private val ocShareViewModel = mockk(relaxed = true) - private val sharesLiveData = MutableLiveData>>() + private val sharesLiveData = MutableLiveData>>>() @Before fun init() { @@ -86,10 +86,12 @@ class SearchShareesFragmentTest { @Test fun showUserShares() { sharesLiveData.postValue( - UIResult.Success( - listOf( - DUMMY_SHARE.copy(sharedWithDisplayName = "Sheldon"), - DUMMY_SHARE.copy(sharedWithDisplayName = "Penny") + Event( + UIResult.Success( + listOf( + DUMMY_SHARE.copy(sharedWithDisplayName = "Sheldon"), + DUMMY_SHARE.copy(sharedWithDisplayName = "Penny") + ) ) ) ) @@ -105,11 +107,13 @@ class SearchShareesFragmentTest { @Test fun showGroupShares() { sharesLiveData.postValue( - UIResult.Success( - listOf( - DUMMY_SHARE.copy( - shareType = ShareType.GROUP, - sharedWithDisplayName = "Friends" + Event( + UIResult.Success( + listOf( + DUMMY_SHARE.copy( + shareType = ShareType.GROUP, + sharedWithDisplayName = "Friends" + ) ) ) ) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt index 65249be496a..8925234b395 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt @@ -35,6 +35,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.R import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.EditPrivateShareFragment import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel @@ -60,7 +61,7 @@ class EditPrivateShareFragmentTest { private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext private val defaultSharedWithDisplayName = "user" private val ocShareViewModel = mockk(relaxed = true) - private val privateShareAsLiveData = MutableLiveData>() + private val privateShareAsLiveData = MutableLiveData>>() @Before fun setUp() { @@ -253,13 +254,15 @@ class EditPrivateShareFragmentTest { } privateShareAsLiveData.postValue( - UIResult.Success( - DUMMY_SHARE.copy( - shareWith = "user", - sharedWithDisplayName = "User", - path = "/Videos", - isFolder = isFolder, - permissions = permissions + Event( + UIResult.Success( + DUMMY_SHARE.copy( + shareWith = "user", + sharedWithDisplayName = "User", + path = "/Videos", + isFolder = isFolder, + permissions = permissions + ) ) ) ) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt index 019427ce537..56fbc2ecd4d 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt @@ -40,6 +40,7 @@ import androidx.test.espresso.matcher.ViewMatchers.withText import com.owncloud.android.R import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability +import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.PublicShareDialogFragment import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel @@ -66,7 +67,7 @@ class PublicShareCreationDialogFragmentTest { private val ocCapabilityViewModel = mockk(relaxed = true) private val capabilitiesLiveData = MutableLiveData>() private val ocShareViewModel = mockk(relaxed = true) - private val publicShareCreationStatus = MutableLiveData>() + private val publicShareCreationStatus = MutableLiveData>>() @Before fun setUp() { @@ -201,7 +202,7 @@ class PublicShareCreationDialogFragmentTest { fun enableExpirationSwitch() { loadPublicShareDialogFragment() onView(withId(R.id.shareViaLinkExpirationSwitch)).perform(click()) - onView(withId(android.R.id.button1)).perform(click()); + onView(withId(android.R.id.button1)).perform(click()) onView(withId(R.id.shareViaLinkExpirationValue)) .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE))) //TODO: check the date form the picker @@ -223,8 +224,10 @@ class PublicShareCreationDialogFragmentTest { onView(withId(R.id.saveButton)).perform(click()) publicShareCreationStatus.postValue( - UIResult.Error( - error = Throwable("It was not possible to share this file or folder") + Event( + UIResult.Error( + error = Throwable("It was not possible to share this file or folder") + ) ) ) @@ -438,8 +441,10 @@ class PublicShareCreationDialogFragmentTest { onView(withId(R.id.saveButton)).perform(scrollTo(), click()) publicShareCreationStatus.postValue( - UIResult.Error( - error = Throwable(commonError) + Event( + UIResult.Error( + error = Throwable(commonError) + ) ) ) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt index fd51e20f5d4..5b3d4526760 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt @@ -33,9 +33,7 @@ import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import com.owncloud.android.R -import com.owncloud.android.datamodel.OCFile import com.owncloud.android.domain.capabilities.model.OCCapability -import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.resources.shares.RemoteShare import com.owncloud.android.presentation.UIResult @@ -47,7 +45,6 @@ import com.owncloud.android.utils.AppTestUtil.DUMMY_FILE import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE import io.mockk.every import io.mockk.mockk -import io.mockk.mockkClass import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -67,7 +64,6 @@ class PublicShareEditionDialogFragmentTest { private val capabilitiesLiveData = MutableLiveData>() private val ocShareViewModel = mockk(relaxed = true) - private val file = mockkClass(OCFile::class) private val expirationDate = 1556575200000 // GMT: Monday, April 29, 2019 10:00:00 PM @Before @@ -121,7 +117,7 @@ class PublicShareEditionDialogFragmentTest { @Test fun checkUploadOnly() { - onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).check(matches(isChecked())); + onView(withId(R.id.shareViaLinkEditPermissionUploadFiles)).check(matches(isChecked())) } @Test @@ -140,10 +136,10 @@ class PublicShareEditionDialogFragmentTest { val calendar = GregorianCalendar() calendar.timeInMillis = expirationDate - val formatter: DateFormat = SimpleDateFormat("MMM dd, yyyy"); - formatter.timeZone = TimeZone.getDefault(); + val formatter: DateFormat = SimpleDateFormat("MMM dd, yyyy") + formatter.timeZone = TimeZone.getDefault() - val time = formatter.format(calendar.time); + val time = formatter.format(calendar.time) onView(withId(R.id.shareViaLinkExpirationLabel)).check( matches(withText(R.string.share_via_link_expiration_date_label)) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt index eca36f6bb1c..6b3a9b54a9e 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt @@ -37,6 +37,7 @@ import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.domain.utils.Event import com.owncloud.android.lib.resources.status.OwnCloudVersion import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.ShareFileFragment @@ -62,7 +63,7 @@ class ShareFileFragmentTest { private val ocCapabilityViewModel = mockk(relaxed = true) private val capabilitiesLiveData = MutableLiveData>() private val ocShareViewModel = mockk(relaxed = true) - private val sharesLiveData = MutableLiveData>>() + private val sharesLiveData = MutableLiveData>>>() @Before fun setUp() { @@ -238,7 +239,7 @@ class ShareFileFragmentTest { versionString = "10.1.1", filesSharingPublicMultiple = CapabilityBooleanType.TRUE ), - shares = listOf(publicShareList.get(0)) + shares = listOf(publicShareList[0]) ) onView(withId(R.id.addPublicLinkButton)) @@ -252,7 +253,7 @@ class ShareFileFragmentTest { versionString = "10.1.1", filesSharingPublicMultiple = CapabilityBooleanType.FALSE ), - shares = listOf(publicShareList.get(0)) + shares = listOf(publicShareList[0]) ) onView(withId(R.id.addPublicLinkButton)) @@ -265,7 +266,7 @@ class ShareFileFragmentTest { capabilities = DUMMY_CAPABILITY.copy( versionString = "9.3.1" ), - shares = listOf(publicShareList.get(0)) + shares = listOf(publicShareList[0]) ) onView(withId(R.id.addPublicLinkButton)) @@ -322,6 +323,6 @@ class ShareFileFragmentTest { } capabilitiesLiveData.postValue(capabilitiesUIResult) - sharesLiveData.postValue(sharesUIResult) + sharesLiveData.postValue(Event(sharesUIResult)) } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt index f3fabc19c21..6ef639380ca 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt @@ -20,7 +20,6 @@ package com.owncloud.android.sharing.shares.ui -import android.accounts.Account import android.content.Context import androidx.lifecycle.MutableLiveData import androidx.test.core.app.ActivityScenario @@ -33,12 +32,12 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.owncloud.android.R import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.utils.Event import com.owncloud.android.lib.resources.status.OwnCloudVersion import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.ShareFileFragment import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.utils.AppTestUtil import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY import com.owncloud.android.utils.AppTestUtil.DUMMY_FOLDER @@ -61,7 +60,7 @@ class ShareFolderFragmentTest { private val ocCapabilityViewModel = mockk(relaxed = true) private val capabilitiesLiveData = MutableLiveData>() private val ocShareViewModel = mockk(relaxed = true) - private val sharesLiveData = MutableLiveData>>() + private val sharesLiveData = MutableLiveData>>>() @Before fun setUp() { @@ -97,17 +96,9 @@ class ShareFolderFragmentTest { it.startFragment(shareFileFragment) } - capabilitiesLiveData.postValue( - UIResult.Success( - DUMMY_CAPABILITY - ) - ) + capabilitiesLiveData.postValue(UIResult.Success(DUMMY_CAPABILITY)) - sharesLiveData.postValue( - UIResult.Success( - listOf(DUMMY_SHARE) - ) - ) + sharesLiveData.postValue(Event(UIResult.Success(listOf(DUMMY_SHARE)))) } @Test diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt index 9a9f4b4a4c9..0afb3f0579c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt @@ -25,7 +25,6 @@ package com.owncloud.android.presentation.ui.sharing.fragments import android.accounts.Account import android.content.Context import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -34,12 +33,12 @@ import android.widget.CompoundButton import androidx.appcompat.widget.SwitchCompat import androidx.core.view.isGone import androidx.fragment.app.DialogFragment -import androidx.lifecycle.Observer import com.owncloud.android.R import com.owncloud.android.authentication.AccountUtils import com.owncloud.android.datamodel.OCFile import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.domain.utils.Event.EventObserver import com.owncloud.android.extensions.parseError import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.shares.RemoteShare @@ -91,10 +90,10 @@ class EditPrivateShareFragment : DialogFragment() { if (arguments != null) { file = arguments?.getParcelable(ARG_FILE) account = arguments?.getParcelable(ARG_ACCOUNT) - if (savedInstanceState == null) { - share = arguments?.getParcelable(ARG_SHARE) + share = if (savedInstanceState == null) { + arguments?.getParcelable(ARG_SHARE) } else { - share = savedInstanceState.getParcelable(ARG_SHARE) + savedInstanceState.getParcelable(ARG_SHARE) } Log_OC.e( TAG, String.format( @@ -160,12 +159,11 @@ class EditPrivateShareFragment : DialogFragment() { /** * Updates the UI with the current permissions in the edited [RemoteShare] * - * @param editShareView Root view in the fragment. */ - fun refreshUiFromState() { + private fun refreshUiFromState() { val editShareView = view if (editShareView != null) { - setPermissionsListening(editShareView, false) + setPermissionsListening(false) val sharePermissions = share!!.permissions val isFederated = ShareType.FEDERATED == share!!.shareType @@ -205,7 +203,7 @@ class EditPrivateShareFragment : DialogFragment() { compound.visibility = if (canEdit) View.VISIBLE else View.GONE } - setPermissionsListening(editShareView, true) + setPermissionsListening(true) } } @@ -213,10 +211,9 @@ class EditPrivateShareFragment : DialogFragment() { * Binds or unbinds listener for user actions to enable or disable a permission on the edited share * to the views receiving the user events. * - * @param editShareView Root view in the fragment. * @param enable When 'true', listener is bound to view; when 'false', it is unbound. */ - private fun setPermissionsListening(editShareView: View, enable: Boolean) { + private fun setPermissionsListening(enable: Boolean) { if (enable && onPrivilegeChangeListener == null) { onPrivilegeChangeListener = OnPrivilegeChangeListener() } @@ -395,7 +392,7 @@ class EditPrivateShareFragment : DialogFragment() { private fun observePrivateShareToEdit() { ocShareViewModel.privateShare.observe( this, - Observer { uiResult -> + EventObserver { uiResult -> when (uiResult) { is UIResult.Success -> { updateShare(uiResult.data) @@ -408,7 +405,7 @@ class EditPrivateShareFragment : DialogFragment() { private fun observePrivateShareEdition() { ocShareViewModel.privateShareEditionStatus.observe( this, - Observer { uiResult -> + EventObserver { uiResult -> when (uiResult) { is UIResult.Error -> { showError(getString(R.string.update_link_file_error), uiResult.error) @@ -450,7 +447,7 @@ class EditPrivateShareFragment : DialogFragment() { * Updates the UI after the result of an update operation on the edited [RemoteShare] permissions. * */ - fun updateShare(updatedShare: OCShare?) { + private fun updateShare(updatedShare: OCShare?) { share = updatedShare refreshUiFromState() } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt index d522b174551..dcf5dfc2f36 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt @@ -26,7 +26,6 @@ import android.content.Context import android.graphics.drawable.Drawable import android.os.Bundle import android.text.InputType -import android.util.Log import android.view.LayoutInflater import android.view.MotionEvent import android.view.View @@ -44,6 +43,7 @@ import com.owncloud.android.datamodel.OCFile import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.utils.Event.EventObserver import com.owncloud.android.extensions.parseError import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.shares.RemoteShare @@ -157,9 +157,7 @@ class PublicShareDialogFragment : DialogFragment() { publicShare = arguments!!.getParcelable(ARG_SHARE) } - if (file == null && publicShare == null) { - throw IllegalStateException("Both ARG_FILE and ARG_SHARE cannot be NULL") - } + check(!(file == null && publicShare == null)) { "Both ARG_FILE and ARG_SHARE cannot be NULL" } setStyle(STYLE_NO_TITLE, 0) } @@ -464,7 +462,7 @@ class PublicShareDialogFragment : DialogFragment() { private fun observePublicShareCreation() { ocShareViewModel.publicShareCreationStatus.observe( this, - Observer { uiResult -> + EventObserver { uiResult -> when (uiResult) { is UIResult.Success -> { dismiss() @@ -476,11 +474,6 @@ class PublicShareDialogFragment : DialogFragment() { is UIResult.Loading -> { listener?.showLoading() } - else -> { - Log.d( - TAG, "Unknown status when creating public share" - ) - } } } ) @@ -489,7 +482,7 @@ class PublicShareDialogFragment : DialogFragment() { private fun observePublicShareEdition() { ocShareViewModel.publicShareEditionStatus.observe( this, - Observer { uiResult -> + EventObserver { uiResult -> when (uiResult) { is UIResult.Success -> { dismiss() @@ -501,11 +494,6 @@ class PublicShareDialogFragment : DialogFragment() { is UIResult.Loading -> { listener?.showLoading() } - else -> { - Log.d( - TAG, "Unknown status when editing public share" - ) - } } } ) @@ -638,7 +626,7 @@ class PublicShareDialogFragment : DialogFragment() { } } - fun updateCapabilities(capabilities: OCCapability?) { + private fun updateCapabilities(capabilities: OCCapability?) { this.capabilities = capabilities updateInputFormAccordingToServerCapabilities() } @@ -722,7 +710,7 @@ class PublicShareDialogFragment : DialogFragment() { } // Set password label depending on the checked permission option - shareViaLinkEditPermissionGroup?.setOnCheckedChangeListener { group, checkedId -> + shareViaLinkEditPermissionGroup?.setOnCheckedChangeListener { _, checkedId -> public_link_error_message?.isGone = true if (checkedId == shareViaLinkEditPermissionReadOnly.id) { @@ -776,7 +764,7 @@ class PublicShareDialogFragment : DialogFragment() { /** * Show error when creating or updating the public share, if any */ - fun showError(genericErrorMessage: String, throwable: Throwable?) { + private fun showError(genericErrorMessage: String, throwable: Throwable?) { public_link_error_message?.text = throwable?.parseError(genericErrorMessage, resources) public_link_error_message?.visibility = View.VISIBLE } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt index d8e9b700b76..4702ffd88dd 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt @@ -44,6 +44,7 @@ import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.domain.utils.Event.EventObserver import com.owncloud.android.extensions.showError import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.status.OwnCloudVersion @@ -58,7 +59,6 @@ import kotlinx.android.synthetic.main.share_file_layout.* import kotlinx.android.synthetic.main.share_file_layout.view.* import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf -import java.util.Collections import java.util.Locale /** @@ -155,7 +155,7 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe if (!isDefaultNameSet) { return defaultName } - Collections.sort(usedNumbers) + usedNumbers.sort() var chosenNumber = -1 if (usedNumbers.size == 0 || usedNumbers[0] != 2) { chosenNumber = 2 @@ -373,7 +373,7 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe private fun observeShares() { ocShareViewModel.shares.observe( this, - Observer { uiResult -> + EventObserver { uiResult -> val shares = uiResult.getStoredData() when (uiResult) { is UIResult.Success -> { @@ -395,12 +395,6 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe updateShares(it) } } - else -> { - Log.d( - TAG, "Unknown status when loading public shares for file ${file?.fileName} in account" + - "${account?.name}" - ) - } } } ) @@ -426,7 +420,7 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe ************************************************ CAPABILITIES ************************************************ **************************************************************************************************************/ - fun updateCapabilities(capabilities: OCCapability?) { + private fun updateCapabilities(capabilities: OCCapability?) { this.capabilities = capabilities updatePublicLinkButton() @@ -464,7 +458,7 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe ) // Show data - if (privateShares!!.size > 0) { + if (!privateShares.isNullOrEmpty()) { shareNoUsers?.visibility = View.GONE shareUsersList?.visibility = View.VISIBLE shareUsersList?.adapter = userGroupsAdapter @@ -505,12 +499,12 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe */ private fun updatePublicLinkButton() { // Since capabilities and publicLinks are loaded asynchronously, let's check whether they both exist - if (capabilities == null || publicLinks == null) { + if (capabilities == null) { return } if (!enableMultiplePublicSharing()) { - if (publicLinks?.isNullOrEmpty() == true) { + if (publicLinks.isNullOrEmpty()) { addPublicLinkButton.visibility = View.VISIBLE return } @@ -609,11 +603,11 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe companion object { private val TAG = ShareFileFragment::class.java.simpleName - private val DEFAULT_NAME_SUFFIX = " (%1\$d)" + private const val DEFAULT_NAME_SUFFIX = " (%1\$d)" - private val QUOTE_START = "\\Q" - private val QUOTE_END = "\\E" - private val DEFAULT_NAME_REGEX_SUFFIX = " \\((\\d+)\\)\\z" + private const val QUOTE_START = "\\Q" + private const val QUOTE_END = "\\E" + private const val DEFAULT_NAME_REGEX_SUFFIX = " \\((\\d+)\\)\\z" // matches suffix (end of the string with \z) in the form "(X)", where X is an integer of any length; // also captures the number to reference it later during the match; // reference in https://developer.android.com/reference/java/util/regex/Pattern.html#sum @@ -621,9 +615,9 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe /** * The fragment initialization parameters */ - private val ARG_FILE = "FILE" - private val ARG_ACCOUNT = "ACCOUNT" - private val ARG_SERVER_VERSION = "SERVER_VERSION" + private const val ARG_FILE = "FILE" + private const val ARG_ACCOUNT = "ACCOUNT" + private const val ARG_SERVER_VERSION = "SERVER_VERSION" /** * Public factory method to create new ShareFileFragment instances. diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt index d56dd5fc2f2..f8ca1c7beb9 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt @@ -34,6 +34,7 @@ import com.owncloud.android.domain.sharing.shares.usecases.EditPublicShareAsyncU import com.owncloud.android.domain.sharing.shares.usecases.GetShareAsLiveDataUseCase import com.owncloud.android.domain.sharing.shares.usecases.GetSharesAsLiveDataUseCase import com.owncloud.android.domain.sharing.shares.usecases.RefreshSharesFromServerAsyncUseCase +import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers @@ -57,19 +58,16 @@ class OCShareViewModel( private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) : ViewModel() { - private val _shares = MediatorLiveData>>() - val shares: LiveData>> = _shares + private val _shares = MediatorLiveData>>>() + val shares: LiveData>>> = _shares private var sharesLiveData: LiveData> = getSharesAsLiveDataUseCase.execute( - GetSharesAsLiveDataUseCase.Params( - filePath = filePath, - accountName = accountName - ) + GetSharesAsLiveDataUseCase.Params(filePath = filePath, accountName = accountName) ) init { _shares.addSource(sharesLiveData) { shares -> - _shares.postValue(UIResult.Success(shares)) + _shares.postValue(Event(UIResult.Success(shares))) } refreshSharesFromNetwork() @@ -77,9 +75,7 @@ class OCShareViewModel( fun refreshSharesFromNetwork() { viewModelScope.launch { - _shares.postValue( - UIResult.Loading(sharesLiveData.value) - ) + _shares.postValue(Event(UIResult.Loading(sharesLiveData.value))) val useCaseResult = withContext(ioDispatcher) { refreshSharesFromServerAsyncUseCase.execute( @@ -92,22 +88,21 @@ class OCShareViewModel( if (!useCaseResult.isSuccess) { _shares.postValue( - UIResult.Error(useCaseResult.getThrowableOrNull(), sharesLiveData?.value) - + Event(UIResult.Error(useCaseResult.getThrowableOrNull(), sharesLiveData.value)) ) } } } - private val _shareDeletionStatus = MutableLiveData>() - val shareDeletionStatus: LiveData> = _shareDeletionStatus + private val _shareDeletionStatus = MutableLiveData>>() + val shareDeletionStatus: LiveData>> = _shareDeletionStatus fun deleteShare( remoteId: Long ) { viewModelScope.launch { _shareDeletionStatus.postValue( - UIResult.Loading() + Event(UIResult.Loading()) ) val useCaseResult = withContext(ioDispatcher) { @@ -120,10 +115,10 @@ class OCShareViewModel( if (!useCaseResult.isSuccess) { _shareDeletionStatus.postValue( - UIResult.Error(useCaseResult.getThrowableOrNull()) + Event(UIResult.Error(useCaseResult.getThrowableOrNull())) ) } else { - _shareDeletionStatus.postValue(UIResult.Success()) + _shareDeletionStatus.postValue(Event(UIResult.Success())) } } } @@ -132,8 +127,8 @@ class OCShareViewModel( ******************************************* PRIVATE SHARES ******************************************* ******************************************************************************************************/ - private val _privateShareCreationStatus = MutableLiveData>() - val privateShareCreationStatus: LiveData> = _privateShareCreationStatus + private val _privateShareCreationStatus = MutableLiveData>>() + val privateShareCreationStatus: LiveData>> = _privateShareCreationStatus fun insertPrivateShare( filePath: String, @@ -144,7 +139,7 @@ class OCShareViewModel( ) { viewModelScope.launch { _privateShareCreationStatus.postValue( - UIResult.Loading() + Event(UIResult.Loading()) ) val useCaseResult = withContext(ioDispatcher) { @@ -161,14 +156,14 @@ class OCShareViewModel( if (!useCaseResult.isSuccess) { _privateShareCreationStatus.postValue( - UIResult.Error(useCaseResult.getThrowableOrNull()) + Event(UIResult.Error(useCaseResult.getThrowableOrNull())) ) } } } - private val _privateShare = MediatorLiveData>() - val privateShare: LiveData> = _privateShare + private val _privateShare = MediatorLiveData>>() + val privateShare: LiveData>> = _privateShare private var privateShareLiveData: LiveData? = null @@ -182,13 +177,13 @@ class OCShareViewModel( privateShareLiveData?.let { _privateShare.addSource(it) { privateShare -> - _privateShare.postValue(UIResult.Success(privateShare)) + _privateShare.postValue(Event(UIResult.Success(privateShare))) } } } - private val _privateShareEditionStatus = MutableLiveData>() - val privateShareEditionStatus: LiveData> = _privateShareEditionStatus + private val _privateShareEditionStatus = MutableLiveData>>() + val privateShareEditionStatus: LiveData>> = _privateShareEditionStatus fun updatePrivateShare( remoteId: Long, @@ -197,7 +192,7 @@ class OCShareViewModel( ) { viewModelScope.launch { _privateShareEditionStatus.postValue( - UIResult.Loading() + Event(UIResult.Loading()) ) val useCaseResult = withContext(ioDispatcher) { @@ -212,10 +207,10 @@ class OCShareViewModel( if (!useCaseResult.isSuccess) { _privateShareEditionStatus.postValue( - UIResult.Error(useCaseResult.getThrowableOrNull()) + Event(UIResult.Error(useCaseResult.getThrowableOrNull())) ) } else { - _privateShareEditionStatus.postValue(UIResult.Success()) + _privateShareEditionStatus.postValue(Event(UIResult.Success())) } } } @@ -224,8 +219,8 @@ class OCShareViewModel( ******************************************* PUBLIC SHARES ******************************************** ******************************************************************************************************/ - private val _publicShareCreationStatus = MutableLiveData>() - val publicShareCreationStatus: LiveData> = _publicShareCreationStatus + private val _publicShareCreationStatus = MutableLiveData>>() + val publicShareCreationStatus: LiveData>> = _publicShareCreationStatus fun insertPublicShare( filePath: String, @@ -238,7 +233,7 @@ class OCShareViewModel( ) { viewModelScope.launch { _publicShareCreationStatus.postValue( - UIResult.Loading() + Event(UIResult.Loading()) ) val useCaseResult = withContext(ioDispatcher) { @@ -257,16 +252,16 @@ class OCShareViewModel( if (!useCaseResult.isSuccess) { _publicShareCreationStatus.postValue( - UIResult.Error(useCaseResult.getThrowableOrNull()) + Event(UIResult.Error(useCaseResult.getThrowableOrNull())) ) } else { - _publicShareCreationStatus.postValue(UIResult.Success()) + _publicShareCreationStatus.postValue(Event(UIResult.Success())) } } } - private val _publicShareEditionStatus = MutableLiveData>() - val publicShareEditionStatus: LiveData> = _publicShareEditionStatus + private val _publicShareEditionStatus = MutableLiveData>>() + val publicShareEditionStatus: LiveData>> = _publicShareEditionStatus fun updatePublicShare( remoteId: Long, @@ -279,7 +274,7 @@ class OCShareViewModel( ) { viewModelScope.launch { _publicShareEditionStatus.postValue( - UIResult.Loading() + Event(UIResult.Loading()) ) val useCaseResult = withContext(ioDispatcher) { @@ -298,10 +293,10 @@ class OCShareViewModel( if (!useCaseResult.isSuccess) { _publicShareEditionStatus.postValue( - UIResult.Error(useCaseResult.getThrowableOrNull()) + Event(UIResult.Error(useCaseResult.getThrowableOrNull())) ) } else { - _publicShareEditionStatus.postValue(UIResult.Success()) + _publicShareEditionStatus.postValue(Event(UIResult.Success())) } } } diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/utils/Event.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/utils/Event.kt new file mode 100644 index 00000000000..4c41939df00 --- /dev/null +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/utils/Event.kt @@ -0,0 +1,59 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.owncloud.android.domain.utils + +import androidx.lifecycle.Observer + +/** + * Used as a wrapper for data that is exposed via a LiveData that represents an event. + */ +data class Event(private val content: T) { + + var hasBeenHandled = false + private set // Allow external read but not write + + /** + * Returns the content and prevents its use again. + */ + fun getContentIfNotHandled(): T? { + return if (hasBeenHandled) { + null + } else { + hasBeenHandled = true + content + } + } + + /** + * Returns the content, even if it's already been handled. + */ + fun peekContent(): T = content + + /** + * An [Observer] for [Event]s, simplifying the pattern of checking if the [Event]'s content has + * already been handled. + * + * [onEventUnhandledContent] is *only* called if the [Event]'s contents has not been handled. + */ + class EventObserver(private val onEventUnhandledContent: (T) -> Unit) : Observer> { + override fun onChanged(event: Event?) { + event?.getContentIfNotHandled()?.let { value -> + onEventUnhandledContent(value) + } + } + } +} From 102c56a248b1cba7ddcfa727779eea4717741b6a Mon Sep 17 00:00:00 2001 From: davigonz Date: Wed, 20 Nov 2019 18:25:39 +0100 Subject: [PATCH 22/41] Fix double notification error after screen rotation --- .../presentation/ui/sharing/ShareActivity.kt | 8 ++++---- .../fragments/PublicShareDialogFragment.kt | 3 +-- .../sharing/fragments/SearchShareesFragment.kt | 5 ++--- .../ui/sharing/fragments/ShareFileFragment.kt | 18 ++++++++++-------- .../capabilities/OCCapabilityViewModel.kt | 11 ++++++----- 5 files changed, 23 insertions(+), 22 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/ShareActivity.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/ShareActivity.kt index 823266795a7..3abedab0c13 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/ShareActivity.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/ShareActivity.kt @@ -29,11 +29,11 @@ import android.content.Intent import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.transaction -import androidx.lifecycle.Observer import com.owncloud.android.R import com.owncloud.android.datamodel.OCFile import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.domain.utils.Event.EventObserver import com.owncloud.android.extensions.showError import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.shares.RemoteShare @@ -137,7 +137,7 @@ class ShareActivity : FileActivity(), ShareFragmentListener { private fun observePrivateShareCreation() { ocShareViewModel.privateShareCreationStatus.observe( this, - Observer { uiResult -> + EventObserver { uiResult -> when (uiResult) { is UIResult.Error -> { showError(getString(R.string.share_link_file_error), uiResult.error) @@ -181,7 +181,7 @@ class ShareActivity : FileActivity(), ShareFragmentListener { private fun observePrivateShareEdition() { ocShareViewModel.privateShareEditionStatus.observe( this, - Observer { uiResult -> + EventObserver { uiResult -> when (uiResult) { is UIResult.Error -> { showError(getString(R.string.share_link_file_error), uiResult.error) @@ -253,7 +253,7 @@ class ShareActivity : FileActivity(), ShareFragmentListener { private fun observeShareDeletion() { ocShareViewModel.shareDeletionStatus.observe( this, - Observer { uiResult -> + EventObserver { uiResult -> when (uiResult) { is UIResult.Error -> { dismissLoadingDialog() diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt index dcf5dfc2f36..85e70f26fdb 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt @@ -37,7 +37,6 @@ import android.widget.TextView import androidx.appcompat.widget.SwitchCompat import androidx.core.view.isGone import androidx.fragment.app.DialogFragment -import androidx.lifecycle.Observer import com.owncloud.android.R import com.owncloud.android.datamodel.OCFile import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType @@ -448,7 +447,7 @@ class PublicShareDialogFragment : DialogFragment() { private fun observeCapabilities() { ocCapabilityViewModel.capabilities.observe( this, - Observer { uiResult -> + EventObserver { uiResult -> when (uiResult) { is UIResult.Success -> { updateCapabilities(uiResult.data) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/SearchShareesFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/SearchShareesFragment.kt index b4be0af6843..5d04aeee985 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/SearchShareesFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/SearchShareesFragment.kt @@ -30,7 +30,6 @@ import android.accounts.Account import android.app.SearchManager import android.content.Context import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -40,11 +39,11 @@ import android.widget.ListView import androidx.appcompat.widget.SearchView import androidx.core.os.bundleOf import androidx.fragment.app.Fragment -import androidx.lifecycle.Observer import com.owncloud.android.R import com.owncloud.android.datamodel.OCFile import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.domain.utils.Event import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.adapters.sharing.ShareUserListAdapter @@ -147,7 +146,7 @@ class SearchShareesFragment : Fragment(), private fun observePrivateShares() { ocShareViewModel.shares.observe( this, - Observer { uiResult -> + Event.EventObserver { uiResult -> val privateShares = uiResult.getStoredData()?.filter { share -> share.shareType == ShareType.USER || share.shareType == ShareType.GROUP || diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt index 4702ffd88dd..76d8944ef3d 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt @@ -44,7 +44,6 @@ import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType -import com.owncloud.android.domain.utils.Event.EventObserver import com.owncloud.android.extensions.showError import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.status.OwnCloudVersion @@ -318,9 +317,6 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe observeCapabilities() // Get capabilities to update some UI elements depending on them observeShares() - - ocCapabilityViewModel.refreshCapabilitiesFromNetwork() - ocShareViewModel.refreshSharesFromNetwork() } override fun onAttach(context: Context) { @@ -340,7 +336,8 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe private fun observeCapabilities() { ocCapabilityViewModel.capabilities.observe( this, - Observer { uiResult -> + Observer { event -> + val uiResult = event.peekContent() val capabilities = uiResult.getStoredData() when (uiResult) { is UIResult.Success -> { @@ -353,7 +350,9 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe capabilities?.let { updateCapabilities(it) } - showError(getString(R.string.get_capabilities_error), uiResult.error) + event.getContentIfNotHandled()?.let { + showError(getString(R.string.get_capabilities_error), uiResult.error) + } listener?.dismissLoading() } is UIResult.Loading -> { @@ -373,7 +372,8 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe private fun observeShares() { ocShareViewModel.shares.observe( this, - EventObserver { uiResult -> + Observer { event -> + val uiResult = event.peekContent() val shares = uiResult.getStoredData() when (uiResult) { is UIResult.Success -> { @@ -386,7 +386,9 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe shares?.let { updateShares(it) } - showError(getString(R.string.get_shares_error), uiResult.error) + event.getContentIfNotHandled()?.let { + showError(getString(R.string.get_shares_error), uiResult.error) + } listener?.dismissLoading() } is UIResult.Loading -> { diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt index 87b34de42ff..c0fdb98f886 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt @@ -28,6 +28,7 @@ import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.capabilities.usecases.GetCapabilitiesAsLiveDataUseCase import com.owncloud.android.domain.capabilities.usecases.GetStoredCapabilitiesUseCase import com.owncloud.android.domain.capabilities.usecases.RefreshCapabilitiesFromServerAsyncUseCase +import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers @@ -45,8 +46,8 @@ class OCCapabilityViewModel( private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) : ViewModel() { - private val _capabilities = MediatorLiveData>() - val capabilities: LiveData> = _capabilities + private val _capabilities = MediatorLiveData>>() + val capabilities: LiveData>> = _capabilities private var capabilitiesLiveData: LiveData? = getCapabilitiesAsLiveDataUseCase.execute( GetCapabilitiesAsLiveDataUseCase.Params( @@ -56,7 +57,7 @@ class OCCapabilityViewModel( init { _capabilities.addSource(capabilitiesLiveData!!) { capabilities -> - _capabilities.postValue(UIResult.Success(capabilities)) + _capabilities.postValue(Event(UIResult.Success(capabilities))) } refreshCapabilitiesFromNetwork() @@ -71,7 +72,7 @@ class OCCapabilityViewModel( fun refreshCapabilitiesFromNetwork() { viewModelScope.launch { _capabilities.postValue( - UIResult.Loading(capabilitiesLiveData?.value) + Event(UIResult.Loading(capabilitiesLiveData?.value)) ) val useCaseResult = withContext(ioDispatcher) { @@ -84,7 +85,7 @@ class OCCapabilityViewModel( if (useCaseResult.isError) { _capabilities.postValue( - UIResult.Error(useCaseResult.getThrowableOrNull(), capabilitiesLiveData?.value) + Event(UIResult.Error(useCaseResult.getThrowableOrNull(), capabilitiesLiveData?.value)) ) } } From 2da5d07e046304e3d5bfb2021885801dcaac7612 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Thu, 21 Nov 2019 09:54:02 +0100 Subject: [PATCH 23/41] Moving testutils to new module --- build.gradle | 1 + owncloudApp/build.gradle | 2 +- .../viewmodels/OCCapabilityViewModelTest.kt | 13 +-- .../android/database/MigrationTest.kt | 39 ++++---- .../sharees/ui/SearchShareesFragmentTest.kt | 8 +- .../viewmodels/OCShareeViewmodelTest.kt | 89 ------------------- .../shares/ui/EditPrivateShareFragmentTest.kt | 16 ++-- .../PublicShareCreationDialogFragmentTest.kt | 54 +++++------ .../PublicShareEditionDialogFragmentTest.kt | 38 ++++---- .../shares/ui/ShareFileFragmentTest.kt | 52 +++++------ .../shares/ui/ShareFolderFragmentTest.kt | 18 ++-- .../shares/viewmodels/OCShareViewModelTest.kt | 43 ++++----- .../com/owncloud/android/utils/AppTestUtil.kt | 75 +--------------- .../android/utils/LiveDataTestUtil.kt | 52 ----------- .../owncloud/android/utils/ViewModelUtil.kt | 37 -------- .../ui/sharing/fragments/ShareFileFragment.kt | 3 - .../android/data/utils/DataTestUtil.kt | 54 ----------- .../mapper/OCRemoteCapabilityMapperTest.kt | 4 +- .../mapper/OCRemoteShareMapperTest.kt | 4 +- .../android/domain/utils/DomainTestUtil.kt | 86 ------------------ .../GetCapabilitiesAsLiveDataUseCaseTest.kt | 4 +- .../usecases/GetShareAsLiveDataUseCaseTest.kt | 5 +- .../GetSharesAsLiveDataUseCaseTest.kt | 5 +- owncloudTestUtil/build.gradle | 1 + .../owncloud/android/testutil/OCAccount.kt | 7 ++ .../com/owncloud/android/testutil/OCShare.kt | 24 +++++ .../android/testutil/livedata/LiveData.kt | 48 ++++++++++ .../livedata}/TestTimeOutConstants.kt | 2 +- 28 files changed, 230 insertions(+), 554 deletions(-) delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/utils/LiveDataTestUtil.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/utils/ViewModelUtil.kt delete mode 100644 owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/DomainTestUtil.kt create mode 100644 owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt create mode 100644 owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveData.kt rename {owncloudApp/src/androidTest/java/com/owncloud/android/utils => owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata}/TestTimeOutConstants.kt (94%) diff --git a/build.gradle b/build.gradle index fabbba73020..b1eec5201e0 100644 --- a/build.gradle +++ b/build.gradle @@ -31,6 +31,7 @@ buildscript { ktxCoreVersion = "1.1.0" ktxViewModelVersion = "2.2.0-alpha01" ktxFragmentVersion = "1.0.0" + ktxLiveData = "2.1.0" } repositories { diff --git a/owncloudApp/build.gradle b/owncloudApp/build.gradle index 057ead71aca..2a7c193bd1b 100644 --- a/owncloudApp/build.gradle +++ b/owncloudApp/build.gradle @@ -11,7 +11,7 @@ dependencies { /// data and domain modules implementation project(':owncloudDomain') implementation project(':owncloudData') - testImplementation project(':owncloudTestUtil') + androidTestImplementation project(':owncloudTestUtil') /// dependencies for app building implementation "androidx.legacy:legacy-support-v4:$androidX" diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt index 2770879705d..ee5a0643da8 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt @@ -18,7 +18,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.capabilities.viewmodel +package com.owncloud.android.capabilities.viewmodels import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule @@ -27,11 +27,12 @@ import com.owncloud.android.domain.UseCaseResult import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.capabilities.usecases.GetStoredCapabilitiesUseCase import com.owncloud.android.domain.capabilities.usecases.RefreshCapabilitiesFromServerAsyncUseCase -import com.owncloud.android.domain.utils.DomainTestUtil.DUMMY_CAPABILITY import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel -import com.owncloud.android.utils.AppTestUtil -import com.owncloud.android.utils.TIMEOUT_TEST_LONG +import com.owncloud.android.testutil.OC_ACCOUNT +import com.owncloud.android.testutil.OC_CAPABILITY +import com.owncloud.android.testutil.livedata.TIMEOUT_TEST_LONG +import com.owncloud.android.testutil.livedata.getOrAwaitValues import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every @@ -55,7 +56,7 @@ class OCCapabilityViewModelTest { private val capabilityLiveData = MutableLiveData() - private var testAccount: Account = AppTestUtil.createAccount("admin@server", "test") + private var testAccount: Account = OC_ACCOUNT @Rule @JvmField @@ -83,7 +84,7 @@ class OCCapabilityViewModelTest { fun getStoredCapabilitiesWithData() { initTest() - val capability = DUMMY_CAPABILITY.copy(accountName = testAccount.name) + val capability = OC_CAPABILITY.copy(accountName = testAccount.name) getStoredCapabilitiesVerification( valueToTest = capability, diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/database/MigrationTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/database/MigrationTest.kt index aa5a4e5e70d..aca4c19125d 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/database/MigrationTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/database/MigrationTest.kt @@ -29,7 +29,7 @@ import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry -import com.owncloud.android.db.OwncloudDatabase +import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.db.ProviderMeta.ProviderTableMeta import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL @@ -37,6 +37,7 @@ import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_SHARI import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MAYOR import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MICRO import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MINOR +import com.owncloud.android.testutil.OC_CAPABILITY import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Rule @@ -75,7 +76,7 @@ class MigrationTest { // Verify that the data is correct val dbCapability = - getMigratedRoomDatabase().capabilityDao().getCapabilityForAccount(cv.getAsString(CAPABILITIES_ACCOUNT_NAME)) + getMigratedRoomDatabase().capabilityDao().getCapabilitiesForAccount(OC_CAPABILITY.accountName!!) assertEquals(dbCapability.accountName, cv.getAsString(CAPABILITIES_ACCOUNT_NAME)) assertEquals(dbCapability.versionMayor, cv.getAsInteger(CAPABILITIES_VERSION_MAYOR)) assertEquals(dbCapability.versionMinor, cv.getAsInteger(CAPABILITIES_VERSION_MINOR)) @@ -113,7 +114,7 @@ class MigrationTest { // MigrationTestHelper automatically verifies the schema changes. // Verify that the data was migrated properly. val dbCapability = - getMigratedRoomDatabase().capabilityDao().getCapabilityForAccount(cv.getAsString(CAPABILITIES_ACCOUNT_NAME)) + getMigratedRoomDatabase().capabilityDao().getCapabilitiesForAccount(OC_CAPABILITY.accountName!!) assertEquals(dbCapability.accountName, cv.getAsString(CAPABILITIES_ACCOUNT_NAME)) assertEquals(dbCapability.versionMayor, cv.getAsInteger(CAPABILITIES_VERSION_MAYOR)) assertEquals(dbCapability.versionMinor, cv.getAsInteger(CAPABILITIES_VERSION_MINOR)) @@ -139,17 +140,13 @@ class MigrationTest { close() } - val dbCapability = - getMigratedRoomDatabase().capabilityDao().getCapabilityForAccount(cv.getAsString(CAPABILITIES_ACCOUNT_NAME)) - assertEquals(dbCapability.accountName, cv.getAsString(CAPABILITIES_ACCOUNT_NAME)) - assertEquals(dbCapability.versionMayor, cv.getAsInteger(CAPABILITIES_VERSION_MAYOR)) - assertEquals(dbCapability.versionMinor, cv.getAsInteger(CAPABILITIES_VERSION_MINOR)) - assertEquals(dbCapability.versionMicro, cv.getAsInteger(CAPABILITIES_VERSION_MICRO)) - assertEquals(dbCapability.corePollInterval, cv.getAsInteger(CAPABILITIES_CORE_POLLINTERVAL)) - assertEquals( - dbCapability.filesSharingPublicExpireDateDays, - cv.getAsInteger(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS) - ) + val dbCapability = getMigratedRoomDatabase().capabilityDao().getCapabilitiesForAccount(OC_CAPABILITY.accountName!!) + assertEquals(OC_CAPABILITY.accountName, dbCapability.accountName) + assertEquals(OC_CAPABILITY.versionMayor, dbCapability.versionMayor) + assertEquals(OC_CAPABILITY.versionMinor, dbCapability.versionMinor) + assertEquals(OC_CAPABILITY.versionMicro, dbCapability.versionMicro) + assertEquals(OC_CAPABILITY.corePollInterval, dbCapability.corePollInterval) + assertEquals(OC_CAPABILITY.filesSharingPublicExpireDateDays, dbCapability.filesSharingPublicExpireDateDays) } private fun getMigratedRoomDatabase(): OwncloudDatabase { @@ -173,15 +170,13 @@ class MigrationTest { // Added a new capability: "search_min_length" private const val DB_VERSION_28 = 28 - //TODO: Consider adding a DUMMY_CAPABILITY full of values available for testing - // to avoid including values hardcoded in each test private val cv = ContentValues().apply { - put(CAPABILITIES_ACCOUNT_NAME, "user1@server") - put(CAPABILITIES_VERSION_MAYOR, 3) - put(CAPABILITIES_VERSION_MINOR, 2) - put(CAPABILITIES_VERSION_MICRO, 1) - put(CAPABILITIES_CORE_POLLINTERVAL, 60) - put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS, 0) + put(CAPABILITIES_ACCOUNT_NAME, OC_CAPABILITY.accountName) + put(CAPABILITIES_VERSION_MAYOR, OC_CAPABILITY.versionMayor) + put(CAPABILITIES_VERSION_MINOR, OC_CAPABILITY.versionMinor) + put(CAPABILITIES_VERSION_MICRO, OC_CAPABILITY.versionMicro) + put(CAPABILITIES_CORE_POLLINTERVAL, OC_CAPABILITY.corePollInterval) + put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS, OC_CAPABILITY.filesSharingPublicExpireDateDays) } } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt index b42ef58c760..a7a1a25b611 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt @@ -38,7 +38,7 @@ import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.SearchShareesFragment import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel import com.owncloud.android.sharing.shares.ui.TestShareFileActivity -import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE +import com.owncloud.android.testutil.OC_SHARE import io.mockk.every import io.mockk.mockk import org.hamcrest.CoreMatchers @@ -89,8 +89,8 @@ class SearchShareesFragmentTest { Event( UIResult.Success( listOf( - DUMMY_SHARE.copy(sharedWithDisplayName = "Sheldon"), - DUMMY_SHARE.copy(sharedWithDisplayName = "Penny") + OC_SHARE.copy(sharedWithDisplayName = "Sheldon"), + OC_SHARE.copy(sharedWithDisplayName = "Penny") ) ) ) @@ -110,7 +110,7 @@ class SearchShareesFragmentTest { Event( UIResult.Success( listOf( - DUMMY_SHARE.copy( + OC_SHARE.copy( shareType = ShareType.GROUP, sharedWithDisplayName = "Friends" ) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt deleted file mode 100644 index 8d42d5691f0..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/viewmodels/OCShareeViewmodelTest.kt +++ /dev/null @@ -1,89 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.presentation.sharing.sharees.viewmodels - -import android.accounts.Account -import androidx.arch.core.executor.testing.InstantTaskExecutorRule -import androidx.test.platform.app.InstrumentationRegistry -import com.owncloud.android.data.sharing.sharees.repository.OCShareeRepository -import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation -import com.owncloud.android.utils.AppTestUtil -import io.mockk.every -import io.mockk.mockkClass -import junit.framework.Assert.assertEquals -import org.json.JSONObject -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.junit.runners.JUnit4 - -@RunWith(JUnit4::class) -class OCShareeViewmodelTest { - @Rule - @JvmField - val instantExecutorRule = InstantTaskExecutorRule() - - private var testAccount: Account = AppTestUtil.createAccount("admin@server", "test") - private var ocShareeRepository: OCShareeRepository = mockkClass( - OCShareeRepository::class) - - @Test - fun loadSharees() { - val sharees = arrayListOf( - AppTestUtil.createSharee("User", ShareType.USER.value.toString(), "user", "user@mail.com"), - AppTestUtil.createSharee("Group", ShareType.GROUP.value.toString(), "user2", "user2@mail.com") - ) - - every { - ocShareeRepository.getSharees( - "User", 1, 10 - ) - } returns DataResult.success(sharees) - - val ocShareeViewModel = createOCShareeViewModel(ocShareeRepository) - - val data: ArrayList? = ocShareeViewModel.getSharees("User", 1, 10).data - - assertEquals(2, data?.size) - - val sharee1 = data?.get(0) - assertEquals(sharee1?.getString(GetRemoteShareesOperation.PROPERTY_LABEL), "User") - val value = sharee1?.getJSONObject(GetRemoteShareesOperation.NODE_VALUE) - assertEquals(value?.getString(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE), ShareType.USER.value.toString()) - assertEquals(value?.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH), "user") - assertEquals(value?.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO), "user@mail.com") - - val sharee2 = data?.get(1) - assertEquals(sharee2?.getString(GetRemoteShareesOperation.PROPERTY_LABEL), "Group") - val value2 = sharee2?.getJSONObject(GetRemoteShareesOperation.NODE_VALUE) - assertEquals(value2?.getString(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE), ShareType.GROUP.value.toString()) - assertEquals(value2?.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH), "user2") - assertEquals(value2?.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO), "user2@mail.com") - } - - private fun createOCShareeViewModel(ocShareeRepository: OCShareeRepository): OCShareeViewModel { - val context = InstrumentationRegistry.getInstrumentation().targetContext - return OCShareeViewModel( - context, - testAccount, - ocShareeRepository - ) - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt index 8925234b395..284d060d6b3 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt @@ -39,10 +39,10 @@ import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.EditPrivateShareFragment import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT -import com.owncloud.android.utils.AppTestUtil.DUMMY_FILE -import com.owncloud.android.utils.AppTestUtil.DUMMY_FOLDER -import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE +import com.owncloud.android.testutil.OC_ACCOUNT +import com.owncloud.android.testutil.OC_SHARE +import com.owncloud.android.utils.AppTestUtil.OC_FILE +import com.owncloud.android.utils.AppTestUtil.OC_FOLDER import com.owncloud.android.utils.Permissions import io.mockk.every import io.mockk.mockk @@ -236,17 +236,17 @@ class EditPrivateShareFragmentTest { isFolder: Boolean = false, permissions: Int = Permissions.READ_PERMISSIONS.value ) { - val shareToEdit = DUMMY_SHARE.copy( + val shareToEdit = OC_SHARE.copy( sharedWithDisplayName = defaultSharedWithDisplayName, permissions = permissions ) - val sharedFile = if (isFolder) DUMMY_FOLDER else DUMMY_FILE + val sharedFile = if (isFolder) OC_FOLDER else OC_FILE val editPrivateShareFragment = EditPrivateShareFragment.newInstance( shareToEdit, sharedFile, - DUMMY_ACCOUNT + OC_ACCOUNT ) ActivityScenario.launch(TestShareFileActivity::class.java).onActivity { @@ -256,7 +256,7 @@ class EditPrivateShareFragmentTest { privateShareAsLiveData.postValue( Event( UIResult.Success( - DUMMY_SHARE.copy( + OC_SHARE.copy( shareWith = "user", sharedWithDisplayName = "User", path = "/Videos", diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt index 56fbc2ecd4d..dffcfae78e8 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareCreationDialogFragmentTest.kt @@ -45,10 +45,10 @@ import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.PublicShareDialogFragment import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT -import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY -import com.owncloud.android.utils.AppTestUtil.DUMMY_FILE -import com.owncloud.android.utils.AppTestUtil.DUMMY_FOLDER +import com.owncloud.android.testutil.OC_ACCOUNT +import com.owncloud.android.testutil.OC_CAPABILITY +import com.owncloud.android.utils.AppTestUtil.OC_FILE +import com.owncloud.android.utils.AppTestUtil.OC_FOLDER import com.owncloud.android.utils.DateUtils import io.mockk.every import io.mockk.mockk @@ -65,7 +65,7 @@ import java.util.Date class PublicShareCreationDialogFragmentTest { private val ocCapabilityViewModel = mockk(relaxed = true) - private val capabilitiesLiveData = MutableLiveData>() + private val capabilitiesLiveData = MutableLiveData>>() private val ocShareViewModel = mockk(relaxed = true) private val publicShareCreationStatus = MutableLiveData>>() @@ -116,7 +116,7 @@ class PublicShareCreationDialogFragmentTest { fun showFolderAdditionalFields() { loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.0.1", filesSharingPublicUpload = CapabilityBooleanType.TRUE, filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE @@ -155,7 +155,7 @@ class PublicShareCreationDialogFragmentTest { @Test fun checkPasswordEnforced() { loadPublicShareDialogFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( filesSharingPublicPasswordEnforced = CapabilityBooleanType.TRUE ) ) @@ -171,7 +171,7 @@ class PublicShareCreationDialogFragmentTest { @Test fun checkExpireDateEnforced() { loadPublicShareDialogFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( filesSharingPublicExpireDateEnforced = CapabilityBooleanType.TRUE ) ) @@ -186,7 +186,7 @@ class PublicShareCreationDialogFragmentTest { @Test fun checkExpireDateNotEnforced() { loadPublicShareDialogFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( filesSharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE ) ) @@ -212,7 +212,7 @@ class PublicShareCreationDialogFragmentTest { fun cancelExpirationSwitch() { loadPublicShareDialogFragment() onView(withId(R.id.shareViaLinkExpirationSwitch)).perform(click()) - onView(withId(android.R.id.button2)).perform(click()); + onView(withId(android.R.id.button2)).perform(click()) onView(withId(R.id.shareViaLinkExpirationValue)) .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.INVISIBLE))) } @@ -243,7 +243,7 @@ class PublicShareCreationDialogFragmentTest { fun uploadPermissionsWithFolderDisplayed() { loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, filesSharingPublicUpload = CapabilityBooleanType.TRUE @@ -257,7 +257,7 @@ class PublicShareCreationDialogFragmentTest { fun uploadPermissionsWithFolderNotDisplayed() { loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, filesSharingPublicUpload = CapabilityBooleanType.FALSE @@ -271,7 +271,7 @@ class PublicShareCreationDialogFragmentTest { fun expirationDateDays() { val daysToTest = 15 loadPublicShareDialogFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicExpireDateDays = daysToTest ) @@ -291,7 +291,7 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordNotEnforced() { loadPublicShareDialogFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE ) @@ -303,7 +303,7 @@ class PublicShareCreationDialogFragmentTest { @Test fun passwordEnforced() { loadPublicShareDialogFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicPasswordEnforced = CapabilityBooleanType.TRUE ) @@ -316,7 +316,7 @@ class PublicShareCreationDialogFragmentTest { fun passwordEnforcedReadOnlyFolders() { loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, filesSharingPublicUpload = CapabilityBooleanType.TRUE, @@ -334,7 +334,7 @@ class PublicShareCreationDialogFragmentTest { fun passwordNotEnforcedReadOnlyFolders() { loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, filesSharingPublicUpload = CapabilityBooleanType.TRUE, @@ -352,7 +352,7 @@ class PublicShareCreationDialogFragmentTest { fun passwordEnforcedReadWriteFolders() { loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, filesSharingPublicUpload = CapabilityBooleanType.TRUE, @@ -370,7 +370,7 @@ class PublicShareCreationDialogFragmentTest { fun passwordNotEnforcedReadWriteFolders() { loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, filesSharingPublicUpload = CapabilityBooleanType.TRUE, @@ -388,7 +388,7 @@ class PublicShareCreationDialogFragmentTest { fun passwordEnforcedUploadOnlyFolders() { loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, filesSharingPublicUpload = CapabilityBooleanType.TRUE, @@ -406,7 +406,7 @@ class PublicShareCreationDialogFragmentTest { fun passwordNotEnforcedUploadOnlyFolders() { loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, filesSharingPublicUpload = CapabilityBooleanType.TRUE, @@ -428,7 +428,7 @@ class PublicShareCreationDialogFragmentTest { //to a non-forced one loadPublicShareDialogFragment( isFolder = true, - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.TRUE, filesSharingPublicUpload = CapabilityBooleanType.TRUE, @@ -457,13 +457,13 @@ class PublicShareCreationDialogFragmentTest { private fun loadPublicShareDialogFragment( isFolder: Boolean = false, - capabilities: OCCapability = DUMMY_CAPABILITY + capabilities: OCCapability = OC_CAPABILITY ) { - val file = if (isFolder) DUMMY_FOLDER else DUMMY_FILE + val file = if (isFolder) OC_FOLDER else OC_FILE val publicShareDialogFragment = PublicShareDialogFragment.newInstanceToCreate( file, - DUMMY_ACCOUNT, + OC_ACCOUNT, "DOC_12112018.jpg link" ) @@ -471,10 +471,10 @@ class PublicShareCreationDialogFragmentTest { it.startFragment(publicShareDialogFragment) } - capabilitiesLiveData.postValue( + capabilitiesLiveData.postValue(Event( UIResult.Success( capabilities - ) + )) ) } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt index 5b3d4526760..50633bfaf6d 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt @@ -27,6 +27,7 @@ import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.isChecked +import androidx.test.espresso.matcher.ViewMatchers.Visibility.VISIBLE import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility import androidx.test.espresso.matcher.ViewMatchers.withHint import androidx.test.espresso.matcher.ViewMatchers.withId @@ -35,14 +36,15 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import com.owncloud.android.R import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.domain.utils.Event import com.owncloud.android.lib.resources.shares.RemoteShare import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.PublicShareDialogFragment import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT -import com.owncloud.android.utils.AppTestUtil.DUMMY_FILE -import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE +import com.owncloud.android.testutil.OC_ACCOUNT +import com.owncloud.android.testutil.OC_SHARE +import com.owncloud.android.utils.AppTestUtil.OC_FILE import io.mockk.every import io.mockk.mockk import org.junit.Before @@ -61,7 +63,7 @@ import java.util.TimeZone @RunWith(AndroidJUnit4::class) class PublicShareEditionDialogFragmentTest { private val ocCapabilityViewModel = mockk(relaxed = true) - private val capabilitiesLiveData = MutableLiveData>() + private val capabilitiesLiveData = MutableLiveData>>() private val ocShareViewModel = mockk(relaxed = true) private val expirationDate = 1556575200000 // GMT: Monday, April 29, 2019 10:00:00 PM @@ -71,9 +73,9 @@ class PublicShareEditionDialogFragmentTest { every { ocCapabilityViewModel.capabilities } returns capabilitiesLiveData val publicShareDialogFragment = PublicShareDialogFragment.newInstanceToUpdate( - DUMMY_FILE, - DUMMY_ACCOUNT, - DUMMY_SHARE.copy( + OC_FILE, + OC_ACCOUNT, + OC_SHARE.copy( shareType = ShareType.PUBLIC_LINK, shareWith = "user", name = "Docs link", @@ -123,12 +125,9 @@ class PublicShareEditionDialogFragmentTest { @Test fun checkPasswordSet() { onView(withId(R.id.shareViaLinkPasswordLabel)).check(matches(withText(R.string.share_via_link_password_label))) - onView(withId(R.id.shareViaLinkPasswordSwitch)) - .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE))) - onView(withId(R.id.shareViaLinkPasswordValue)) - .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE))) - onView(withId(R.id.shareViaLinkPasswordValue)) - .check(matches(withHint(R.string.share_via_link_default_password))) + onView(withId(R.id.shareViaLinkPasswordSwitch)).check(matches(withEffectiveVisibility(VISIBLE))) + onView(withId(R.id.shareViaLinkPasswordValue)).check(matches(withEffectiveVisibility(VISIBLE))) + onView(withId(R.id.shareViaLinkPasswordValue)).check(matches(withHint(R.string.share_via_link_default_password))) } @Test @@ -141,14 +140,9 @@ class PublicShareEditionDialogFragmentTest { val time = formatter.format(calendar.time) - onView(withId(R.id.shareViaLinkExpirationLabel)).check( - matches(withText(R.string.share_via_link_expiration_date_label)) - ) - onView(withId(R.id.shareViaLinkExpirationSwitch)) - .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE))) - onView(withId(R.id.shareViaLinkExpirationValue)) - .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE))) - onView(withId(R.id.shareViaLinkExpirationValue)) - .check(matches(withText(time))) + onView(withId(R.id.shareViaLinkExpirationLabel)).check(matches(withText(R.string.share_via_link_expiration_date_label))) + onView(withId(R.id.shareViaLinkExpirationSwitch)).check(matches(withEffectiveVisibility(VISIBLE))) + onView(withId(R.id.shareViaLinkExpirationValue)).check(matches(withEffectiveVisibility(VISIBLE))) + onView(withId(R.id.shareViaLinkExpirationValue)).check(matches(withText(time))) } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt index 6b3a9b54a9e..d4fe0eec6f5 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt @@ -43,10 +43,10 @@ import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.ShareFileFragment import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT -import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY -import com.owncloud.android.utils.AppTestUtil.DUMMY_FILE -import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE +import com.owncloud.android.testutil.OC_ACCOUNT +import com.owncloud.android.testutil.OC_CAPABILITY +import com.owncloud.android.testutil.OC_SHARE +import com.owncloud.android.utils.AppTestUtil.OC_FILE import io.mockk.every import io.mockk.mockk import io.mockk.mockkClass @@ -61,7 +61,7 @@ import org.koin.dsl.module class ShareFileFragmentTest { private val ocCapabilityViewModel = mockk(relaxed = true) - private val capabilitiesLiveData = MutableLiveData>() + private val capabilitiesLiveData = MutableLiveData>>() private val ocShareViewModel = mockk(relaxed = true) private val sharesLiveData = MutableLiveData>>>() @@ -110,20 +110,16 @@ class ShareFileFragmentTest { ******************************************************************************************************/ private var userSharesList = listOf( - DUMMY_SHARE.copy( - sharedWithDisplayName = "Batman" - ), - DUMMY_SHARE.copy( - sharedWithDisplayName = "Jocker" - ) + OC_SHARE.copy(sharedWithDisplayName = "Batman"), + OC_SHARE.copy(sharedWithDisplayName = "Jocker") ) private var groupSharesList = listOf( - DUMMY_SHARE.copy( + OC_SHARE.copy( shareType = ShareType.GROUP, sharedWithDisplayName = "Suicide Squad" ), - DUMMY_SHARE.copy( + OC_SHARE.copy( shareType = ShareType.GROUP, sharedWithDisplayName = "Avengers" ) @@ -166,21 +162,21 @@ class ShareFileFragmentTest { ******************************************************************************************************/ private var publicShareList = listOf( - DUMMY_SHARE.copy( + OC_SHARE.copy( shareType = ShareType.PUBLIC_LINK, path = "/Photos/image.jpg", isFolder = false, name = "Image link", shareLink = "http://server:port/s/1" ), - DUMMY_SHARE.copy( + OC_SHARE.copy( shareType = ShareType.PUBLIC_LINK, path = "/Photos/image.jpg", isFolder = false, name = "Image link 2", shareLink = "http://server:port/s/2" ), - DUMMY_SHARE.copy( + OC_SHARE.copy( shareType = ShareType.PUBLIC_LINK, path = "/Photos/image.jpg", isFolder = false, @@ -212,7 +208,7 @@ class ShareFileFragmentTest { @Test fun showPublicSharesSharingEnabled() { loadShareFileFragment( - capabilities = DUMMY_CAPABILITY.copy(filesSharingPublicEnabled = CapabilityBooleanType.TRUE), + capabilities = OC_CAPABILITY.copy(filesSharingPublicEnabled = CapabilityBooleanType.TRUE), shares = publicShareList ) @@ -224,7 +220,7 @@ class ShareFileFragmentTest { @Test fun hidePublicSharesSharingDisabled() { loadShareFileFragment( - capabilities = DUMMY_CAPABILITY.copy(filesSharingPublicEnabled = CapabilityBooleanType.FALSE), + capabilities = OC_CAPABILITY.copy(filesSharingPublicEnabled = CapabilityBooleanType.FALSE), shares = publicShareList ) @@ -235,7 +231,7 @@ class ShareFileFragmentTest { @Test fun createPublicShareMultipleCapability() { loadShareFileFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicMultiple = CapabilityBooleanType.TRUE ), @@ -249,7 +245,7 @@ class ShareFileFragmentTest { @Test fun cannotCreatePublicShareMultipleCapability() { loadShareFileFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "10.1.1", filesSharingPublicMultiple = CapabilityBooleanType.FALSE ), @@ -263,7 +259,7 @@ class ShareFileFragmentTest { @Test fun cannotCreatePublicShareServerCapability() { loadShareFileFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( versionString = "9.3.1" ), shares = listOf(publicShareList[0]) @@ -280,7 +276,7 @@ class ShareFileFragmentTest { @Test fun hideSharesSharingApiDisabled() { loadShareFileFragment( - capabilities = DUMMY_CAPABILITY.copy( + capabilities = OC_CAPABILITY.copy( filesSharingApiEnabled = CapabilityBooleanType.FALSE ) ) @@ -303,9 +299,9 @@ class ShareFileFragmentTest { } private fun loadShareFileFragment( - capabilities: OCCapability = DUMMY_CAPABILITY, - capabilitiesUIResult: UIResult = UIResult.Success(capabilities), - shares: List = listOf(DUMMY_SHARE), + capabilities: OCCapability = OC_CAPABILITY, + capabilitiesEvent: Event> = Event(UIResult.Success(capabilities)), + shares: List = listOf(OC_SHARE), sharesUIResult: UIResult> = UIResult.Success(shares) ) { val ownCloudVersion = mockkClass(OwnCloudVersion::class) @@ -313,8 +309,8 @@ class ShareFileFragmentTest { every { ownCloudVersion.isSearchUsersSupported } returns true val shareFileFragment = ShareFileFragment.newInstance( - DUMMY_FILE, - DUMMY_ACCOUNT, + OC_FILE, + OC_ACCOUNT, ownCloudVersion ) @@ -322,7 +318,7 @@ class ShareFileFragmentTest { it.startFragment(shareFileFragment) } - capabilitiesLiveData.postValue(capabilitiesUIResult) + capabilitiesLiveData.postValue(capabilitiesEvent) sharesLiveData.postValue(Event(sharesUIResult)) } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt index 6ef639380ca..7a0613acb7e 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt @@ -38,10 +38,10 @@ import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.sharing.fragments.ShareFileFragment import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.utils.AppTestUtil.DUMMY_ACCOUNT -import com.owncloud.android.utils.AppTestUtil.DUMMY_CAPABILITY -import com.owncloud.android.utils.AppTestUtil.DUMMY_FOLDER -import com.owncloud.android.utils.AppTestUtil.DUMMY_SHARE +import com.owncloud.android.testutil.OC_ACCOUNT +import com.owncloud.android.testutil.OC_CAPABILITY +import com.owncloud.android.testutil.OC_SHARE +import com.owncloud.android.utils.AppTestUtil.OC_FOLDER import io.mockk.every import io.mockk.mockk import io.mockk.mockkClass @@ -58,7 +58,7 @@ import org.koin.dsl.module @RunWith(AndroidJUnit4::class) class ShareFolderFragmentTest { private val ocCapabilityViewModel = mockk(relaxed = true) - private val capabilitiesLiveData = MutableLiveData>() + private val capabilitiesLiveData = MutableLiveData>>() private val ocShareViewModel = mockk(relaxed = true) private val sharesLiveData = MutableLiveData>>>() @@ -87,8 +87,8 @@ class ShareFolderFragmentTest { every { ownCloudVersion.isSearchUsersSupported } returns true val shareFileFragment = ShareFileFragment.newInstance( - DUMMY_FOLDER, - DUMMY_ACCOUNT, + OC_FOLDER, + OC_ACCOUNT, ownCloudVersion ) @@ -96,9 +96,9 @@ class ShareFolderFragmentTest { it.startFragment(shareFileFragment) } - capabilitiesLiveData.postValue(UIResult.Success(DUMMY_CAPABILITY)) + capabilitiesLiveData.postValue(Event(UIResult.Success(OC_CAPABILITY))) - sharesLiveData.postValue(Event(UIResult.Success(listOf(DUMMY_SHARE)))) + sharesLiveData.postValue(Event(UIResult.Success(listOf(OC_SHARE)))) } @Test diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt index f93dbc09e3a..ec83a9512a2 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt @@ -18,7 +18,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.presentation.sharing.shares.viewmodels +package com.owncloud.android.sharing.shares.viewmodels import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule @@ -33,11 +33,12 @@ import com.owncloud.android.domain.sharing.shares.usecases.EditPublicShareAsyncU import com.owncloud.android.domain.sharing.shares.usecases.GetShareAsLiveDataUseCase import com.owncloud.android.domain.sharing.shares.usecases.GetSharesAsLiveDataUseCase import com.owncloud.android.domain.sharing.shares.usecases.RefreshSharesFromServerAsyncUseCase -import com.owncloud.android.domain.utils.DomainTestUtil.DUMMY_SHARE import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.utils.AppTestUtil -import com.owncloud.android.utils.TIMEOUT_TEST_LONG +import com.owncloud.android.testutil.OC_ACCOUNT +import com.owncloud.android.testutil.OC_SHARE +import com.owncloud.android.testutil.livedata.TIMEOUT_TEST_LONG +import com.owncloud.android.testutil.livedata.getOrAwaitValues import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every @@ -67,9 +68,9 @@ class OCShareViewModelTest { private val filePath = "/Photos/image.jpg" - private var testAccount: Account = AppTestUtil.createAccount("admin@server", "test") + private var testAccount: Account = OC_ACCOUNT - private val sharesLiveData = MutableLiveData?>() + private val sharesLiveData = MutableLiveData>() private val privateShareLiveData = MutableLiveData() @Rule @@ -173,7 +174,7 @@ class OCShareViewModelTest { fun refreshPrivateShareSuccess() { initTest() - val ocShare = DUMMY_SHARE.copy(id = 123, name = "PhotoLink") + val ocShare = OC_SHARE.copy(id = 123, name = "PhotoLink") privateShareLiveData.postValue(ocShare) refreshPrivateShareVerification( @@ -190,12 +191,12 @@ class OCShareViewModelTest { ) { coEvery { createPrivateShareAsyncUseCase.execute(any()) } returns valueToTest - ocShareViewModel.refreshPrivateShare(DUMMY_SHARE.remoteId) + ocShareViewModel.refreshPrivateShare(OC_SHARE.remoteId) val value = ocShareViewModel.privateShare.getOrAwaitValues(expectedOnPosition) assertEquals(expectedValue, value[expectedOnPosition - 1]) - verify(exactly = 1) { getShareAsLiveDataUseCase.execute(GetShareAsLiveDataUseCase.Params(DUMMY_SHARE.remoteId)) } + verify(exactly = 1) { getShareAsLiveDataUseCase.execute(GetShareAsLiveDataUseCase.Params(OC_SHARE.remoteId)) } // Just once on init verify(exactly = 1) { getSharesAsLiveDataUseCase.execute(any()) } } @@ -208,11 +209,11 @@ class OCShareViewModelTest { coEvery { createPrivateShareAsyncUseCase.execute(any()) } returns valueToTest ocShareViewModel.insertPrivateShare( - filePath = DUMMY_SHARE.path, - shareType = DUMMY_SHARE.shareType, - shareeName = DUMMY_SHARE.accountOwner, - permissions = DUMMY_SHARE.permissions, - accountName = DUMMY_SHARE.accountOwner + filePath = OC_SHARE.path, + shareType = OC_SHARE.shareType, + shareeName = OC_SHARE.accountOwner, + permissions = OC_SHARE.permissions, + accountName = OC_SHARE.accountOwner ) val value = ocShareViewModel.privateShareCreationStatus.getOrAwaitValues(expectedOnPosition) @@ -230,9 +231,9 @@ class OCShareViewModelTest { coEvery { editPrivateShareAsyncUseCase.execute(any()) } returns valueToTest ocShareViewModel.updatePrivateShare( - remoteId = DUMMY_SHARE.remoteId, - permissions = DUMMY_SHARE.permissions, - accountName = DUMMY_SHARE.accountOwner + remoteId = OC_SHARE.remoteId, + permissions = OC_SHARE.permissions, + accountName = OC_SHARE.accountOwner ) val value = ocShareViewModel.privateShareEditionStatus.getOrAwaitValues(expectedOnPosition) @@ -324,13 +325,13 @@ class OCShareViewModelTest { coEvery { createPublicShareAsyncUseCase.execute(any()) } returns valueToTest ocShareViewModel.insertPublicShare( - filePath = DUMMY_SHARE.path, + filePath = OC_SHARE.path, name = "Photos 2 link", password = "1234", expirationTimeInMillis = -1, publicUpload = false, - permissions = DUMMY_SHARE.permissions, - accountName = DUMMY_SHARE.accountOwner + permissions = OC_SHARE.permissions, + accountName = OC_SHARE.accountOwner ) val value = ocShareViewModel.publicShareCreationStatus.getOrAwaitValues(expectedOnPosition) @@ -461,7 +462,7 @@ class OCShareViewModelTest { coEvery { deletePublicShareAsyncUseCase.execute(any()) } returns valueToTest ocShareViewModel.deleteShare( - remoteId = DUMMY_SHARE.remoteId + remoteId = OC_SHARE.remoteId ) val value = ocShareViewModel.shareDeletionStatus.getOrAwaitValues(expectedOnPosition) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt index e57766b3182..07bc75cf91e 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt @@ -19,41 +19,11 @@ package com.owncloud.android.utils -import android.accounts.Account -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity import com.owncloud.android.datamodel.OCFile -import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType -import com.owncloud.android.domain.capabilities.model.OCCapability -import com.owncloud.android.domain.sharing.shares.model.OCShare -import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation import org.json.JSONObject object AppTestUtil { - /** - * Shares - */ - val DUMMY_SHARE = OCShare( - fileSource = 7, - itemSource = 7, - shareType = ShareType.USER, // Private share by default - shareWith = "", - path = "/Photos/image.jpg", - permissions = 1, - sharedDate = 1542628397, - expirationDate = 0, - token = "AnyToken", - sharedWithDisplayName = "", - sharedWithAdditionalInfo = "", - isFolder = false, - userId = -1, - remoteId = 1, - accountOwner = "admin@server", - name = "", - shareLink = "" - ) - /** * Sharees */ @@ -77,50 +47,11 @@ object AppTestUtil { return jsonObject } - /** - * Capabilities - */ - val DUMMY_CAPABILITY = - OCCapability( - accountName = "user@server", - versionMayor = 2, - versionMinor = 1, - versionMicro = 0, - versionString = "1.0.0", - versionEdition = "1.0.0", - corePollInterval = 0, - filesSharingApiEnabled = CapabilityBooleanType.TRUE, - filesSharingSearchMinLength = 3, - filesSharingPublicEnabled = CapabilityBooleanType.TRUE, - filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE, - filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE, - filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE, - filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE, - filesSharingPublicExpireDateEnabled = CapabilityBooleanType.FALSE, - filesSharingPublicExpireDateDays = 0, - filesSharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE, - filesSharingPublicSendMail = CapabilityBooleanType.FALSE, - filesSharingPublicUpload = CapabilityBooleanType.FALSE, - filesSharingPublicMultiple = CapabilityBooleanType.FALSE, - filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.FALSE, - filesSharingUserSendMail = CapabilityBooleanType.FALSE, - filesSharingResharing = CapabilityBooleanType.FALSE, - filesSharingFederationOutgoing = CapabilityBooleanType.FALSE, - filesSharingFederationIncoming = CapabilityBooleanType.FALSE, - filesBigFileChunking = CapabilityBooleanType.FALSE, - filesUndelete = CapabilityBooleanType.FALSE, - filesVersioning = CapabilityBooleanType.FALSE - ) - - /** - * Accounts - */ - val DUMMY_ACCOUNT = Account("test", "owncloud") - /** * Files + * Move to owncloudTestUtil module when OCFile is migrated to owncloudDomain */ - val DUMMY_FILE = OCFile( + val OC_FILE = OCFile( "/Images/img.png" ).apply { fileId = 1 @@ -129,7 +60,7 @@ object AppTestUtil { privateLink = "privateLink" } - val DUMMY_FOLDER = OCFile( + val OC_FOLDER = OCFile( "/Images/img.png" ).apply { fileName = "/Documents/" diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/LiveDataTestUtil.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/LiveDataTestUtil.kt deleted file mode 100644 index d5667143fb1..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/LiveDataTestUtil.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.owncloud.android.utils - -import androidx.lifecycle.LiveData -import androidx.lifecycle.Observer -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit - -object LiveDataTestUtil { - - /** - * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds. - * Once we got a notification via onChanged, we stop observing. - */ - inline fun LiveData.getOrAwaitValues( - expectedValues: Int = 1 - ): List { - var currentValue: Int = 0 - val data = arrayOfNulls(expectedValues) - val latch = CountDownLatch(expectedValues) - val observer = object : Observer { - override fun onChanged(o: T?) { - data[currentValue] = o - currentValue++ - latch.countDown() - if (currentValue == expectedValues) { - this@getOrAwaitValues.removeObserver(this) - } - } - } - this.observeForever(observer) - latch.await(TIMEOUT_TEST_SHORT, TimeUnit.MILLISECONDS) - - @Suppress("UNCHECKED_CAST") - return data.toList() - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/ViewModelUtil.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/ViewModelUtil.kt deleted file mode 100644 index e173d35949c..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/ViewModelUtil.kt +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.owncloud.android.utils - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider - -/** - * Creates a one off view model factory for the given view model instance. - */ -object ViewModelUtil { - fun createFor(model: T): ViewModelProvider.Factory { - return object : ViewModelProvider.Factory { - override fun create(modelClass: Class): T { - if (modelClass.isAssignableFrom(model.javaClass)) { - @Suppress("UNCHECKED_CAST") - return model as T - } - throw IllegalArgumentException("unexpected model class $modelClass") - } - } - } -} diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt index 76d8944ef3d..8337b3f2847 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt @@ -361,9 +361,6 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe updateCapabilities(it) } } - else -> { - Log.d(TAG, "Unknown status when loading capabilities in account ${account?.name}") - } } } ) diff --git a/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt b/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt index 73c8a4d1481..58116d0ad14 100644 --- a/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt +++ b/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt @@ -37,28 +37,6 @@ import io.mockk.mockk import org.json.JSONObject object DataTestUtil { - /** - * Shares - */ - val DUMMY_SHARE = OCShare( - fileSource = 7, - itemSource = 7, - shareType = ShareType.USER, // Public share by default - shareWith = "", - path = "/Photos/image.jpg", - permissions = 1, - sharedDate = 1542628397, - expirationDate = 0, - token = "AnyToken", - sharedWithDisplayName = "", - sharedWithAdditionalInfo = "", - isFolder = false, - userId = -1, - remoteId = 1, - accountOwner = "admin@server", - name = "", - shareLink = "" - ) val DUMMY_REMOTE_SHARE = RemoteShare().apply { @@ -302,38 +280,6 @@ object DataTestUtil { /** * Capability */ - val DUMMY_CAPABILITY = - OCCapability( - accountName = "user@server", - versionMayor = 2, - versionMinor = 1, - versionMicro = 0, - versionString = "1.0.0", - versionEdition = "1.0.0", - corePollInterval = 0, - filesSharingApiEnabled = CapabilityBooleanType.TRUE, - filesSharingSearchMinLength = 3, - filesSharingPublicEnabled = CapabilityBooleanType.TRUE, - filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE, - filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE, - filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE, - filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE, - filesSharingPublicExpireDateEnabled = CapabilityBooleanType.FALSE, - filesSharingPublicExpireDateDays = 0, - filesSharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE, - filesSharingPublicSendMail = CapabilityBooleanType.FALSE, - filesSharingPublicUpload = CapabilityBooleanType.FALSE, - filesSharingPublicMultiple = CapabilityBooleanType.FALSE, - filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.FALSE, - filesSharingUserSendMail = CapabilityBooleanType.FALSE, - filesSharingResharing = CapabilityBooleanType.FALSE, - filesSharingFederationOutgoing = CapabilityBooleanType.FALSE, - filesSharingFederationIncoming = CapabilityBooleanType.FALSE, - filesBigFileChunking = CapabilityBooleanType.FALSE, - filesUndelete = CapabilityBooleanType.FALSE, - filesVersioning = CapabilityBooleanType.FALSE - ) - val DUMMY_REMOTE_CAPABILITY = RemoteCapability().apply { accountName = "user@server" diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt index 72e5ec9dd2d..cbfb1a4749d 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt @@ -19,8 +19,8 @@ package com.owncloud.android.data.capabilities.datasources.mapper -import com.owncloud.android.data.utils.DataTestUtil.DUMMY_CAPABILITY import com.owncloud.android.data.utils.DataTestUtil.DUMMY_REMOTE_CAPABILITY +import com.owncloud.android.testutil.OC_CAPABILITY import org.junit.Assert import org.junit.Test @@ -39,6 +39,6 @@ class OCRemoteCapabilityMapperTest { val capability = ocRemoteCapabilityMapper.toModel(DUMMY_REMOTE_CAPABILITY) Assert.assertNotNull(capability) - Assert.assertEquals(capability, DUMMY_CAPABILITY) + Assert.assertEquals(capability, OC_CAPABILITY) } } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt index a5c030c1877..bcfa655e9be 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt @@ -21,7 +21,7 @@ package com.owncloud.android.data.shares.datasources.mapper import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteShareMapper import com.owncloud.android.data.utils.DataTestUtil.DUMMY_REMOTE_SHARE -import com.owncloud.android.data.utils.DataTestUtil.DUMMY_SHARE +import com.owncloud.android.testutil.OC_SHARE import org.junit.Assert import org.junit.Test @@ -40,6 +40,6 @@ class OCRemoteShareMapperTest { val capability = ocRemoteShareMapper.toModel(DUMMY_REMOTE_SHARE) Assert.assertNotNull(capability) - Assert.assertEquals(capability, DUMMY_SHARE.copy(accountOwner = "")) + Assert.assertEquals(capability, OC_SHARE.copy(accountOwner = "")) } } diff --git a/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/DomainTestUtil.kt b/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/DomainTestUtil.kt deleted file mode 100644 index 3ca719db426..00000000000 --- a/owncloudDomain/src/test-common/java/com/owncloud/android/domain/utils/DomainTestUtil.kt +++ /dev/null @@ -1,86 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.domain.utils - -import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType -import com.owncloud.android.domain.capabilities.model.OCCapability -import com.owncloud.android.domain.sharing.shares.model.OCShare -import com.owncloud.android.domain.sharing.shares.model.ShareType - -object DomainTestUtil { - /** - * Shares - */ - - val DUMMY_SHARE = OCShare( - fileSource = 7, - itemSource = 7, - shareType = ShareType.USER, // Public share by default - shareWith = "", - path = "/Photos/image.jpg", - permissions = 1, - sharedDate = 1542628397, - expirationDate = 0, - token = "AnyToken", - sharedWithDisplayName = "", - sharedWithAdditionalInfo = "", - isFolder = false, - userId = -1, - remoteId = 1, - accountOwner = "admin@server", - name = "", - shareLink = "" - ) - - /** - * Capability - */ - val DUMMY_CAPABILITY = - OCCapability( - accountName = "user@server", - versionMayor = 2, - versionMinor = 1, - versionMicro = 0, - versionString = "1.0.0", - versionEdition = "1.0.0", - corePollInterval = 0, - filesSharingApiEnabled = CapabilityBooleanType.TRUE, - filesSharingSearchMinLength = 3, - filesSharingPublicEnabled = CapabilityBooleanType.TRUE, - filesSharingPublicPasswordEnforced = CapabilityBooleanType.FALSE, - filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.FALSE, - filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.FALSE, - filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.FALSE, - filesSharingPublicExpireDateEnabled = CapabilityBooleanType.FALSE, - filesSharingPublicExpireDateDays = 0, - filesSharingPublicExpireDateEnforced = CapabilityBooleanType.FALSE, - filesSharingPublicSendMail = CapabilityBooleanType.FALSE, - filesSharingPublicUpload = CapabilityBooleanType.FALSE, - filesSharingPublicMultiple = CapabilityBooleanType.FALSE, - filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.FALSE, - filesSharingUserSendMail = CapabilityBooleanType.FALSE, - filesSharingResharing = CapabilityBooleanType.FALSE, - filesSharingFederationOutgoing = CapabilityBooleanType.FALSE, - filesSharingFederationIncoming = CapabilityBooleanType.FALSE, - filesBigFileChunking = CapabilityBooleanType.FALSE, - filesUndelete = CapabilityBooleanType.FALSE, - filesVersioning = CapabilityBooleanType.FALSE - ) -} diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetCapabilitiesAsLiveDataUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetCapabilitiesAsLiveDataUseCaseTest.kt index b9519c0a9eb..95621ed06d6 100644 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetCapabilitiesAsLiveDataUseCaseTest.kt +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/usecases/GetCapabilitiesAsLiveDataUseCaseTest.kt @@ -24,7 +24,7 @@ import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import com.owncloud.android.domain.capabilities.CapabilityRepository import com.owncloud.android.domain.capabilities.model.OCCapability -import com.owncloud.android.domain.utils.DomainTestUtil +import com.owncloud.android.testutil.OC_CAPABILITY import io.mockk.every import io.mockk.spyk import org.junit.Assert @@ -52,7 +52,7 @@ class GetCapabilitiesAsLiveDataUseCaseTest { val capabilitiesLiveData = MutableLiveData() every { capabilityRepository.getCapabilitiesAsLiveData(any()) } returns capabilitiesLiveData - val capabilitiesToEmit = listOf(DomainTestUtil.DUMMY_CAPABILITY) + val capabilitiesToEmit = listOf(OC_CAPABILITY) useCase.execute(useCaseParams).observeForever { capabilitiesEmitted.add(it!!) diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetShareAsLiveDataUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetShareAsLiveDataUseCaseTest.kt index a64860edf10..7c041d5d5a6 100644 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetShareAsLiveDataUseCaseTest.kt +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetShareAsLiveDataUseCaseTest.kt @@ -24,8 +24,7 @@ import androidx.lifecycle.MutableLiveData import com.owncloud.android.domain.sharing.shares.ShareRepository import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.usecases.GetShareAsLiveDataUseCase -import com.owncloud.android.domain.utils.DomainTestUtil.DUMMY_SHARE - +import com.owncloud.android.testutil.OC_SHARE import io.mockk.every import io.mockk.spyk import org.junit.Assert @@ -53,7 +52,7 @@ class GetShareAsLiveDataUseCaseTest { val shareLiveData = MutableLiveData() every { shareRepository.getShareAsLiveData(any()) } returns shareLiveData - val shareToEmit = listOf(DUMMY_SHARE) + val shareToEmit = listOf(OC_SHARE) useCase.execute(useCaseParams).observeForever { shareEmitted.add(it) diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetSharesAsLiveDataUseCaseTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetSharesAsLiveDataUseCaseTest.kt index aef95b07aef..86cb0b9c1ee 100644 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetSharesAsLiveDataUseCaseTest.kt +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/GetSharesAsLiveDataUseCaseTest.kt @@ -24,8 +24,7 @@ import androidx.lifecycle.MutableLiveData import com.owncloud.android.domain.sharing.shares.ShareRepository import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.usecases.GetSharesAsLiveDataUseCase -import com.owncloud.android.domain.utils.DomainTestUtil.DUMMY_SHARE - +import com.owncloud.android.testutil.OC_SHARE import io.mockk.every import io.mockk.spyk import org.junit.Assert @@ -53,7 +52,7 @@ class GetSharesAsLiveDataUseCaseTest { val sharesLiveData = MutableLiveData>() every { shareRepository.getSharesAsLiveData(any(), any()) } returns sharesLiveData - val sharesToEmit = listOf(DUMMY_SHARE, DUMMY_SHARE.copy(id = 2), DUMMY_SHARE.copy(id = 3)) + val sharesToEmit = listOf(OC_SHARE, OC_SHARE.copy(id = 2), OC_SHARE.copy(id = 3)) useCase.execute(useCaseParams).observeForever { it?.forEach { ocShare -> sharesEmitted.add(ocShare) } diff --git a/owncloudTestUtil/build.gradle b/owncloudTestUtil/build.gradle index 784fead5792..81fbf262d42 100644 --- a/owncloudTestUtil/build.gradle +++ b/owncloudTestUtil/build.gradle @@ -21,4 +21,5 @@ dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation project(':owncloudDomain') implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" + implementation "androidx.lifecycle:lifecycle-livedata-ktx:$ktxLiveData" } diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt index d2f7f0af636..dcfa751b043 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt @@ -1,3 +1,10 @@ package com.owncloud.android.testutil +import android.accounts.Account + const val OC_ACCOUNT_NAME = "admin@server" + +/** + * Accounts + */ +val OC_ACCOUNT = Account("ownCloud", "test") diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt new file mode 100644 index 00000000000..722af1b595d --- /dev/null +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt @@ -0,0 +1,24 @@ +package com.owncloud.android.testutil + +import com.owncloud.android.domain.sharing.shares.model.OCShare +import com.owncloud.android.domain.sharing.shares.model.ShareType + +val OC_SHARE = OCShare( + fileSource = 7, + itemSource = 7, + shareType = ShareType.USER, // Private share by default + shareWith = "", + path = "/Photos/image.jpg", + permissions = 1, + sharedDate = 1542628397, + expirationDate = 0, + token = "AnyToken", + sharedWithDisplayName = "", + sharedWithAdditionalInfo = "", + isFolder = false, + userId = -1, + remoteId = 1, + accountOwner = "admin@server", + name = "", + shareLink = "" +) diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveData.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveData.kt new file mode 100644 index 00000000000..679ecd81d51 --- /dev/null +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveData.kt @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.owncloud.android.testutil.livedata + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +/** + * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds. + * Once we got a notification via onChanged, we stop observing. + */ +inline fun LiveData.getOrAwaitValues( + expectedValues: Int = 1 +): List { + var currentValue = 0 + val data = arrayOfNulls(expectedValues) + val latch = CountDownLatch(expectedValues) + val observer = object : Observer { + override fun onChanged(o: T?) { + data[currentValue] = o + currentValue++ + latch.countDown() + if (currentValue == expectedValues) { + this@getOrAwaitValues.removeObserver(this) + } + } + } + this.observeForever(observer) + latch.await(TIMEOUT_TEST_SHORT, TimeUnit.MILLISECONDS) + + return data.toList() +} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/TestTimeOutConstants.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/TestTimeOutConstants.kt similarity index 94% rename from owncloudApp/src/androidTest/java/com/owncloud/android/utils/TestTimeOutConstants.kt rename to owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/TestTimeOutConstants.kt index 0c585d099a4..7fa0077ac73 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/TestTimeOutConstants.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/TestTimeOutConstants.kt @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.owncloud.android.utils +package com.owncloud.android.testutil.livedata const val TIMEOUT_TEST_LONG = 5_000L const val TIMEOUT_TEST_SHORT = 2_000L \ No newline at end of file From ec9fe40b8aa1274bd5824e5f1526e585f86858b0 Mon Sep 17 00:00:00 2001 From: davigonz Date: Thu, 21 Nov 2019 12:47:50 +0100 Subject: [PATCH 24/41] Update type of test Accounts and remove no longer needed test utils --- .../android/utils/AccountsTestManager.kt | 102 ------------------ .../com/owncloud/android/utils/AppTestUtil.kt | 23 ---- .../owncloud/android/utils/FileManager.java | 62 ----------- .../owncloud/android/utils/ServerType.java | 66 ------------ .../dependecyinjection/ViewModelModule.kt | 2 +- .../capabilities/OCCapabilityViewModel.kt | 7 -- .../owncloud/android/testutil/OCAccount.kt | 2 +- 7 files changed, 2 insertions(+), 262 deletions(-) delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsTestManager.kt delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/utils/FileManager.java delete mode 100644 owncloudApp/src/androidTest/java/com/owncloud/android/utils/ServerType.java diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsTestManager.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsTestManager.kt deleted file mode 100644 index 18ecd0f949e..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AccountsTestManager.kt +++ /dev/null @@ -1,102 +0,0 @@ -/** - * ownCloud Android client application - * - * - * Copyright (C) 2016 ownCloud GmbH. - * - * - * - * - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * - * This program 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 this program. If not, see //www.gnu.org/licenses/>. - */ -package com.owncloud.android.utils - -import android.accounts.Account -import android.accounts.AccountManager -import android.content.Context -import android.os.SystemClock -import com.owncloud.android.authentication.AccountAuthenticator -import com.owncloud.android.lib.common.accounts.AccountUtils -import com.owncloud.android.lib.resources.status.OwnCloudVersion - -object AccountsTestManager { - private const val accountType = "owncloud" - private const val KEY_AUTH_TOKEN_TYPE = "AUTH_TOKEN_TYPE" - private const val KEY_AUTH_TOKEN = "AUTH_TOKEN" - private const val version = "" - private const val WAIT_UNTIL_ACCOUNT_CREATED_MS = 1000 - private const val HTTP_SCHEME = "http://" - private const val HTTPS_SCHEME = "https://" - - fun addAccount( - context: Context?, - account: Account, - password: String? - ) { // obtaining an AccountManager instance - // obtaining an AccountManager instance - val accountManager = AccountManager.get(context) - - accountManager.addAccountExplicitly(account, password, null) - - // include account version, user, server version and token with the new account - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_VERSION, - OwnCloudVersion("10.2").toString() - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_BASE_URL, - "serverUrl:port" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_DISPLAY_NAME, - "admin" - ) - accountManager.setUserData( - account, - AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION, - "1" - ) - - accountManager.setAuthToken( - account, - AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, - "AUTH_TOKEN" - ) - } - - //Remove an account from the device - fun deleteAccount(context: Context?, accountDel: String?) { - val accountManager = AccountManager.get(context) - val account = Account(accountDel, accountType) - accountManager.removeAccount(account, null, null) - } - - //Remove all accounts from the device - fun deleteAllAccounts(context: Context?) { - val accountManager = AccountManager.get(context) - val accounts = accountManager.accounts - for (account in accounts) { - if (account.type.compareTo(accountType) == 0) { - accountManager.removeAccount(account, null, null) - SystemClock.sleep(WAIT_UNTIL_ACCOUNT_CREATED_MS.toLong()) - } - } - } -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt index 07bc75cf91e..00d460cd68e 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/AppTestUtil.kt @@ -24,29 +24,6 @@ import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation import org.json.JSONObject object AppTestUtil { - /** - * Sharees - */ - fun createSharee( - label: String, - shareType: String, - shareWith: String, - shareWithAdditionalInfo: String - ): JSONObject { - val jsonObject = JSONObject() - - jsonObject.put(GetRemoteShareesOperation.PROPERTY_LABEL, label) - - val value = JSONObject() - value.put(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE, shareType) - value.put(GetRemoteShareesOperation.PROPERTY_SHARE_WITH, shareWith) - value.put(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO, shareWithAdditionalInfo) - - jsonObject.put(GetRemoteShareesOperation.NODE_VALUE, value) - - return jsonObject - } - /** * Files * Move to owncloudTestUtil module when OCFile is migrated to owncloudDomain diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/FileManager.java b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/FileManager.java deleted file mode 100644 index a0d3e7d0b77..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/FileManager.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.owncloud.android.utils; - -import android.content.Context; - -import androidx.test.uiautomator.UiObject; -import androidx.test.uiautomator.UiSelector; -import com.owncloud.android.R; - -import static androidx.test.espresso.Espresso.onView; -import static androidx.test.espresso.action.ViewActions.click; -import static androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA; -import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription; -import static androidx.test.espresso.matcher.ViewMatchers.withId; -import static org.hamcrest.Matchers.allOf; - -/** - * ownCloud Android client application - * - * @author Jesús Recio @jesmrec - * Copyright (C) 2017 ownCloud GmbH. - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - *

- * This program 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 this program. If not, see . - */ - -public class FileManager { - - //To select an option in files view - public static void selectOptionActionsMenu(Context context, int option) { - String optionSelected = context.getResources().getString(option); - if (!new UiObject(new UiSelector().description(optionSelected)).exists()) { - onView(allOf(withContentDescription("More options"), - isDescendantOfA(withId(R.id.toolbar)))).perform(click()); - switch (option) { - case R.string.action_share: - onView(withId(R.id.action_share_file)).perform(click()); - break; - default: - break; - } - - } else { - switch (option) { - case R.string.action_share: - onView(withId(R.id.action_share_file)).perform(click()); - break; - default: - break; - } - } - } - -} diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/ServerType.java b/owncloudApp/src/androidTest/java/com/owncloud/android/utils/ServerType.java deleted file mode 100644 index 8a587a4152e..00000000000 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/utils/ServerType.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * ownCloud Android client application - * - * @author Jesús Recio @jesmrec - * Copyright (C) 2017 ownCloud GmbH. - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - *

- * This program 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 this program. If not, see . - */ - -package com.owncloud.android.utils; - -public enum ServerType { - /* - * Server with http - */ - HTTP(1), - - /* - * Server with https, but non-secure certificate - */ - HTTPS_NON_SECURE(2), - - /* - * Server with https - */ - HTTPS_SECURE(3), - - /* - * Server redirected to a non-secure server - */ - REDIRECTED_NON_SECURE(4); - - private final int status; - - ServerType(int status) { - this.status = status; - } - - public int getStatus() { - return status; - } - - public static ServerType fromValue(int value) { - switch (value) { - case 1: - return HTTP; - case 2: - return HTTPS_NON_SECURE; - case 3: - return HTTPS_SECURE; - case 4: - return REDIRECTED_NON_SECURE; - } - return null; - } -} diff --git a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt index 9d941891ce5..8797f8fd88b 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt @@ -26,7 +26,7 @@ import org.koin.dsl.module val viewModelModule = module { viewModel { (accountName: String) -> - OCCapabilityViewModel(accountName, get(), get(), get()) + OCCapabilityViewModel(accountName, get(), get()) } viewModel { (filePath: String, accountName: String) -> diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt index c0fdb98f886..68cb54af0a3 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt @@ -41,7 +41,6 @@ import kotlinx.coroutines.withContext class OCCapabilityViewModel( private val accountName: String, getCapabilitiesAsLiveDataUseCase: GetCapabilitiesAsLiveDataUseCase, - private val getStoredCapabilitiesUseCase: GetStoredCapabilitiesUseCase, private val refreshCapabilitiesFromServerUseCase: RefreshCapabilitiesFromServerAsyncUseCase, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) : ViewModel() { @@ -63,12 +62,6 @@ class OCCapabilityViewModel( refreshCapabilitiesFromNetwork() } - fun getStoredCapabilities(): OCCapability? = getStoredCapabilitiesUseCase.execute( - GetStoredCapabilitiesUseCase.Params( - accountName = accountName - ) - ) - fun refreshCapabilitiesFromNetwork() { viewModelScope.launch { _capabilities.postValue( diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt index dcfa751b043..dbf12a95db9 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCAccount.kt @@ -7,4 +7,4 @@ const val OC_ACCOUNT_NAME = "admin@server" /** * Accounts */ -val OC_ACCOUNT = Account("ownCloud", "test") +val OC_ACCOUNT = Account("ownCloudTestAccount", "owncloud") From e5aadb8bdb08e2d7b51b24e28eee1ebefc6d77ad Mon Sep 17 00:00:00 2001 From: davigonz Date: Thu, 21 Nov 2019 13:16:23 +0100 Subject: [PATCH 25/41] Start to fix OCCapabilityViewModelTest --- .../viewmodels/OCCapabilityViewModelTest.kt | 94 ++++++++++--------- 1 file changed, 48 insertions(+), 46 deletions(-) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt index ee5a0643da8..8665339d25e 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt @@ -25,8 +25,9 @@ import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import com.owncloud.android.domain.UseCaseResult import com.owncloud.android.domain.capabilities.model.OCCapability -import com.owncloud.android.domain.capabilities.usecases.GetStoredCapabilitiesUseCase +import com.owncloud.android.domain.capabilities.usecases.GetCapabilitiesAsLiveDataUseCase import com.owncloud.android.domain.capabilities.usecases.RefreshCapabilitiesFromServerAsyncUseCase +import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.testutil.OC_ACCOUNT @@ -51,10 +52,10 @@ import org.junit.runners.JUnit4 class OCCapabilityViewModelTest { private lateinit var ocCapabilityViewModel: OCCapabilityViewModel - private lateinit var getStoredCapabilitiesUseCase: GetStoredCapabilitiesUseCase + private lateinit var getCapabilitiesAsLiveDataUseCase: GetCapabilitiesAsLiveDataUseCase private lateinit var refreshCapabilitiesFromServerUseCase: RefreshCapabilitiesFromServerAsyncUseCase - private val capabilityLiveData = MutableLiveData() + private val capabilitiesLiveData = MutableLiveData() private var testAccount: Account = OC_ACCOUNT @@ -68,37 +69,37 @@ class OCCapabilityViewModelTest { } private fun initTest() { - getStoredCapabilitiesUseCase = spyk(mockkClass(GetStoredCapabilitiesUseCase::class)) + getCapabilitiesAsLiveDataUseCase = spyk(mockkClass(GetCapabilitiesAsLiveDataUseCase::class)) refreshCapabilitiesFromServerUseCase = spyk(mockkClass(RefreshCapabilitiesFromServerAsyncUseCase::class)) - every { getStoredCapabilitiesUseCase.execute(any()) } returns capabilityLiveData + every { getCapabilitiesAsLiveDataUseCase.execute(any()) } returns capabilitiesLiveData ocCapabilityViewModel = OCCapabilityViewModel( accountName = testAccount.name, - getStoredCapabilitiesUseCase = getStoredCapabilitiesUseCase, + getCapabilitiesAsLiveDataUseCase = getCapabilitiesAsLiveDataUseCase, refreshCapabilitiesFromServerUseCase = refreshCapabilitiesFromServerUseCase ) } @Test - fun getStoredCapabilitiesWithData() { + fun getCapabilitiesAsLiveDataWithData() { initTest() val capability = OC_CAPABILITY.copy(accountName = testAccount.name) - getStoredCapabilitiesVerification( + getCapabilitiesAsLiveDataVerification( valueToTest = capability, - expectedValue = UIResult.Success(capability) + expectedValue = Event(UIResult.Success(capability)) ) } @Test - fun getStoredCapabilitiesWithoutData() { + fun getCapabilitiesAsLiveDataWithoutData() { initTest() - getStoredCapabilitiesVerification( + getCapabilitiesAsLiveDataVerification( valueToTest = null, - expectedValue = null + expectedValue = Event(UIResult.Success(null)) ) } @@ -108,51 +109,52 @@ class OCCapabilityViewModelTest { fetchCapabilitiesVerification( valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Loading() + expectedValue = Event(UIResult.Loading()) ) } - - @Test - fun fetchCapabilitiesError() { - initTest() - - val error = Throwable() - fetchCapabilitiesVerification( - valueToTest = UseCaseResult.Error(error), - expectedValue = UIResult.Error(error), - expectedOnPosition = 2 - ) - } - - @Test - fun fetchCapabilitiesSuccess() { - initTest() - - //Expect a null since we are mocking refreshCapabilities and we are not storing new capabilities on db - fetchCapabilitiesVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = null, - expectedOnPosition = 2 - ) - } - - private fun getStoredCapabilitiesVerification( +// +// @Test +// fun fetchCapabilitiesError() { +// initTest() +// +// val error = Throwable() +// fetchCapabilitiesVerification( +// valueToTest = UseCaseResult.Error(error), +// expectedValue = UIResult.Error(error), +// expectedOnPosition = 2 +// ) +// } +// +// @Test +// fun fetchCapabilitiesSuccess() { +// initTest() +// +// //Expect a null since we are mocking refreshCapabilities and we are not storing new capabilities on db +// fetchCapabilitiesVerification( +// valueToTest = UseCaseResult.Success(Unit), +// expectedValue = null, +// expectedOnPosition = 2 +// ) +// } + + private fun getCapabilitiesAsLiveDataVerification( valueToTest: OCCapability?, - expectedValue: UIResult?, + expectedValue: Event>?, expectedOnPosition: Int = 1 ) { - capabilityLiveData.postValue(valueToTest) + // Calls performed during OCCapabilityViewModel initialization + verify(exactly = 1) { getCapabilitiesAsLiveDataUseCase.execute(any()) } + verify(exactly = 1) { refreshCapabilitiesFromServerUseCase.execute(any()) } + + capabilitiesLiveData.postValue(valueToTest) val value = ocCapabilityViewModel.capabilities.getOrAwaitValues() assertEquals(expectedValue, value[expectedOnPosition - 1]) - - coVerify(exactly = 0) { refreshCapabilitiesFromServerUseCase.execute(any()) } - verify(exactly = 1) { getStoredCapabilitiesUseCase.execute(any()) } } private fun fetchCapabilitiesVerification( valueToTest: UseCaseResult, - expectedValue: UIResult?, + expectedValue: Event?>, expectedOnPosition: Int = 1 ) { coEvery { refreshCapabilitiesFromServerUseCase.execute(any()) } returns valueToTest @@ -164,6 +166,6 @@ class OCCapabilityViewModelTest { coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { refreshCapabilitiesFromServerUseCase.execute(any()) } //Just once on init - verify(exactly = 1) { getStoredCapabilitiesUseCase.execute(any()) } + verify(exactly = 1) { getCapabilitiesAsLiveDataUseCase.execute(any()) } } } From 0dfe7eb48f8e79f8fcb1160810485ba08d1c860d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Thu, 21 Nov 2019 15:05:43 +0100 Subject: [PATCH 26/41] Move datautils to owncloudTestUtil module --- .../utils/ErrorMessageAdapterUnitTest.java | 77 --- .../data/sharing/shares/db/OCShareDaoTest.kt | 167 ++++--- .../android/data/utils/DataTestUtil.kt | 444 ------------------ .../OCRemoteCapabilitiesDataSourceTest.kt | 19 +- .../mapper/OCCapabilityMapperTest.kt | 7 +- .../mapper/OCRemoteCapabilityMapperTest.kt | 6 +- .../OCLocalSharesDataSourceTest.kt | 56 +-- .../OCRemoteSharesDataSourceTest.kt | 140 +++--- .../mapper/OCRemoteShareMapperTest.kt | 10 +- .../datasources/mapper/OCShareMapperTest.kt | 17 +- .../repository/OCShareRepositoryTest.kt | 23 +- .../com/owncloud/android/testutil/OCShare.kt | 13 + 12 files changed, 251 insertions(+), 728 deletions(-) delete mode 100644 owncloudApp/src/test/java/com/owncloud/android/utils/ErrorMessageAdapterUnitTest.java diff --git a/owncloudApp/src/test/java/com/owncloud/android/utils/ErrorMessageAdapterUnitTest.java b/owncloudApp/src/test/java/com/owncloud/android/utils/ErrorMessageAdapterUnitTest.java deleted file mode 100644 index 19226a32959..00000000000 --- a/owncloudApp/src/test/java/com/owncloud/android/utils/ErrorMessageAdapterUnitTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David A. Velasco - * Copyright (C) 2019 ownCloud GmbH. - *

- * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - *

- * This program 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 this program. If not, see . - */ - -package com.owncloud.android.utils; - -import android.content.res.Resources; - -import com.owncloud.android.R; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.operations.RemoveFileOperation; -import com.owncloud.android.ui.errorhandling.ErrorMessageAdapter; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.when; - -/** - * Local unit test, to be run out of Android emulator or device. - *

- * At the moment, it's a sample to validate the automatic test environment, in the scope of local unit tests with - * mock Android dependencies. - *

- * Don't take it as an example of completeness. - *

- * See http://developer.android.com/intl/es/training/testing/unit-testing/local-unit-tests.html . - */ -@RunWith(MockitoJUnitRunner.class) -public class ErrorMessageAdapterUnitTest { - - private final static String MOCK_FORBIDDEN_PERMISSIONS = "You do not have permission %s"; - private final static String MOCK_TO_DELETE = "to delete this file"; - private final static String PATH_TO_DELETE = "/path/to/a.file"; - private final static String EXPECTED_ERROR_MESSAGE = "You do not have permission to delete this file"; - - @Mock - Resources mMockResources; - - @Test - public void getErrorCauseMessageForForbiddenRemoval() { - // Given a mocked set of resources passed to the object under test... - when(mMockResources.getString(R.string.forbidden_permissions)) - .thenReturn(MOCK_FORBIDDEN_PERMISSIONS); - when(mMockResources.getString(R.string.forbidden_permissions_delete)) - .thenReturn(MOCK_TO_DELETE); - - // ... when method under test is called ... - String errorMessage = ErrorMessageAdapter.Companion.getResultMessage( - new RemoteOperationResult(RemoteOperationResult.ResultCode.FORBIDDEN), - new RemoveFileOperation(PATH_TO_DELETE, false, true), - mMockResources - ); - - // ... then the result should be the expected one. - assertThat(errorMessage, is(EXPECTED_ERROR_MESSAGE)); - - } -} diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt index d0adf48454a..d112aa27127 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt @@ -23,9 +23,11 @@ import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.OwncloudDatabase -import com.owncloud.android.data.utils.DataTestUtil +import com.owncloud.android.data.sharing.shares.datasources.mapper.OCShareMapper import com.owncloud.android.data.utils.LiveDataTestUtil.getValue import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.testutil.OC_PRIVATE_SHARE +import com.owncloud.android.testutil.OC_PUBLIC_SHARE import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertEquals @@ -41,6 +43,7 @@ class OCShareDaoTest { val instantExecutorRule = InstantTaskExecutorRule() private lateinit var ocShareDao: OCShareDao + private val ocShareMapper = OCShareMapper() private val privateShareTypeValues = listOf( ShareType.USER.value, ShareType.GROUP.value, ShareType.FEDERATED.value @@ -79,24 +82,30 @@ class OCShareDaoTest { fun insertSharesFromDifferentFilesAndRead() { ocShareDao.insert( listOf( - DataTestUtil.createPublicShareEntity( - path = "/Photos/", - isFolder = true, - name = "Photos folder link", - shareLink = "http://server:port/s/1" - ), - DataTestUtil.createPublicShareEntity( - path = "/Photos/image1.jpg", - isFolder = false, - name = "Image 1 link", - shareLink = "http://server:port/s/2" - ), - DataTestUtil.createPrivateShareEntity( - path = "/Photos/image2.jpg", - isFolder = false, - shareWith = "username", - sharedWithDisplayName = "John" - ) + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( + path = "/Photos/", + isFolder = true, + name = "Photos folder link", + shareLink = "http://server:port/s/1" + ) + )!!, + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( + path = "/Photos/image1.jpg", + isFolder = false, + name = "Image 1 link", + shareLink = "http://server:port/s/2" + ) + )!!, + ocShareMapper.toEntity( + OC_PRIVATE_SHARE.copy( + path = "/Photos/image2.jpg", + isFolder = false, + shareWith = "username", + sharedWithDisplayName = "John" + ) + )!! ) ) @@ -144,27 +153,33 @@ class OCShareDaoTest { fun insertSharesFromDifferentAccountsAndRead() { ocShareDao.insert( listOf( - DataTestUtil.createPublicShareEntity( - path = "/Documents/document1.docx", - isFolder = false, - accountOwner = "user1@server", - name = "Document 1 link", - shareLink = "http://server:port/s/1" - ), - DataTestUtil.createPublicShareEntity( - path = "/Documents/document1.docx", - isFolder = false, - accountOwner = "user2@server", - name = "Document 1 link", - shareLink = "http://server:port/s/2" - ), - DataTestUtil.createPrivateShareEntity( - path = "/Documents/document1.docx", - isFolder = false, - accountOwner = "user3@server", - shareWith = "user_name", - sharedWithDisplayName = "Patrick" - ) + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( + path = "/Documents/document1.docx", + isFolder = false, + accountOwner = "user1@server", + name = "Document 1 link", + shareLink = "http://server:port/s/1" + ) + )!!, + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( + path = "/Documents/document1.docx", + isFolder = false, + accountOwner = "user2@server", + name = "Document 1 link", + shareLink = "http://server:port/s/2" + ) + )!!, + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( + path = "/Documents/document1.docx", + isFolder = false, + accountOwner = "user3@server", + shareWith = "user_name", + sharedWithDisplayName = "Patrick" + ) + )!! ) ) @@ -209,23 +224,25 @@ class OCShareDaoTest { } @Test - fun testAutogenerationId() { + fun testAutogenerateId() { ocShareDao.insert( listOf( - DataTestUtil.createPublicShareEntity( - path = "/Documents/document1.docx", - isFolder = false, - accountOwner = "user1@server", - name = "Document 1 link", - shareLink = "http://server:port/s/1" - ), - DataTestUtil.createPublicShareEntity( - path = "/Documents/document1.docx", - isFolder = false, - accountOwner = "user1@server", - name = "Document 1 link", - shareLink = "http://server:port/s/1" - ) + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( + path = "/Documents/document1.docx", + accountOwner = "user1@server", + name = "Document 1 link", + shareLink = "http://server:port/s/1" + ) + )!!, + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( + path = "/Documents/document1.docx", + accountOwner = "user1@server", + name = "Document 1 link", + shareLink = "http://server:port/s/1" + ) + )!! ) ) @@ -295,13 +312,13 @@ class OCShareDaoTest { @Test fun replacePrivateShareIfAlreadyExists_doesNotExist() { val privateShare = createDefaultPrivateShareEntity( - shareType = ShareType.GROUP.value + shareType = ShareType.GROUP ) ocShareDao.insert(privateShare) val privateShareToReplace = createDefaultPrivateShareEntity( - shareType = ShareType.GROUP.value, + shareType = ShareType.GROUP, shareWith = "userName", path = "/Texts/text2.txt" ) @@ -369,19 +386,21 @@ class OCShareDaoTest { } private fun createDefaultPrivateShareEntity( - shareType: Int = 0, + shareType: ShareType = ShareType.USER, shareWith: String = "username", path: String = "/Texts/text1.txt", permissions: Int = -1, shareWithDisplayName: String = "Steve" - ) = DataTestUtil.createPrivateShareEntity( - shareType = shareType, - shareWith = shareWith, - path = path, - permissions = permissions, - isFolder = false, - sharedWithDisplayName = shareWithDisplayName - ) + ) = ocShareMapper.toEntity( + OC_PRIVATE_SHARE.copy( + shareType = shareType, + shareWith = shareWith, + path = path, + permissions = permissions, + isFolder = false, + sharedWithDisplayName = shareWithDisplayName + ) + )!! /****************************************************************************************************** ******************************************* PUBLIC SHARES ******************************************** @@ -498,11 +517,13 @@ class OCShareDaoTest { path: String = "/Texts/text1.txt", expirationDate: Long = 1000, name: String = "Text 1 link" - ) = DataTestUtil.createPublicShareEntity( - path = path, - expirationDate = expirationDate, - isFolder = false, - name = name, - shareLink = "http://server:port/s/1" - ) + ) = ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( + path = path, + expirationDate = expirationDate, + isFolder = false, + name = name, + shareLink = "http://server:port/s/1" + ) + )!! } diff --git a/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt b/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt index 58116d0ad14..a2b181e2fcb 100644 --- a/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt +++ b/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt @@ -20,240 +20,13 @@ package com.owncloud.android.data.utils -import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType -import com.owncloud.android.domain.capabilities.model.OCCapability -import com.owncloud.android.domain.sharing.shares.model.OCShare -import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation -import com.owncloud.android.lib.resources.shares.RemoteShare -import com.owncloud.android.lib.resources.shares.ShareType as RemoteShareType -import com.owncloud.android.lib.resources.status.CapabilityBooleanType as RemoteCapabilityBooleanType -import com.owncloud.android.lib.resources.status.RemoteCapability import io.mockk.every import io.mockk.mockk import org.json.JSONObject object DataTestUtil { - - val DUMMY_REMOTE_SHARE = - RemoteShare().apply { - fileSource = 7 - itemSource = 7 - shareType = RemoteShareType.USER - shareWith = "" - path = "/Photos/image.jpg" - permissions = 1 - sharedDate = 1542628397 - expirationDate = 0 - token = "AnyToken" - sharedWithDisplayName = "" - isFolder = false - userId = -1 - id = 1 - name = "" - shareLink = "" - } - - fun createShare( - fileSource: Long = 7, - itemSource: Long = 7, - shareType: Int, // Public share by default - shareWith: String = "", - path: String, - permissions: Int = 1, - sharedDate: Long = 1542628397, - expirationDate: Long = 0, - token: String = "pwdasd12dasdWZ", - sharedWithDisplayName: String = "", - sharedWithAdditionalInfo: String = "", - isFolder: Boolean, - userId: Long = -1, - remoteId: Long = 1, - accountOwner: String = "admin@server", - name: String = "", - shareLink: String = "" - ) = OCShare( - 0, - fileSource, - itemSource, - ShareType.fromValue(shareType)!!, - shareWith, - path, - permissions, - sharedDate, - expirationDate, - token, - sharedWithDisplayName, - sharedWithAdditionalInfo, - isFolder, - userId, - remoteId, - accountOwner, - name, - shareLink - ) - - fun createShareEntity( - fileSource: Long = 7, - itemSource: Long = 7, - shareType: Int, // Public share by default - shareWith: String = "", - path: String, - permissions: Int = 1, - sharedDate: Long = 1542628397, - expirationDate: Long = 0, - token: String = "pwdasd12dasdWZ", - sharedWithDisplayName: String = "", - sharedWithAdditionalInfo: String = "", - isFolder: Boolean, - userId: Long = -1, - remoteId: Long = 1, - accountOwner: String = "admin@server", - name: String = "", - shareLink: String = "" - ) = OCShareEntity( - fileSource, - itemSource, - shareType, - shareWith, - path, - permissions, - sharedDate, - expirationDate, - token, - sharedWithDisplayName, - sharedWithAdditionalInfo, - isFolder, - userId, - remoteId, - accountOwner, - name, - shareLink - ) - - fun createPrivateShare( - remoteId: Long = 1, - shareType: Int = 0, - shareWith: String = "whoever", - path: String = "/Photos/image.jpg", - permissions: Int = -1, - isFolder: Boolean = false, - sharedWithDisplayName: String = "whatever", - accountOwner: String = "admin@server" - ) = createShare( - remoteId = remoteId, - shareType = shareType, - shareWith = shareWith, - path = path, - permissions = permissions, - isFolder = isFolder, - sharedWithDisplayName = sharedWithDisplayName, - accountOwner = accountOwner - ) - - fun createPrivateShareEntity( - remoteId: Long = 1, - shareType: Int = 0, - shareWith: String, - path: String, - permissions: Int = -1, - isFolder: Boolean, - sharedWithDisplayName: String, - accountOwner: String = "admin@server" - ) = createShareEntity( - remoteId = remoteId, - shareType = shareType, - shareWith = shareWith, - path = path, - permissions = permissions, - isFolder = isFolder, - sharedWithDisplayName = sharedWithDisplayName, - accountOwner = accountOwner - ) - - fun createPublicShare( - shareWith: String = "", - path: String = "/Photos/image.jpg", - expirationDate: Long = 1000, - isFolder: Boolean = false, - permissions: Int = 1, - remoteId: Long = 1, - accountOwner: String = "admin@server", - name: String = "Image link", - shareLink: String = "link" - ) = createShare( - shareWith = shareWith, - shareType = 3, - path = path, - permissions = permissions, - expirationDate = expirationDate, - isFolder = isFolder, - remoteId = remoteId, - accountOwner = accountOwner, - name = name, - shareLink = shareLink - ) - - fun createPublicShareEntity( - shareWith: String = "", - path: String, - expirationDate: Long = 1000, - isFolder: Boolean, - permissions: Int = 1, - remoteId: Long = 1, - accountOwner: String = "admin@server", - name: String, - shareLink: String - ) = createShareEntity( - shareWith = shareWith, - shareType = 3, - path = path, - permissions = permissions, - expirationDate = expirationDate, - isFolder = isFolder, - remoteId = remoteId, - accountOwner = accountOwner, - name = name, - shareLink = shareLink - ) - - fun createRemoteShare( - fileSource: Long = 7, - itemSource: Long = 7, - shareType: Int, // Public share by default - shareWith: String = "", - path: String, - permissions: Int = 1, - sharedDate: Long = 1542628397, - expirationDate: Long = 0, - token: String = "pwdasd12dasdWZ", - sharedWithDisplayName: String = "", - isFolder: Boolean, - userId: Long = -1, - remoteId: Long = 1, - name: String = "", - shareLink: String = "" - ): RemoteShare = RemoteShare().also { - it.fileSource = fileSource - it.itemSource = itemSource - it.shareType = RemoteShareType.fromValue(shareType) - it.shareWith = shareWith - it.path = path - it.permissions = permissions - it.sharedDate = sharedDate - it.expirationDate = expirationDate - it.token = token - it.sharedWithDisplayName = sharedWithDisplayName - it.isFolder = isFolder - it.userId = userId - it.id = remoteId - it.name = name - it.shareLink = shareLink - } - /** * Sharees */ @@ -277,223 +50,6 @@ object DataTestUtil { return jsonObject } - /** - * Capability - */ - val DUMMY_REMOTE_CAPABILITY = - RemoteCapability().apply { - accountName = "user@server" - versionMayor = 2 - versionMinor = 1 - versionMicro = 0 - versionString = "1.0.0" - versionEdition = "1.0.0" - corePollinterval = 0 - filesSharingApiEnabled = RemoteCapabilityBooleanType.TRUE - filesSharingSearchMinLength = 3 - filesSharingPublicEnabled = RemoteCapabilityBooleanType.TRUE - filesSharingPublicPasswordEnforced = RemoteCapabilityBooleanType.FALSE - filesSharingPublicPasswordEnforcedReadOnly = RemoteCapabilityBooleanType.FALSE - filesSharingPublicPasswordEnforcedReadWrite = RemoteCapabilityBooleanType.FALSE - filesSharingPublicPasswordEnforcedUploadOnly = RemoteCapabilityBooleanType.FALSE - filesSharingPublicExpireDateEnabled = RemoteCapabilityBooleanType.FALSE - filesSharingPublicExpireDateDays = 0 - filesSharingPublicExpireDateEnforced = RemoteCapabilityBooleanType.FALSE - filesSharingPublicSendMail = RemoteCapabilityBooleanType.FALSE - filesSharingPublicUpload = RemoteCapabilityBooleanType.FALSE - filesSharingPublicMultiple = RemoteCapabilityBooleanType.FALSE - filesSharingPublicSupportsUploadOnly = RemoteCapabilityBooleanType.FALSE - filesSharingUserSendMail = RemoteCapabilityBooleanType.FALSE - filesSharingResharing = RemoteCapabilityBooleanType.FALSE - filesSharingFederationOutgoing = RemoteCapabilityBooleanType.FALSE - filesSharingFederationIncoming = RemoteCapabilityBooleanType.FALSE - filesBigFileChunking = RemoteCapabilityBooleanType.FALSE - filesUndelete = RemoteCapabilityBooleanType.FALSE - filesVersioning = RemoteCapabilityBooleanType.FALSE - } - - fun createCapability( - accountName: String = "user@server", - versionMayor: Int = 2, - versionMinor: Int = 1, - versionMicro: Int = 0, - versionString: String = "1.0.0", - versionEdition: String = "1.0.0", - corePollinterval: Int = 0, - sharingApiEnabled: CapabilityBooleanType = CapabilityBooleanType.TRUE, - sharingSearchMinLength: Int = 0, - sharingPublicEnabled: CapabilityBooleanType = CapabilityBooleanType.TRUE, - sharingPublicPasswordEnforced: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingPublicPasswordEnforcedReadOnly: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingPublicPasswordEnforcedReadWrite: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingPublicPasswordEnforcedUploadOnly: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingPublicExpireDateEnabled: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingPublicExpireDateDays: Int = 0, - sharingPublicExpireDateEnforced: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingPublicSendMail: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingPublicUpload: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingPublicMultiple: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingPublicSupportsUploadOnly: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingUserSendMail: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingResharing: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingFederationOutgoing: CapabilityBooleanType = CapabilityBooleanType.FALSE, - sharingFederationIncoming: CapabilityBooleanType = CapabilityBooleanType.FALSE, - filesBigFileChunking: CapabilityBooleanType = CapabilityBooleanType.FALSE, - filesUndelete: CapabilityBooleanType = CapabilityBooleanType.FALSE, - filesVersioning: CapabilityBooleanType = CapabilityBooleanType.FALSE - ) = OCCapability( - 0, - accountName, - versionMayor, - versionMinor, - versionMicro, - versionString, - versionEdition, - corePollinterval, - sharingApiEnabled, - sharingSearchMinLength, - sharingPublicEnabled, - sharingPublicPasswordEnforced, - sharingPublicPasswordEnforcedReadOnly, - sharingPublicPasswordEnforcedReadWrite, - sharingPublicPasswordEnforcedUploadOnly, - sharingPublicExpireDateEnabled, - sharingPublicExpireDateDays, - sharingPublicExpireDateEnforced, - sharingPublicSendMail, - sharingPublicUpload, - sharingPublicMultiple, - sharingPublicSupportsUploadOnly, - sharingUserSendMail, - sharingResharing, - sharingFederationOutgoing, - sharingFederationIncoming, - filesBigFileChunking, - filesUndelete, - filesVersioning - ) - - fun createCapabilityEntity( - accountName: String = "user@server", - versionMayor: Int = 2, - versionMinor: Int = 1, - versionMicro: Int = 0, - versionString: String = "1.0.0", - versionEdition: String = "1.0.0", - corePollinterval: Int = 0, - sharingApiEnabled: Int = 1, - sharingSearchMinLength: Int = 0, - sharingPublicEnabled: Int = 1, - sharingPublicPasswordEnforced: Int = 0, - sharingPublicPasswordEnforcedReadOnly: Int = 0, - sharingPublicPasswordEnforcedReadWrite: Int = 0, - sharingPublicPasswordEnforcedUploadOnly: Int = 0, - sharingPublicExpireDateEnabled: Int = 0, - sharingPublicExpireDateDays: Int = 0, - sharingPublicExpireDateEnforced: Int = 0, - sharingPublicSendMail: Int = 0, - sharingPublicUpload: Int = 0, - sharingPublicMultiple: Int = 0, - sharingPublicSupportsUploadOnly: Int = 0, - sharingUserSendMail: Int = 0, - sharingResharing: Int = 0, - sharingFederationOutgoing: Int = 0, - sharingFederationIncoming: Int = 0, - filesBigFileChunking: Int = 0, - filesUndelete: Int = 0, - filesVersioning: Int = 0 - ) = OCCapabilityEntity( - accountName, - versionMayor, - versionMinor, - versionMicro, - versionString, - versionEdition, - corePollinterval, - sharingApiEnabled, - sharingSearchMinLength, - sharingPublicEnabled, - sharingPublicPasswordEnforced, - sharingPublicPasswordEnforcedReadOnly, - sharingPublicPasswordEnforcedReadWrite, - sharingPublicPasswordEnforcedUploadOnly, - sharingPublicExpireDateEnabled, - sharingPublicExpireDateDays, - sharingPublicExpireDateEnforced, - sharingPublicSendMail, - sharingPublicUpload, - sharingPublicMultiple, - sharingPublicSupportsUploadOnly, - sharingUserSendMail, - sharingResharing, - sharingFederationOutgoing, - sharingFederationIncoming, - filesBigFileChunking, - filesUndelete, - filesVersioning - ) - - fun createRemoteCapability( - accountName: String = "user@server", - versionMayor: Int = 2, - versionMinor: Int = 1, - versionMicro: Int = 0, - versionString: String = "1.0.0", - versionEdition: String = "1.0.0", - corePollinterval: Int = 0, - sharingApiEnabled: Int = 0, - sharingPublicEnabled: Int = 1, - sharingPublicPasswordEnforced: Int = 0, - sharingPublicPasswordEnforcedReadOnly: Int = 0, - sharingPublicPasswordEnforcedReadWrite: Int = 0, - sharingPublicPasswordEnforcedUploadOnly: Int = 0, - sharingPublicExpireDateEnabled: Int = 0, - sharingPublicExpireDateDays: Int = 0, - sharingPublicExpireDateEnforced: Int = 0, - sharingPublicSendMail: Int = 0, - sharingPublicUpload: Int = 0, - sharingPublicMultiple: Int = 0, - sharingPublicSupportsUploadOnly: Int = 0, - sharingUserSendMail: Int = 0, - sharingResharing: Int = 0, - sharingFederationOutgoing: Int = 0, - sharingFederationIncoming: Int = 0, - filesBigFileChunking: Int = 0, - filesUndelete: Int = 0, - filesVersioning: Int = 0 - ): RemoteCapability = RemoteCapability().apply { - this.accountName = accountName - this.versionMayor = versionMayor - this.versionMinor = versionMinor - this.versionMicro = versionMicro - this.versionString = versionString - this.versionEdition = versionEdition - this.corePollinterval = corePollinterval - filesSharingApiEnabled = RemoteCapabilityBooleanType.fromValue(sharingApiEnabled)!! - filesSharingPublicEnabled = RemoteCapabilityBooleanType.fromValue(sharingPublicEnabled)!! - filesSharingPublicPasswordEnforced = RemoteCapabilityBooleanType.fromValue(sharingPublicPasswordEnforced)!! - filesSharingPublicPasswordEnforcedReadOnly = - RemoteCapabilityBooleanType.fromValue(sharingPublicPasswordEnforcedReadOnly)!! - filesSharingPublicPasswordEnforcedReadWrite = - RemoteCapabilityBooleanType.fromValue(sharingPublicPasswordEnforcedReadWrite)!! - filesSharingPublicPasswordEnforcedUploadOnly = - RemoteCapabilityBooleanType.fromValue(sharingPublicPasswordEnforcedUploadOnly)!! - filesSharingPublicExpireDateEnabled = RemoteCapabilityBooleanType.fromValue(sharingPublicExpireDateEnabled)!! - filesSharingPublicExpireDateDays = sharingPublicExpireDateDays - filesSharingPublicExpireDateEnforced = RemoteCapabilityBooleanType.fromValue(sharingPublicExpireDateEnforced)!! - filesSharingPublicSendMail = RemoteCapabilityBooleanType.fromValue(sharingPublicSendMail)!! - filesSharingPublicUpload = RemoteCapabilityBooleanType.fromValue(sharingPublicUpload)!! - filesSharingPublicMultiple = RemoteCapabilityBooleanType.fromValue(sharingPublicMultiple)!! - filesSharingPublicSupportsUploadOnly = RemoteCapabilityBooleanType.fromValue(sharingPublicSupportsUploadOnly)!! - filesSharingUserSendMail = RemoteCapabilityBooleanType.fromValue(sharingUserSendMail)!! - filesSharingResharing = RemoteCapabilityBooleanType.fromValue(sharingResharing)!! - filesSharingFederationOutgoing = RemoteCapabilityBooleanType.fromValue(sharingFederationOutgoing)!! - filesSharingFederationIncoming = RemoteCapabilityBooleanType.fromValue(sharingFederationIncoming)!! - this.filesBigFileChunking = RemoteCapabilityBooleanType.fromValue(filesBigFileChunking)!! - this.filesUndelete = RemoteCapabilityBooleanType.fromValue(filesUndelete)!! - this.filesVersioning = RemoteCapabilityBooleanType.fromValue(filesVersioning)!! - } - fun createRemoteOperationResultMock( data: T, isSuccess: Boolean, diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt index 9a28392db7e..41449901355 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt @@ -24,6 +24,8 @@ import com.owncloud.android.data.capabilities.datasources.implementation.OCRemot import com.owncloud.android.data.capabilities.network.OCCapabilityService import com.owncloud.android.data.capabilities.datasources.mapper.RemoteCapabilityMapper import com.owncloud.android.data.utils.DataTestUtil +import com.owncloud.android.testutil.OC_ACCOUNT_NAME +import com.owncloud.android.testutil.OC_CAPABILITY import io.mockk.every import io.mockk.mockk import org.hamcrest.CoreMatchers.notNullValue @@ -36,8 +38,7 @@ class OCRemoteCapabilitiesDataSourceTest { private lateinit var ocRemoteCapabilitiesDataSource: OCRemoteCapabilitiesDataSource private val ocCapabilityService: OCCapabilityService = mockk() - private val remoteCapabilityMapper = - RemoteCapabilityMapper() + private val remoteCapabilityMapper = RemoteCapabilityMapper() @Before fun init() { @@ -50,11 +51,9 @@ class OCRemoteCapabilitiesDataSourceTest { @Test fun readRemoteCapabilities() { - val accountName = "ceo@server" + val accountName = OC_ACCOUNT_NAME - val remoteCapability = DataTestUtil.createRemoteCapability( - accountName, 15, 14, 13 - ) + val remoteCapability = remoteCapabilityMapper.toRemote(OC_CAPABILITY) val getRemoteCapabilitiesOperationResult = DataTestUtil.createRemoteOperationResultMock( remoteCapability, @@ -70,9 +69,9 @@ class OCRemoteCapabilitiesDataSourceTest { assertThat(capabilities, notNullValue()) - assertEquals("ceo@server", capabilities.accountName) - assertEquals(15, capabilities.versionMayor) - assertEquals(14, capabilities.versionMinor) - assertEquals(13, capabilities.versionMicro) + assertEquals(OC_CAPABILITY.accountName, capabilities.accountName) + assertEquals(OC_CAPABILITY.versionMayor, capabilities.versionMayor) + assertEquals(OC_CAPABILITY.versionMinor, capabilities.versionMinor) + assertEquals(OC_CAPABILITY.versionMicro, capabilities.versionMicro) } } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt index 060e256ed69..1bd7826e7a9 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt @@ -19,8 +19,7 @@ package com.owncloud.android.data.capabilities.datasources.mapper -import com.owncloud.android.data.utils.DataTestUtil.createCapability -import com.owncloud.android.data.utils.DataTestUtil.createCapabilityEntity +import com.owncloud.android.testutil.OC_CAPABILITY import org.junit.Assert import org.junit.Test @@ -28,8 +27,8 @@ class OCCapabilityMapperTest { private val ocCapabilityMapper = OCCapabilityMapper() - private val ocCapability = createCapability() - private val ocCapabilityEntity = createCapabilityEntity() + private val ocCapability = OC_CAPABILITY + private val ocCapabilityEntity = ocCapabilityMapper.toEntity(ocCapability) @Test fun checkToModelNull() { diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt index cbfb1a4749d..186803320e1 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCRemoteCapabilityMapperTest.kt @@ -19,7 +19,6 @@ package com.owncloud.android.data.capabilities.datasources.mapper -import com.owncloud.android.data.utils.DataTestUtil.DUMMY_REMOTE_CAPABILITY import com.owncloud.android.testutil.OC_CAPABILITY import org.junit.Assert import org.junit.Test @@ -35,9 +34,10 @@ class OCRemoteCapabilityMapperTest { @Test fun checkToModelNotNull() { - Assert.assertNotNull(DUMMY_REMOTE_CAPABILITY) + val remoteCapability = ocRemoteCapabilityMapper.toRemote(OC_CAPABILITY) + Assert.assertNotNull(remoteCapability) - val capability = ocRemoteCapabilityMapper.toModel(DUMMY_REMOTE_CAPABILITY) + val capability = ocRemoteCapabilityMapper.toModel(remoteCapability) Assert.assertNotNull(capability) Assert.assertEquals(capability, OC_CAPABILITY) } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt index b877975e3f5..5d402a46fdd 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt @@ -26,9 +26,10 @@ import com.owncloud.android.data.sharing.shares.datasources.implementation.OCLoc import com.owncloud.android.data.sharing.shares.datasources.mapper.OCShareMapper import com.owncloud.android.data.sharing.shares.db.OCShareDao import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.data.utils.DataTestUtil import com.owncloud.android.data.utils.LiveDataTestUtil.getValue import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.testutil.OC_PRIVATE_SHARE +import com.owncloud.android.testutil.OC_PUBLIC_SHARE import io.mockk.every import io.mockk.mockkClass import org.junit.Assert.assertEquals @@ -39,6 +40,7 @@ import org.junit.Test class OCLocalDataSourceTest { private lateinit var ocLocalSharesDataSource: OCLocalShareDataSource private val ocSharesDao = mockkClass(OCShareDao::class) + private val ocShareMapper = OCShareMapper() @Rule @JvmField @@ -55,7 +57,7 @@ class OCLocalDataSourceTest { ocLocalSharesDataSource = OCLocalShareDataSource( ocSharesDao, - OCShareMapper() + ocShareMapper ) } @@ -64,18 +66,20 @@ class OCLocalDataSourceTest { ******************************************************************************************************/ private val privateShares = listOf( - DataTestUtil.createPrivateShareEntity( - path = "/Docs/doc1.doc", - isFolder = false, - shareWith = "username", - sharedWithDisplayName = "Sophie" - ), - DataTestUtil.createPrivateShareEntity( - path = "/Docs/doc1.doc", - isFolder = false, - shareWith = "user.name", - sharedWithDisplayName = "Nicole" - ) + ocShareMapper.toEntity( + OC_PRIVATE_SHARE.copy( + path = "/Docs/doc1.doc", + shareWith = "username", + sharedWithDisplayName = "Sophie" + ) + )!!, + ocShareMapper.toEntity( + OC_PRIVATE_SHARE.copy( + path = "/Docs/doc1.doc", + shareWith = "user.name", + sharedWithDisplayName = "Nicole" + ) + )!! ) private val privateShareTypes = listOf( @@ -145,10 +149,8 @@ class OCLocalDataSourceTest { } returns 10 val insertedShareId = ocLocalSharesDataSource.insert( - DataTestUtil.createPrivateShare( - shareType = ShareType.USER.value, + OC_PRIVATE_SHARE.copy( path = "/Docs/doc1.doc", - isFolder = false, shareWith = "username", sharedWithDisplayName = "Sophie" ) @@ -168,10 +170,8 @@ class OCLocalDataSourceTest { } returns 3 val updatedShareId = ocLocalSharesDataSource.update( - DataTestUtil.createPrivateShare( - shareType = ShareType.USER.value, + OC_PRIVATE_SHARE.copy( path = "/Docs/doc1.doc", - isFolder = false, shareWith = "user.name", sharedWithDisplayName = "Nicole" ) @@ -183,19 +183,21 @@ class OCLocalDataSourceTest { ******************************************* PUBLIC SHARES ******************************************** ******************************************************************************************************/ - val publicShares = listOf( - DataTestUtil.createPublicShareEntity( + private val publicShares = listOf( + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( path = "/Photos/", isFolder = true, name = "Photos link", shareLink = "http://server:port/s/1" - ), - DataTestUtil.createPublicShareEntity( + ))!!, + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( path = "/Photos/", isFolder = true, name = "Photos link 2", shareLink = "http://server:port/s/2" - ) + ))!! ) @Test @@ -240,7 +242,7 @@ class OCLocalDataSourceTest { } returns 7 val insertedShareId = ocLocalSharesDataSource.insert( - DataTestUtil.createPublicShare( + OC_PUBLIC_SHARE.copy( path = "/Photos/", isFolder = true, name = "Photos link", @@ -262,7 +264,7 @@ class OCLocalDataSourceTest { } returns 8 val updatedShareId = ocLocalSharesDataSource.update( - DataTestUtil.createPublicShare( + OC_PUBLIC_SHARE.copy( path = "/Photos/", isFolder = true, name = "Photos link 2", diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt index e575e9bee00..4080fe3775f 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt @@ -29,6 +29,7 @@ import com.owncloud.android.domain.exceptions.ShareNotFoundException import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.shares.ShareParserResult +import com.owncloud.android.testutil.OC_SHARE import io.mockk.every import io.mockk.mockk import org.hamcrest.CoreMatchers.notNullValue @@ -56,14 +57,16 @@ class OCRemoteShareDataSourceTest { fun insertPrivateShare() { val createRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( ShareParserResult( - arrayListOf( - DataTestUtil.createRemoteShare( - shareType = ShareType.USER.value, - path = "Photos/", - isFolder = true, - shareWith = "user", - sharedWithDisplayName = "User" - ) + listOf( + remoteShareMapper.toRemote( + OC_SHARE.copy( + shareType = ShareType.USER, + path = "Photos/", + isFolder = true, + shareWith = "user", + sharedWithDisplayName = "User" + ) + )!! ) ), true @@ -95,16 +98,17 @@ class OCRemoteShareDataSourceTest { fun updatePrivateShare() { val updateRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( ShareParserResult( - arrayListOf( - DataTestUtil.createRemoteShare( - shareType = ShareType.USER.value, - path = "Images/image_1.mp4", - shareWith = "user", - sharedWithDisplayName = "User", - permissions = 17, - isFolder = false, - remoteId = 3 - ) + listOf( + remoteShareMapper.toRemote( + OC_SHARE.copy( + shareType = ShareType.USER, + path = "Images/image_1.mp4", + shareWith = "user", + sharedWithDisplayName = "User", + permissions = 17, + remoteId = 3 + ) + )!! ) ), true @@ -138,14 +142,15 @@ class OCRemoteShareDataSourceTest { fun insertPublicShare() { val createRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( ShareParserResult( - arrayListOf( - DataTestUtil.createRemoteShare( - shareType = ShareType.PUBLIC_LINK.value, - path = "Photos/img1.png", - isFolder = false, - name = "img1 link", - shareLink = "http://server:port/s/112ejbhdasyd1" - ) + listOf( + remoteShareMapper.toRemote( + OC_SHARE.copy( + shareType = ShareType.PUBLIC_LINK, + path = "Photos/img1.png", + name = "img1 link", + shareLink = "http://server:port/s/112ejbhdasyd1" + ) + )!! ) ), true @@ -178,16 +183,17 @@ class OCRemoteShareDataSourceTest { fun updatePublicShare() { val updateRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( ShareParserResult( - arrayListOf( - DataTestUtil.createRemoteShare( - shareType = ShareType.PUBLIC_LINK.value, - path = "Videos/video1.mp4", - expirationDate = 2000, - isFolder = false, - remoteId = 3, - name = "video1 link updated", - shareLink = "http://server:port/s/1275farv" - ) + listOf( + remoteShareMapper.toRemote( + OC_SHARE.copy( + shareType = ShareType.PUBLIC_LINK, + path = "Videos/video1.mp4", + expirationDate = 2000, + remoteId = 3, + name = "video1 link updated", + shareLink = "http://server:port/s/1275farv" + ) + )!! ) ), true @@ -220,35 +226,39 @@ class OCRemoteShareDataSourceTest { @Test fun readRemoteShares() { - val remoteShares = arrayListOf( - DataTestUtil.createRemoteShare( - shareType = ShareType.PUBLIC_LINK.value, - path = "/Documents/doc", - isFolder = false, - name = "Doc link", - shareLink = "http://server:port/s/1" - ), - DataTestUtil.createRemoteShare( - shareType = ShareType.PUBLIC_LINK.value, - path = "/Documents/doc", - isFolder = false, - name = "Doc link 2", - shareLink = "http://server:port/s/2" - ), - DataTestUtil.createRemoteShare( - shareType = ShareType.USER.value, - path = "/Documents/doc", - isFolder = false, - shareWith = "steve", - sharedWithDisplayName = "Steve" - ), - DataTestUtil.createRemoteShare( - shareType = ShareType.GROUP.value, - path = "/Documents/doc", - isFolder = false, - shareWith = "family", - sharedWithDisplayName = "My family" - ) + val remoteShares = listOf( + remoteShareMapper.toRemote( + OC_SHARE.copy( + shareType = ShareType.PUBLIC_LINK, + path = "/Documents/doc", + name = "Doc link", + shareLink = "http://server:port/s/1" + ) + )!!, + remoteShareMapper.toRemote( + OC_SHARE.copy( + shareType = ShareType.PUBLIC_LINK, + path = "/Documents/doc", + name = "Doc link 2", + shareLink = "http://server:port/s/2" + ) + )!!, + remoteShareMapper.toRemote( + OC_SHARE.copy( + shareType = ShareType.USER, + path = "/Documents/doc", + shareWith = "steve", + sharedWithDisplayName = "Steve" + ) + )!!, + remoteShareMapper.toRemote( + OC_SHARE.copy( + shareType = ShareType.GROUP, + path = "/Documents/doc", + shareWith = "family", + sharedWithDisplayName = "My family" + ) + )!! ) val getRemoteSharesOperationResult = DataTestUtil.createRemoteOperationResultMock( diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt index bcfa655e9be..211e3a447fd 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt @@ -20,7 +20,6 @@ package com.owncloud.android.data.shares.datasources.mapper import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteShareMapper -import com.owncloud.android.data.utils.DataTestUtil.DUMMY_REMOTE_SHARE import com.owncloud.android.testutil.OC_SHARE import org.junit.Assert import org.junit.Test @@ -36,10 +35,11 @@ class OCRemoteShareMapperTest { @Test fun checkToModelNotNull() { - Assert.assertNotNull(DUMMY_REMOTE_SHARE) + val remoteShare = ocRemoteShareMapper.toRemote(OC_SHARE) + Assert.assertNotNull(remoteShare) - val capability = ocRemoteShareMapper.toModel(DUMMY_REMOTE_SHARE) - Assert.assertNotNull(capability) - Assert.assertEquals(capability, OC_SHARE.copy(accountOwner = "")) + val share = ocRemoteShareMapper.toModel(remoteShare) + Assert.assertNotNull(share) + Assert.assertEquals(OC_SHARE, share) } } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt index cbde8191936..68d55ea34c7 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt @@ -20,8 +20,7 @@ package com.owncloud.android.data.shares.datasources.mapper import com.owncloud.android.data.sharing.shares.datasources.mapper.OCShareMapper -import com.owncloud.android.data.utils.DataTestUtil.createShare -import com.owncloud.android.data.utils.DataTestUtil.createShareEntity +import com.owncloud.android.testutil.OC_SHARE import org.junit.Assert import org.junit.Test @@ -29,17 +28,17 @@ class OCShareMapperTest { private val ocShareMapper = OCShareMapper() private val ocShare = - createShare( + OC_SHARE.copy( isFolder = false, - path = "/Photos/image2.jpg", - shareType = 0 + path = "/Photos/image2.jpg" ) private val ocShareEntity = - createShareEntity( - isFolder = false, - path = "/Photos/image2.jpg", - shareType = 0 + ocShareMapper.toEntity( + OC_SHARE.copy( + isFolder = false, + path = "/Photos/image2.jpg" + ) ) @Test diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt index d90f3ad886e..df7d739d72a 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt @@ -24,11 +24,12 @@ import androidx.lifecycle.MutableLiveData import com.owncloud.android.data.sharing.shares.datasources.LocalShareDataSource import com.owncloud.android.data.sharing.shares.datasources.RemoteShareDataSource import com.owncloud.android.data.sharing.shares.repository.OCShareRepository -import com.owncloud.android.data.utils.DataTestUtil import com.owncloud.android.domain.exceptions.FileNotFoundException import com.owncloud.android.domain.exceptions.NoConnectionWithServerException import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType +import com.owncloud.android.testutil.OC_PRIVATE_SHARE +import com.owncloud.android.testutil.OC_PUBLIC_SHARE import io.mockk.every import io.mockk.mockk import io.mockk.verify @@ -50,10 +51,10 @@ class OCShareRepositoryTest { OCShareRepository(localShareDataSource, remoteShareDataSource) private val shares = arrayListOf( - DataTestUtil.createPublicShare(), - DataTestUtil.createPrivateShare(), - DataTestUtil.createPrivateShare(), - DataTestUtil.createPublicShare() + OC_PUBLIC_SHARE, + OC_PRIVATE_SHARE, + OC_PRIVATE_SHARE, + OC_PUBLIC_SHARE ) private val filePath = "/Images" @@ -368,7 +369,7 @@ class OCShareRepositoryTest { any(), any() ) - } returns shares.get(2) + } returns shares[2] ocShareRepository.insertPrivateShare( filePath, @@ -388,7 +389,7 @@ class OCShareRepositoryTest { ) } - verify(exactly = 1) { localShareDataSource.insert(shares.get(2)) } + verify(exactly = 1) { localShareDataSource.insert(shares[2]) } } @Test(expected = FileNotFoundException::class) @@ -426,7 +427,7 @@ class OCShareRepositoryTest { } verify(exactly = 0) { - localShareDataSource.insert(shares.get(2)) + localShareDataSource.insert(shares[2]) } } @@ -442,7 +443,7 @@ class OCShareRepositoryTest { any(), any() ) - } returns shares.get(2) + } returns shares[2] ocShareRepository.updatePrivateShare( 1, @@ -458,7 +459,7 @@ class OCShareRepositoryTest { ) } - verify(exactly = 1) { localShareDataSource.update(shares.get(2)) } + verify(exactly = 1) { localShareDataSource.update(shares[2]) } } @Test(expected = FileNotFoundException::class) @@ -489,7 +490,7 @@ class OCShareRepositoryTest { ) } - verify(exactly = 0) { localShareDataSource.update(shares.get(2)) } + verify(exactly = 0) { localShareDataSource.update(shares[2]) } } @Test diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt index 722af1b595d..2eee756af03 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt @@ -22,3 +22,16 @@ val OC_SHARE = OCShare( name = "", shareLink = "" ) + +val OC_PRIVATE_SHARE = OC_SHARE.copy( + shareWith = "WhoEver", + permissions = -1, + sharedWithDisplayName = "anyDisplayName" +) + +val OC_PUBLIC_SHARE = OC_SHARE.copy( + shareType = ShareType.PUBLIC_LINK, + expirationDate = 1000, + name = "Image link", + shareLink = "link" +) From 91e1330d8c1010d78b15b879e38630ac25b9f084 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Tue, 26 Nov 2019 14:10:20 +0100 Subject: [PATCH 27/41] Fix ViewModels tests --- build.gradle | 1 + owncloudApp/build.gradle | 4 +- .../dependecyinjection/CommonModule.kt | 3 + .../dependecyinjection/ViewModelModule.kt | 4 +- .../capabilities/OCCapabilityViewModel.kt | 16 +- .../viewmodels/sharing/OCShareViewModel.kt | 69 ++-- .../providers/CoroutinesDispatcherProvider.kt | 31 ++ .../OCCapabilityViewModelTest.kt | 115 +++--- .../sharing}/OCShareViewModelTest.kt | 373 +++++++----------- .../android/testutil/livedata/LiveData.kt | 48 --- .../testutil/livedata/LiveDataUtils.kt | 54 +++ 11 files changed, 320 insertions(+), 398 deletions(-) create mode 100644 owncloudApp/src/main/java/com/owncloud/android/providers/CoroutinesDispatcherProvider.kt rename owncloudApp/src/{androidTest/java/com/owncloud/android/capabilities/viewmodels => test/java/com/owncloud/android/presentation/viewmodels/capabilities}/OCCapabilityViewModelTest.kt (67%) rename owncloudApp/src/{androidTest/java/com/owncloud/android/sharing/shares/viewmodels => test/java/com/owncloud/android/presentation/viewmodels/sharing}/OCShareViewModelTest.kt (57%) delete mode 100644 owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveData.kt create mode 100644 owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveDataUtils.kt diff --git a/build.gradle b/build.gradle index b1eec5201e0..57e5b56c10d 100644 --- a/build.gradle +++ b/build.gradle @@ -9,6 +9,7 @@ buildscript { // Kotlin kotlinVersion = "1.3.50" + coroutinesVersion = "1.3.2" // Koin koinVersion = "2.0.1" diff --git a/owncloudApp/build.gradle b/owncloudApp/build.gradle index 2a7c193bd1b..82bf588a669 100644 --- a/owncloudApp/build.gradle +++ b/owncloudApp/build.gradle @@ -11,7 +11,6 @@ dependencies { /// data and domain modules implementation project(':owncloudDomain') implementation project(':owncloudData') - androidTestImplementation project(':owncloudTestUtil') /// dependencies for app building implementation "androidx.legacy:legacy-support-v4:$androidX" @@ -27,11 +26,14 @@ dependencies { implementation 'commons-io:commons-io:2.6' // Tests + testImplementation project(':owncloudTestUtil') testImplementation "junit:junit:$junitVersion" testImplementation "androidx.arch.core:core-testing:$archLifecycleVersion" testImplementation "io.mockk:mockk:$mockkVersion" + testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion" // Instrumented tests + androidTestImplementation project(':owncloudTestUtil') androidTestImplementation "androidx.test:core:$androidTestVersion" androidTestImplementation "androidx.test:rules:$androidTestVersion" androidTestImplementation "androidx.test:runner:$androidTestVersion" diff --git a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/CommonModule.kt b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/CommonModule.kt index cb611cee2a5..1f0f31f8af3 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/CommonModule.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/CommonModule.kt @@ -23,6 +23,7 @@ import com.owncloud.android.data.capabilities.datasources.mapper.OCCapabilityMap import com.owncloud.android.data.sharing.shares.datasources.mapper.OCShareMapper import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteShareMapper import com.owncloud.android.data.capabilities.datasources.mapper.RemoteCapabilityMapper +import com.owncloud.android.providers.CoroutinesDispatcherProvider import org.koin.dsl.module val commonModule = module { @@ -31,4 +32,6 @@ val commonModule = module { factory { RemoteCapabilityMapper() } factory { RemoteShareMapper() } + + single { CoroutinesDispatcherProvider() } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt index 8797f8fd88b..f710ed2406d 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/dependecyinjection/ViewModelModule.kt @@ -26,10 +26,10 @@ import org.koin.dsl.module val viewModelModule = module { viewModel { (accountName: String) -> - OCCapabilityViewModel(accountName, get(), get()) + OCCapabilityViewModel(accountName, get(), get(), get()) } viewModel { (filePath: String, accountName: String) -> - OCShareViewModel(filePath, accountName, get(), get(), get(), get(), get(), get(), get(), get()) + OCShareViewModel(filePath, accountName, get(), get(), get(), get(), get(), get(), get(), get(), get()) } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt index 68cb54af0a3..c1d0ce0e469 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt @@ -26,12 +26,10 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.capabilities.usecases.GetCapabilitiesAsLiveDataUseCase -import com.owncloud.android.domain.capabilities.usecases.GetStoredCapabilitiesUseCase import com.owncloud.android.domain.capabilities.usecases.RefreshCapabilitiesFromServerAsyncUseCase import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult -import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.Dispatchers +import com.owncloud.android.providers.CoroutinesDispatcherProvider import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -42,20 +40,20 @@ class OCCapabilityViewModel( private val accountName: String, getCapabilitiesAsLiveDataUseCase: GetCapabilitiesAsLiveDataUseCase, private val refreshCapabilitiesFromServerUseCase: RefreshCapabilitiesFromServerAsyncUseCase, - private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO + private val coroutineDispatcherProvider: CoroutinesDispatcherProvider ) : ViewModel() { private val _capabilities = MediatorLiveData>>() val capabilities: LiveData>> = _capabilities - private var capabilitiesLiveData: LiveData? = getCapabilitiesAsLiveDataUseCase.execute( + private var capabilitiesLiveData: LiveData = getCapabilitiesAsLiveDataUseCase.execute( GetCapabilitiesAsLiveDataUseCase.Params( accountName = accountName ) ) init { - _capabilities.addSource(capabilitiesLiveData!!) { capabilities -> + _capabilities.addSource(capabilitiesLiveData) { capabilities -> _capabilities.postValue(Event(UIResult.Success(capabilities))) } @@ -65,10 +63,10 @@ class OCCapabilityViewModel( fun refreshCapabilitiesFromNetwork() { viewModelScope.launch { _capabilities.postValue( - Event(UIResult.Loading(capabilitiesLiveData?.value)) + Event(UIResult.Loading(capabilitiesLiveData.value)) ) - val useCaseResult = withContext(ioDispatcher) { + val useCaseResult = withContext(coroutineDispatcherProvider.io) { refreshCapabilitiesFromServerUseCase.execute( RefreshCapabilitiesFromServerAsyncUseCase.Params( accountName = accountName @@ -78,7 +76,7 @@ class OCCapabilityViewModel( if (useCaseResult.isError) { _capabilities.postValue( - Event(UIResult.Error(useCaseResult.getThrowableOrNull(), capabilitiesLiveData?.value)) + Event(UIResult.Error(useCaseResult.getThrowableOrNull(), capabilitiesLiveData.value)) ) } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt index f8ca1c7beb9..952c8b4e8f6 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt @@ -36,8 +36,7 @@ import com.owncloud.android.domain.sharing.shares.usecases.GetSharesAsLiveDataUs import com.owncloud.android.domain.sharing.shares.usecases.RefreshSharesFromServerAsyncUseCase import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult -import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.Dispatchers +import com.owncloud.android.providers.CoroutinesDispatcherProvider import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -55,7 +54,7 @@ class OCShareViewModel( private val createPublicShareUseCase: CreatePublicShareAsyncUseCase, private val editPublicShareUseCase: EditPublicShareAsyncUseCase, private val deletePublicShareUseCase: DeleteShareAsyncUseCase, - private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO + private val coroutineDispatcherProvider: CoroutinesDispatcherProvider ) : ViewModel() { private val _shares = MediatorLiveData>>>() @@ -73,11 +72,11 @@ class OCShareViewModel( refreshSharesFromNetwork() } - fun refreshSharesFromNetwork() { + private fun refreshSharesFromNetwork() { viewModelScope.launch { _shares.postValue(Event(UIResult.Loading(sharesLiveData.value))) - val useCaseResult = withContext(ioDispatcher) { + val useCaseResult = withContext(coroutineDispatcherProvider.io) { refreshSharesFromServerAsyncUseCase.execute( RefreshSharesFromServerAsyncUseCase.Params( filePath = filePath, @@ -105,7 +104,7 @@ class OCShareViewModel( Event(UIResult.Loading()) ) - val useCaseResult = withContext(ioDispatcher) { + val useCaseResult = withContext(coroutineDispatcherProvider.io) { deletePublicShareUseCase.execute( DeleteShareAsyncUseCase.Params( remoteId @@ -113,12 +112,8 @@ class OCShareViewModel( ) } - if (!useCaseResult.isSuccess) { - _shareDeletionStatus.postValue( - Event(UIResult.Error(useCaseResult.getThrowableOrNull())) - ) - } else { - _shareDeletionStatus.postValue(Event(UIResult.Success())) + if (useCaseResult.isError) { + _shareDeletionStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) } } } @@ -142,7 +137,7 @@ class OCShareViewModel( Event(UIResult.Loading()) ) - val useCaseResult = withContext(ioDispatcher) { + val useCaseResult = withContext(coroutineDispatcherProvider.io) { createPrivateShareUseCase.execute( CreatePrivateShareAsyncUseCase.Params( filePath, @@ -154,7 +149,9 @@ class OCShareViewModel( ) } - if (!useCaseResult.isSuccess) { + if (useCaseResult.isSuccess) { + _privateShareCreationStatus.postValue(Event(UIResult.Success())) + } else { _privateShareCreationStatus.postValue( Event(UIResult.Error(useCaseResult.getThrowableOrNull())) ) @@ -165,20 +162,16 @@ class OCShareViewModel( private val _privateShare = MediatorLiveData>>() val privateShare: LiveData>> = _privateShare - private var privateShareLiveData: LiveData? = null - // Used to get a specific private share after updating it fun refreshPrivateShare( remoteId: Long ) { - privateShareLiveData = getShareAsLiveDataUseCase.execute( + val privateShareLiveData = getShareAsLiveDataUseCase.execute( GetShareAsLiveDataUseCase.Params(remoteId) ) - privateShareLiveData?.let { - _privateShare.addSource(it) { privateShare -> - _privateShare.postValue(Event(UIResult.Success(privateShare))) - } + _privateShare.addSource(privateShareLiveData) { privateShare -> + _privateShare.postValue(Event(UIResult.Success(privateShare))) } } @@ -195,7 +188,7 @@ class OCShareViewModel( Event(UIResult.Loading()) ) - val useCaseResult = withContext(ioDispatcher) { + val useCaseResult = withContext(coroutineDispatcherProvider.io) { editPrivateShareUseCase.execute( EditPrivateShareAsyncUseCase.Params( remoteId, @@ -205,12 +198,8 @@ class OCShareViewModel( ) } - if (!useCaseResult.isSuccess) { - _privateShareEditionStatus.postValue( - Event(UIResult.Error(useCaseResult.getThrowableOrNull())) - ) - } else { - _privateShareEditionStatus.postValue(Event(UIResult.Success())) + if (useCaseResult.isError) { + _privateShareEditionStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) } } } @@ -236,7 +225,7 @@ class OCShareViewModel( Event(UIResult.Loading()) ) - val useCaseResult = withContext(ioDispatcher) { + val useCaseResult = withContext(coroutineDispatcherProvider.io) { createPublicShareUseCase.execute( CreatePublicShareAsyncUseCase.Params( filePath, @@ -250,12 +239,10 @@ class OCShareViewModel( ) } - if (!useCaseResult.isSuccess) { - _publicShareCreationStatus.postValue( - Event(UIResult.Error(useCaseResult.getThrowableOrNull())) - ) - } else { + if (useCaseResult.isSuccess) { _publicShareCreationStatus.postValue(Event(UIResult.Success())) + } else { + _publicShareCreationStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) } } } @@ -273,11 +260,9 @@ class OCShareViewModel( accountName: String ) { viewModelScope.launch { - _publicShareEditionStatus.postValue( - Event(UIResult.Loading()) - ) + _publicShareEditionStatus.postValue(Event(UIResult.Loading())) - val useCaseResult = withContext(ioDispatcher) { + val useCaseResult = withContext(coroutineDispatcherProvider.io) { editPublicShareUseCase.execute( EditPublicShareAsyncUseCase.Params( remoteId, @@ -291,12 +276,10 @@ class OCShareViewModel( ) } - if (!useCaseResult.isSuccess) { - _publicShareEditionStatus.postValue( - Event(UIResult.Error(useCaseResult.getThrowableOrNull())) - ) - } else { + if (useCaseResult.isSuccess) { _publicShareEditionStatus.postValue(Event(UIResult.Success())) + } else { + _publicShareEditionStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/providers/CoroutinesDispatcherProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/providers/CoroutinesDispatcherProvider.kt new file mode 100644 index 00000000000..9b1a52f1373 --- /dev/null +++ b/owncloudApp/src/main/java/com/owncloud/android/providers/CoroutinesDispatcherProvider.kt @@ -0,0 +1,31 @@ +/* + * Copyright 2018 Google, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.owncloud.android.providers + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers.Default +import kotlinx.coroutines.Dispatchers.IO +import kotlinx.coroutines.Dispatchers.Main + +/** + * Provide coroutines context. + */ +data class CoroutinesDispatcherProvider( + val main: CoroutineDispatcher = Main, + val computation: CoroutineDispatcher = Default, + val io: CoroutineDispatcher = IO +) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModelTest.kt similarity index 67% rename from owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt rename to owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModelTest.kt index 8665339d25e..fadf2e9d6dc 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/capabilities/viewmodels/OCCapabilityViewModelTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModelTest.kt @@ -18,9 +18,8 @@ * along with this program. If not, see . */ -package com.owncloud.android.capabilities.viewmodels +package com.owncloud.android.presentation.viewmodels.capabilities -import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import com.owncloud.android.domain.UseCaseResult @@ -30,10 +29,10 @@ import com.owncloud.android.domain.capabilities.usecases.RefreshCapabilitiesFrom import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel -import com.owncloud.android.testutil.OC_ACCOUNT +import com.owncloud.android.providers.CoroutinesDispatcherProvider +import com.owncloud.android.testutil.OC_ACCOUNT_NAME import com.owncloud.android.testutil.OC_CAPABILITY -import com.owncloud.android.testutil.livedata.TIMEOUT_TEST_LONG -import com.owncloud.android.testutil.livedata.getOrAwaitValues +import com.owncloud.android.testutil.livedata.getLastEmittedValue import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every @@ -41,14 +40,21 @@ import io.mockk.mockkClass import io.mockk.spyk import io.mockk.unmockkAll import io.mockk.verify +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestCoroutineDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) +@ExperimentalCoroutinesApi class OCCapabilityViewModelTest { private lateinit var ocCapabilityViewModel: OCCapabilityViewModel @@ -57,14 +63,29 @@ class OCCapabilityViewModelTest { private val capabilitiesLiveData = MutableLiveData() - private var testAccount: Account = OC_ACCOUNT + private val testCoroutineDispatcher = TestCoroutineDispatcher() + private val coroutineDispatcherProvider: CoroutinesDispatcherProvider = CoroutinesDispatcherProvider( + io = testCoroutineDispatcher, + main = testCoroutineDispatcher, + computation = testCoroutineDispatcher + ) + + private var testAccountName = OC_ACCOUNT_NAME @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() + @Before + fun setUp() { + Dispatchers.setMain(testCoroutineDispatcher) + } + @After fun tearDown() { + Dispatchers.resetMain() + testCoroutineDispatcher.cleanupTestCoroutines() + unmockkAll() } @@ -75,9 +96,10 @@ class OCCapabilityViewModelTest { every { getCapabilitiesAsLiveDataUseCase.execute(any()) } returns capabilitiesLiveData ocCapabilityViewModel = OCCapabilityViewModel( - accountName = testAccount.name, + accountName = testAccountName, getCapabilitiesAsLiveDataUseCase = getCapabilitiesAsLiveDataUseCase, - refreshCapabilitiesFromServerUseCase = refreshCapabilitiesFromServerUseCase + refreshCapabilitiesFromServerUseCase = refreshCapabilitiesFromServerUseCase, + coroutineDispatcherProvider = coroutineDispatcherProvider ) } @@ -85,7 +107,7 @@ class OCCapabilityViewModelTest { fun getCapabilitiesAsLiveDataWithData() { initTest() - val capability = OC_CAPABILITY.copy(accountName = testAccount.name) + val capability = OC_CAPABILITY.copy(accountName = testAccountName) getCapabilitiesAsLiveDataVerification( valueToTest = capability, @@ -103,69 +125,50 @@ class OCCapabilityViewModelTest { ) } - @Test - fun fetchCapabilitiesLoading() { - initTest() - - fetchCapabilitiesVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = Event(UIResult.Loading()) - ) - } -// -// @Test -// fun fetchCapabilitiesError() { -// initTest() -// -// val error = Throwable() -// fetchCapabilitiesVerification( -// valueToTest = UseCaseResult.Error(error), -// expectedValue = UIResult.Error(error), -// expectedOnPosition = 2 -// ) -// } -// -// @Test -// fun fetchCapabilitiesSuccess() { -// initTest() -// -// //Expect a null since we are mocking refreshCapabilities and we are not storing new capabilities on db -// fetchCapabilitiesVerification( -// valueToTest = UseCaseResult.Success(Unit), -// expectedValue = null, -// expectedOnPosition = 2 -// ) -// } - private fun getCapabilitiesAsLiveDataVerification( valueToTest: OCCapability?, - expectedValue: Event>?, - expectedOnPosition: Int = 1 + expectedValue: Event>? ) { + capabilitiesLiveData.postValue(valueToTest) + + val value = ocCapabilityViewModel.capabilities.getLastEmittedValue() + assertEquals(expectedValue, value) + // Calls performed during OCCapabilityViewModel initialization verify(exactly = 1) { getCapabilitiesAsLiveDataUseCase.execute(any()) } verify(exactly = 1) { refreshCapabilitiesFromServerUseCase.execute(any()) } + } - capabilitiesLiveData.postValue(valueToTest) + @Test + fun fetchCapabilitiesSuccess() { + fetchCapabilitiesVerification( + useCaseResult = UseCaseResult.Success(Unit), + expectedValue = Event(UIResult.Loading()) + ) + } - val value = ocCapabilityViewModel.capabilities.getOrAwaitValues() - assertEquals(expectedValue, value[expectedOnPosition - 1]) + @Test + fun fetchCapabilitiesError() { + val error = Throwable() + fetchCapabilitiesVerification( + useCaseResult = UseCaseResult.Error(error), + expectedValue = Event(UIResult.Error(error)) + ) } private fun fetchCapabilitiesVerification( - valueToTest: UseCaseResult, - expectedValue: Event?>, - expectedOnPosition: Int = 1 + useCaseResult: UseCaseResult, + expectedValue: Event?> ) { - coEvery { refreshCapabilitiesFromServerUseCase.execute(any()) } returns valueToTest + initTest() + coEvery { refreshCapabilitiesFromServerUseCase.execute(any()) } returns useCaseResult ocCapabilityViewModel.refreshCapabilitiesFromNetwork() - val value = ocCapabilityViewModel.capabilities.getOrAwaitValues(expectedOnPosition) - assertEquals(expectedValue, value[expectedOnPosition - 1]) + val value = ocCapabilityViewModel.capabilities.getLastEmittedValue() + assertEquals(expectedValue, value) - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { refreshCapabilitiesFromServerUseCase.execute(any()) } - //Just once on init + coVerify(exactly = 2) { refreshCapabilitiesFromServerUseCase.execute(any()) } verify(exactly = 1) { getCapabilitiesAsLiveDataUseCase.execute(any()) } } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModelTest.kt similarity index 57% rename from owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt rename to owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModelTest.kt index ec83a9512a2..80d04d95174 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/viewmodels/OCShareViewModelTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModelTest.kt @@ -18,9 +18,8 @@ * along with this program. If not, see . */ -package com.owncloud.android.sharing.shares.viewmodels +package com.owncloud.android.presentation.viewmodels.sharing -import android.accounts.Account import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import com.owncloud.android.domain.UseCaseResult @@ -33,26 +32,34 @@ import com.owncloud.android.domain.sharing.shares.usecases.EditPublicShareAsyncU import com.owncloud.android.domain.sharing.shares.usecases.GetShareAsLiveDataUseCase import com.owncloud.android.domain.sharing.shares.usecases.GetSharesAsLiveDataUseCase import com.owncloud.android.domain.sharing.shares.usecases.RefreshSharesFromServerAsyncUseCase +import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult -import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel -import com.owncloud.android.testutil.OC_ACCOUNT +import com.owncloud.android.providers.CoroutinesDispatcherProvider +import com.owncloud.android.testutil.OC_ACCOUNT_NAME import com.owncloud.android.testutil.OC_SHARE import com.owncloud.android.testutil.livedata.TIMEOUT_TEST_LONG -import com.owncloud.android.testutil.livedata.getOrAwaitValues +import com.owncloud.android.testutil.livedata.getEmittedValues +import com.owncloud.android.testutil.livedata.getLastEmittedValue import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockkClass import io.mockk.spyk import io.mockk.unmockkAll -import io.mockk.verify +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestCoroutineDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 +@ExperimentalCoroutinesApi @RunWith(JUnit4::class) class OCShareViewModelTest { private lateinit var ocShareViewModel: OCShareViewModel @@ -67,18 +74,32 @@ class OCShareViewModelTest { private lateinit var deletePublicShareAsyncUseCase: DeleteShareAsyncUseCase private val filePath = "/Photos/image.jpg" - - private var testAccount: Account = OC_ACCOUNT + private val testAccountName = OC_ACCOUNT_NAME private val sharesLiveData = MutableLiveData>() private val privateShareLiveData = MutableLiveData() + private val testCoroutineDispatcher = TestCoroutineDispatcher() + private val coroutineDispatcherProvider: CoroutinesDispatcherProvider = CoroutinesDispatcherProvider( + io = testCoroutineDispatcher, + main = testCoroutineDispatcher, + computation = testCoroutineDispatcher + ) + @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() + @Before + fun setUp() { + Dispatchers.setMain(testCoroutineDispatcher) + } + @After fun tearDown() { + Dispatchers.resetMain() + testCoroutineDispatcher.cleanupTestCoroutines() + unmockkAll() } @@ -95,9 +116,11 @@ class OCShareViewModelTest { every { getSharesAsLiveDataUseCase.execute(any()) } returns sharesLiveData every { getShareAsLiveDataUseCase.execute(any()) } returns privateShareLiveData + testCoroutineDispatcher.pauseDispatcher() + ocShareViewModel = OCShareViewModel( filePath, - testAccount.name, + testAccountName, getSharesAsLiveDataUseCase, getShareAsLiveDataUseCase, refreshSharesFromServerAsyncUseCase, @@ -105,7 +128,8 @@ class OCShareViewModelTest { editPrivateShareAsyncUseCase, createPublicShareAsyncUseCase, editPublicShareAsyncUseCase, - deletePublicShareAsyncUseCase + deletePublicShareAsyncUseCase, + coroutineDispatcherProvider ) } @@ -113,122 +137,87 @@ class OCShareViewModelTest { ******************************************* PRIVATE SHARES ******************************************* ******************************************************************************************************/ - @Test - fun insertPrivateShareLoading() { - initTest() - - insertPrivateShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Loading(), - expectedOnPosition = 1 - ) - } - @Test fun insertPrivateShareSuccess() { - initTest() - insertPrivateShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Success(), - expectedOnPosition = 2 + useCaseResult = UseCaseResult.Success(Unit), + expectedValues = listOf(Event(UIResult.Loading()), Event(UIResult.Success())) ) } @Test fun insertPrivateShareError() { - initTest() - val error = Throwable() insertPrivateShareVerification( - valueToTest = UseCaseResult.Error(error), - expectedValue = UIResult.Error(error), - expectedOnPosition = 2 + useCaseResult = UseCaseResult.Error(error), + expectedValues = listOf(Event(UIResult.Loading()), Event(UIResult.Error(error))) ) } - @Test - fun updatePrivateShareLoading() { + private fun insertPrivateShareVerification( + useCaseResult: UseCaseResult, + expectedValues: List>> + ) { initTest() + coEvery { createPrivateShareAsyncUseCase.execute(any()) } returns useCaseResult - updatePrivateShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Loading(), - expectedOnPosition = 1 + ocShareViewModel.insertPrivateShare( + filePath = OC_SHARE.path, + shareType = OC_SHARE.shareType, + shareeName = OC_SHARE.accountOwner, + permissions = OC_SHARE.permissions, + accountName = OC_SHARE.accountOwner ) - } - @Test - fun updatePrivateShareSuccess() { - initTest() + val emittedValues = ocShareViewModel.privateShareCreationStatus.getEmittedValues(expectedValues.size) { + testCoroutineDispatcher.resumeDispatcher() + } + assertEquals(expectedValues, emittedValues) - updatePrivateShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Success(), - expectedOnPosition = 2 - ) + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { createPrivateShareAsyncUseCase.execute(any()) } + coVerify(exactly = 0) { createPublicShareAsyncUseCase.execute(any()) } } @Test - fun refreshPrivateShareSuccess() { + fun refreshPrivateShare() { initTest() - - val ocShare = OC_SHARE.copy(id = 123, name = "PhotoLink") - privateShareLiveData.postValue(ocShare) - - refreshPrivateShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Success(ocShare), - expectedOnPosition = 1 - ) - } - - private fun refreshPrivateShareVerification( - valueToTest: UseCaseResult, - expectedValue: UIResult?, - expectedOnPosition: Int = 1 - ) { - coEvery { createPrivateShareAsyncUseCase.execute(any()) } returns valueToTest + coEvery { getShareAsLiveDataUseCase.execute(any()) } returns MutableLiveData(OC_SHARE) ocShareViewModel.refreshPrivateShare(OC_SHARE.remoteId) - val value = ocShareViewModel.privateShare.getOrAwaitValues(expectedOnPosition) - assertEquals(expectedValue, value[expectedOnPosition - 1]) + val emittedValues = ocShareViewModel.privateShare.getLastEmittedValue { + testCoroutineDispatcher.resumeDispatcher() + } + assertEquals(Event(UIResult.Success(OC_SHARE)), emittedValues) - verify(exactly = 1) { getShareAsLiveDataUseCase.execute(GetShareAsLiveDataUseCase.Params(OC_SHARE.remoteId)) } - // Just once on init - verify(exactly = 1) { getSharesAsLiveDataUseCase.execute(any()) } + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { getShareAsLiveDataUseCase.execute(any()) } } - private fun insertPrivateShareVerification( - valueToTest: UseCaseResult, - expectedValue: UIResult?, - expectedOnPosition: Int = 1 - ) { - coEvery { createPrivateShareAsyncUseCase.execute(any()) } returns valueToTest - - ocShareViewModel.insertPrivateShare( - filePath = OC_SHARE.path, - shareType = OC_SHARE.shareType, - shareeName = OC_SHARE.accountOwner, - permissions = OC_SHARE.permissions, - accountName = OC_SHARE.accountOwner + @Test + fun updatePrivateShareSuccess() { + updatePrivateShareVerification( + useCaseResult = UseCaseResult.Success(Unit), + expectedValues = listOf(Event(UIResult.Loading())) ) + } - val value = ocShareViewModel.privateShareCreationStatus.getOrAwaitValues(expectedOnPosition) - assertEquals(expectedValue, value[expectedOnPosition - 1]) + @Test + fun updatePrivateShareError() { + val error = Throwable() - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { createPrivateShareAsyncUseCase.execute(any()) } - coVerify(exactly = 0) { createPublicShareAsyncUseCase.execute(any()) } + updatePrivateShareVerification( + useCaseResult = UseCaseResult.Error(error), + expectedValues = listOf(Event(UIResult.Loading()), Event(UIResult.Error(error))) + ) } private fun updatePrivateShareVerification( - valueToTest: UseCaseResult, - expectedValue: UIResult?, - expectedOnPosition: Int = 1 + useCaseResult: UseCaseResult, + expectedValues: List?>> ) { - coEvery { editPrivateShareAsyncUseCase.execute(any()) } returns valueToTest + initTest() + coEvery { editPrivateShareAsyncUseCase.execute(any()) } returns useCaseResult ocShareViewModel.updatePrivateShare( remoteId = OC_SHARE.remoteId, @@ -236,8 +225,10 @@ class OCShareViewModelTest { accountName = OC_SHARE.accountOwner ) - val value = ocShareViewModel.privateShareEditionStatus.getOrAwaitValues(expectedOnPosition) - assertEquals(expectedValue, value[expectedOnPosition - 1]) + val emittedValues = ocShareViewModel.privateShareEditionStatus.getEmittedValues(expectedValues.size) { + testCoroutineDispatcher.resumeDispatcher() + } + assertEquals(expectedValues, emittedValues ) coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { editPrivateShareAsyncUseCase.execute(any()) } coVerify(exactly = 0) { editPublicShareAsyncUseCase.execute(any()) } @@ -247,106 +238,74 @@ class OCShareViewModelTest { ******************************************* PUBLIC SHARES ******************************************** ******************************************************************************************************/ - @Test - fun insertPublicShareLoading() { - initTest() - - insertPublicShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Loading(), - expectedOnPosition = 1 - ) - } - @Test fun insertPublicShareSuccess() { - initTest() - insertPublicShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Success(), - expectedOnPosition = 2 + useCaseResult = UseCaseResult.Success(Unit), + expectedValues = listOf(Event(UIResult.Loading()), Event(UIResult.Success())) ) } @Test fun insertPublicShareError() { - initTest() - val error = Throwable() insertPublicShareVerification( - valueToTest = UseCaseResult.Error(error), - expectedValue = UIResult.Error(error), - expectedOnPosition = 2 + useCaseResult = UseCaseResult.Error(error), + expectedValues = listOf(Event(UIResult.Loading()), Event(UIResult.Error(error))) ) } - @Test - fun updatePublicShareLoading() { + private fun insertPublicShareVerification( + useCaseResult: UseCaseResult, + expectedValues: List?>> + ) { initTest() + coEvery { createPublicShareAsyncUseCase.execute(any()) } returns useCaseResult - updatePublicShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Loading(), - expectedOnPosition = 1 + ocShareViewModel.insertPublicShare( + filePath = OC_SHARE.path, + name = "Photos 2 link", + password = "1234", + expirationTimeInMillis = -1, + publicUpload = false, + permissions = OC_SHARE.permissions, + accountName = OC_SHARE.accountOwner ) + + val emittedValues = ocShareViewModel.publicShareCreationStatus.getEmittedValues(expectedValues.size) { + testCoroutineDispatcher.resumeDispatcher() + } + assertEquals(expectedValues, emittedValues) + + coVerify(exactly = 0) { createPrivateShareAsyncUseCase.execute(any()) } + coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { createPublicShareAsyncUseCase.execute(any()) } } @Test fun updatePublicShareSuccess() { - initTest() - updatePublicShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Success(), - expectedOnPosition = 2 + useCaseResult = UseCaseResult.Success(Unit), + expectedValues = listOf(Event(UIResult.Loading()), Event(UIResult.Success())) ) } @Test fun updatePublicShareError() { - initTest() - val error = Throwable() updatePublicShareVerification( - valueToTest = UseCaseResult.Error(error), - expectedValue = UIResult.Error(error), - expectedOnPosition = 2 + useCaseResult = UseCaseResult.Error(error), + expectedValues = listOf(Event(UIResult.Loading()), Event(UIResult.Error(error))) ) } - private fun insertPublicShareVerification( - valueToTest: UseCaseResult, - expectedValue: UIResult?, - expectedOnPosition: Int = 1 - ) { - coEvery { createPublicShareAsyncUseCase.execute(any()) } returns valueToTest - - ocShareViewModel.insertPublicShare( - filePath = OC_SHARE.path, - name = "Photos 2 link", - password = "1234", - expirationTimeInMillis = -1, - publicUpload = false, - permissions = OC_SHARE.permissions, - accountName = OC_SHARE.accountOwner - ) - - val value = ocShareViewModel.publicShareCreationStatus.getOrAwaitValues(expectedOnPosition) - assertEquals(expectedValue, value[expectedOnPosition - 1]) - - coVerify(exactly = 0) { createPrivateShareAsyncUseCase.execute(any()) } - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { createPublicShareAsyncUseCase.execute(any()) } - } - private fun updatePublicShareVerification( - valueToTest: UseCaseResult, - expectedValue: UIResult?, - expectedOnPosition: Int = 1 + useCaseResult: UseCaseResult, + expectedValues: List?>> ) { - coEvery { editPublicShareAsyncUseCase.execute(any()) } returns valueToTest + initTest() + coEvery { editPublicShareAsyncUseCase.execute(any()) } returns useCaseResult ocShareViewModel.updatePublicShare( remoteId = 1, @@ -358,8 +317,10 @@ class OCShareViewModelTest { accountName = "Carlos" ) - val value = ocShareViewModel.publicShareEditionStatus.getOrAwaitValues(expectedOnPosition) - assertEquals(expectedValue, value[expectedOnPosition - 1]) + val emittedValues = ocShareViewModel.publicShareEditionStatus.getEmittedValues(expectedValues.size) { + testCoroutineDispatcher.resumeDispatcher() + } + assertEquals(expectedValues, emittedValues) coVerify(exactly = 0) { editPrivateShareAsyncUseCase.execute(any()) } coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { editPublicShareAsyncUseCase.execute(any()) } @@ -369,104 +330,38 @@ class OCShareViewModelTest { *********************************************** COMMON *********************************************** ******************************************************************************************************/ - @Test - fun deletePublicShareLoading() { - initTest() - - deleteShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Loading(), - expectedOnPosition = 1 - ) - } - @Test fun deletePublicShareSuccess() { - initTest() - deleteShareVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Success(), - expectedOnPosition = 2 + useCaseResult = UseCaseResult.Success(Unit), + expectedValues = listOf(Event(UIResult.Loading())) ) } @Test fun deletePublicShareError() { - initTest() - val error = Throwable() deleteShareVerification( - valueToTest = UseCaseResult.Error(error), - expectedValue = UIResult.Error(error), - expectedOnPosition = 2 - ) - } - - @Test - fun getSharesAsLiveDataLoading() { - initTest() - - getSharesAsLiveDataVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = UIResult.Loading(sharesLiveData.value), - expectedOnPosition = 1 + useCaseResult = UseCaseResult.Error(error), + expectedValues = listOf(Event(UIResult.Loading()), Event(UIResult.Error(error))) ) } - @Test - fun getSharesAsLiveDataError() { - initTest() - - val error = Throwable() - - getSharesAsLiveDataVerification( - valueToTest = UseCaseResult.Error(error), - expectedValue = UIResult.Error(error, sharesLiveData.value), - expectedOnPosition = 2 - ) - } - - @Test - fun getSharesAsLiveDataWithData() { - initTest() - - getSharesAsLiveDataVerification( - valueToTest = UseCaseResult.Success(Unit), - expectedValue = null, - expectedOnPosition = 2 - ) - } - - private fun getSharesAsLiveDataVerification( - valueToTest: UseCaseResult, - expectedValue: UIResult>?, - expectedOnPosition: Int = 1 - ) { - coEvery { refreshSharesFromServerAsyncUseCase.execute(any()) } returns valueToTest - - ocShareViewModel.refreshSharesFromNetwork() - - val value = ocShareViewModel.shares.getOrAwaitValues(expectedOnPosition) - assertEquals(expectedValue, value[expectedOnPosition - 1]) - - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { refreshSharesFromServerAsyncUseCase.execute(any()) } - } - private fun deleteShareVerification( - valueToTest: UseCaseResult, - expectedValue: UIResult?, - expectedOnPosition: Int = 1 + useCaseResult: UseCaseResult, + expectedValues: List?>> ) { - coEvery { deletePublicShareAsyncUseCase.execute(any()) } returns valueToTest + initTest() + coEvery { deletePublicShareAsyncUseCase.execute(any()) } returns useCaseResult - ocShareViewModel.deleteShare( - remoteId = OC_SHARE.remoteId - ) + ocShareViewModel.deleteShare(remoteId = OC_SHARE.remoteId) + + val emittedValues = ocShareViewModel.shareDeletionStatus.getEmittedValues(expectedValues.size) { + testCoroutineDispatcher.resumeDispatcher() + } - val value = ocShareViewModel.shareDeletionStatus.getOrAwaitValues(expectedOnPosition) - assertEquals(expectedValue, value[expectedOnPosition - 1]) + assertEquals(expectedValues, emittedValues) coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { deletePublicShareAsyncUseCase.execute(any()) diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveData.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveData.kt deleted file mode 100644 index 679ecd81d51..00000000000 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveData.kt +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.owncloud.android.testutil.livedata - -import androidx.lifecycle.LiveData -import androidx.lifecycle.Observer -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit - -/** - * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds. - * Once we got a notification via onChanged, we stop observing. - */ -inline fun LiveData.getOrAwaitValues( - expectedValues: Int = 1 -): List { - var currentValue = 0 - val data = arrayOfNulls(expectedValues) - val latch = CountDownLatch(expectedValues) - val observer = object : Observer { - override fun onChanged(o: T?) { - data[currentValue] = o - currentValue++ - latch.countDown() - if (currentValue == expectedValues) { - this@getOrAwaitValues.removeObserver(this) - } - } - } - this.observeForever(observer) - latch.await(TIMEOUT_TEST_SHORT, TimeUnit.MILLISECONDS) - - return data.toList() -} diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveDataUtils.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveDataUtils.kt new file mode 100644 index 00000000000..93c86adec43 --- /dev/null +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/LiveDataUtils.kt @@ -0,0 +1,54 @@ +/** + * ownCloud Android client application + * + * @author José Carlos Montes Martos + * Copyright (C) 2019 ownCloud GmbH. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program 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 this program. If not, see . + */ +package com.owncloud.android.testutil.livedata + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +inline fun LiveData.getEmittedValues( + expectedSize: Int, + timeout: Long = TIMEOUT_TEST_SHORT, + crossinline onObserved: () -> Unit = {} +): List { + val currentValue = AtomicInteger(0) + val data = arrayOfNulls(expectedSize) + val latch = CountDownLatch(expectedSize) + val observer = object : Observer { + override fun onChanged(o: T?) { + data[currentValue.getAndAdd(1)] = o + if (currentValue.get() == expectedSize) { + removeObserver(this) + } + latch.countDown() + + } + } + observeForever(observer) + onObserved() + latch.await(timeout, TimeUnit.MILLISECONDS) + + return data.toList() +} + +inline fun LiveData.getLastEmittedValue( + crossinline onObserved: () -> Unit = {} +): T? = getEmittedValues(expectedSize = 1, onObserved = onObserved).firstOrNull() From dc1ae37bfb066eccbe4a826c0d750ecf426be856 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Tue, 26 Nov 2019 14:54:19 +0100 Subject: [PATCH 28/41] First attempt to fix migration tests --- build.gradle | 2 +- owncloudApp/build.gradle | 11 ---------- owncloudData/build.gradle | 9 ++++++++ .../owncloud/android/data}/MigrationTest.kt | 22 +++++++++---------- .../owncloud/android/data/ProviderMeta.java | 2 +- 5 files changed, 21 insertions(+), 25 deletions(-) rename {owncloudApp/src/androidTest/java/com/owncloud/android/database => owncloudData/src/androidTest/java/com/owncloud/android/data}/MigrationTest.kt (87%) diff --git a/build.gradle b/build.gradle index 57e5b56c10d..5c6168a5764 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ buildscript { // Android jetpack archLifecycleVersion = "2.1.0" - roomVersion = "2.2.1" + roomVersion = "2.2.2" appCompat = "1.1.0" // Kotlin diff --git a/owncloudApp/build.gradle b/owncloudApp/build.gradle index 82bf588a669..02537878e4e 100644 --- a/owncloudApp/build.gradle +++ b/owncloudApp/build.gradle @@ -45,7 +45,6 @@ dependencies { androidTestImplementation "androidx.test.espresso:espresso-web:$espressoTestVersion" androidTestImplementation "androidx.test.uiautomator:uiautomator:$uiAutomatorTestVersion" androidTestImplementation "androidx.annotation:annotation:$annotationTestVersion" - androidTestImplementation "androidx.room:room-testing:$roomVersion" androidTestImplementation "androidx.arch.core:core-testing:$archLifecycleVersion" androidTestImplementation("io.mockk:mockk-android:$mockkVersion") { exclude module: 'objenesis' @@ -68,9 +67,6 @@ dependencies { implementation "androidx.lifecycle:lifecycle-viewmodel:$archLifecycleVersion" kapt "androidx.lifecycle:lifecycle-common-java8:$archLifecycleVersion" - implementation "androidx.room:room-runtime:$roomVersion" - kapt "androidx.room:room-compiler:$roomVersion" - // Koin dependency injector implementation "org.koin:koin-androidx-viewmodel:$koinVersion" @@ -105,12 +101,6 @@ android { buildConfigField "String", gitRemote, "\"" + getGitOriginRemote() + "\"" buildConfigField "String", commitSHA1, "\"" + getLatestGitHash() + "\"" - javaCompileOptions { - annotationProcessorOptions { - arguments = ["room.schemaLocation": "$projectDir/schemas".toString()] - } - } - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } @@ -122,7 +112,6 @@ android { sourceSets { androidTest.java.srcDirs += "src/test-common/java" test.java.srcDirs += "src/test-common/java" - androidTest.assets.srcDirs += files("$projectDir/schemas".toString()) } lintOptions { diff --git a/owncloudData/build.gradle b/owncloudData/build.gradle index 8ee9e3c23c9..6a4dd7f34e3 100644 --- a/owncloudData/build.gradle +++ b/owncloudData/build.gradle @@ -19,6 +19,12 @@ android { testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + // Room Database Tests + javaCompileOptions { + annotationProcessorOptions { + arguments = ["room.schemaLocation": "$projectDir/schemas".toString()] + } + } } buildTypes { @@ -36,6 +42,8 @@ android { sourceSets { androidTest.java.srcDirs += "src/test-common/java" test.java.srcDirs += "src/test-common/java" + // Room Database Tests + androidTest.assets.srcDirs += files("$projectDir/schemas".toString()) } } @@ -67,6 +75,7 @@ dependencies { androidTestImplementation "androidx.test.espresso:espresso-core:$espressoTestVersion" androidTestImplementation "androidx.test.ext:junit:$extJunitVersion" androidTestImplementation "androidx.arch.core:core-testing:$archLifecycleVersion" + androidTestImplementation "android.arch.persistence.room:testing:$roomVersion" androidTestImplementation ("io.mockk:mockk-android:$mockkVersion") { exclude module: 'objenesis' } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/database/MigrationTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt similarity index 87% rename from owncloudApp/src/androidTest/java/com/owncloud/android/database/MigrationTest.kt rename to owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt index aca4c19125d..22ead35dcf7 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/database/MigrationTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt @@ -18,7 +18,7 @@ * */ -package com.owncloud.android.database +package com.owncloud.android.data import android.content.ContentValues import android.database.sqlite.SQLiteDatabase @@ -29,14 +29,12 @@ import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry -import com.owncloud.android.data.OwncloudDatabase -import com.owncloud.android.db.ProviderMeta.ProviderTableMeta -import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME -import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL -import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS -import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MAYOR -import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MICRO -import com.owncloud.android.db.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MINOR +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MAYOR +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MICRO +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MINOR import com.owncloud.android.testutil.OC_CAPABILITY import org.junit.Assert.assertEquals import org.junit.Assert.assertNull @@ -68,7 +66,7 @@ class MigrationTest { ) { // Insert some data - insert(ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) + insert(ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) // Close database close() @@ -99,7 +97,7 @@ class MigrationTest { ) { // Database has schema version 27. Insert some values to test if they are migrated successfully. // We cannot use DAO classes because they expect the latest schema and we may not have some fields there. - insert(ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) + insert(ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) close() } @@ -136,7 +134,7 @@ class MigrationTest { DB_VERSION_28 ) ) { - insert(ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) + insert(ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) close() } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/ProviderMeta.java b/owncloudData/src/main/java/com/owncloud/android/data/ProviderMeta.java index 017b815ce9f..e4d8c229fc6 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/ProviderMeta.java +++ b/owncloudData/src/main/java/com/owncloud/android/data/ProviderMeta.java @@ -31,7 +31,7 @@ public class ProviderMeta { public static final String DB_NAME = "filelist"; public static final String NEW_DB_NAME = "owncloud_database"; - public static final int DB_VERSION = 27; + public static final int DB_VERSION = 28; private ProviderMeta() { } From 49e991c62a455059040eeb5d1fe5693128cf1aa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Tue, 26 Nov 2019 15:03:30 +0100 Subject: [PATCH 29/41] Remove dataUtils --- .../OCRemoteShareesDataSourceTest.kt | 81 ++++++++++++++--- .../android/data/utils/LiveDataTestUtil.kt | 0 .../android/data/utils/DataTestUtil.kt | 90 ------------------- 3 files changed, 69 insertions(+), 102 deletions(-) rename owncloudData/src/{test-common => androidTest}/java/com/owncloud/android/data/utils/LiveDataTestUtil.kt (100%) delete mode 100644 owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt index d8207934f9f..3bbd52ba205 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt @@ -21,14 +21,13 @@ package com.owncloud.android.data.sharing.sharees.datasources import com.owncloud.android.data.sharing.sharees.datasources.implementation.OCRemoteShareeDataSource import com.owncloud.android.data.sharing.sharees.network.OCShareeService -import com.owncloud.android.data.utils.DataTestUtil +import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation import io.mockk.every import io.mockk.mockk -import junit.framework.Assert.assertEquals -import org.hamcrest.CoreMatchers.notNullValue -import org.hamcrest.MatcherAssert.assertThat import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Ignore import org.junit.Test @@ -48,18 +47,18 @@ class OCRemoteShareesDataSourceTest { @Test fun readRemoteSharees() { val remoteSharees: ArrayList = arrayListOf( - DataTestUtil.createSharee("User 1", "0", "user1", "user1@mail.com"), - DataTestUtil.createSharee("User 2", "0", "user2", "user2@mail.com"), - DataTestUtil.createSharee("User 3", "0", "user3", "user3@mail.com") + createSharee("User 1", "0", "user1", "user1@mail.com"), + createSharee("User 2", "0", "user2", "user2@mail.com"), + createSharee("User 3", "0", "user3", "user3@mail.com") ) - val getRemoteShareesOperationResult = DataTestUtil.createRemoteOperationResultMock( + val getRemoteShareesOperationResult = createRemoteOperationResultMock( remoteSharees, true ) every { - ocShareeService.getSharees("user", 1 ,30) + ocShareeService.getSharees("user", 1, 30) } returns getRemoteShareesOperationResult // Get sharees from remote datasource @@ -69,7 +68,7 @@ class OCRemoteShareesDataSourceTest { 30 ) - assertThat(sharees, notNullValue()) + assertNotNull(sharees) assertEquals(3, sharees.size) val sharee1 = sharees.first() @@ -79,18 +78,76 @@ class OCRemoteShareesDataSourceTest { assertEquals(value.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH), "user1") assertEquals(value.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO), "user1@mail.com") - val sharee2 = sharees.get(1) + val sharee2 = sharees[1] assertEquals(sharee2.getString(GetRemoteShareesOperation.PROPERTY_LABEL), "User 2") val value2 = sharee2.getJSONObject(GetRemoteShareesOperation.NODE_VALUE) assertEquals(value2.getString(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE), "0") assertEquals(value2.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH), "user2") assertEquals(value2.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO), "user2@mail.com") - val sharee3 = sharees.get(2) + val sharee3 = sharees[2] assertEquals(sharee3.getString(GetRemoteShareesOperation.PROPERTY_LABEL), "User 3") val value3 = sharee3.getJSONObject(GetRemoteShareesOperation.NODE_VALUE) assertEquals(value3.getString(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE), "0") assertEquals(value3.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH), "user3") assertEquals(value3.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO), "user3@mail.com") } + + private fun createRemoteOperationResultMock( + data: T, + isSuccess: Boolean, + httpPhrase: String? = null, + resultCode: RemoteOperationResult.ResultCode? = null, + exception: Exception? = null + ): RemoteOperationResult { + val remoteOperationResult = mockk>(relaxed = true) + + every { + remoteOperationResult.data + } returns data + + every { + remoteOperationResult.isSuccess + } returns isSuccess + + if (httpPhrase != null) { + every { + remoteOperationResult.httpPhrase + } returns httpPhrase + } + + if (resultCode != null) { + every { + remoteOperationResult.code + } returns resultCode + } + + if (exception != null) { + every { + remoteOperationResult.exception + } returns exception + } + + return remoteOperationResult + } + + private fun createSharee( + label: String, + shareType: String, + shareWith: String, + shareWithAdditionalInfo: String + ): JSONObject { + val jsonObject = JSONObject() + + jsonObject.put(GetRemoteShareesOperation.PROPERTY_LABEL, label) + + val value = JSONObject() + value.put(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE, shareType) + value.put(GetRemoteShareesOperation.PROPERTY_SHARE_WITH, shareWith) + value.put(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO, shareWithAdditionalInfo) + + jsonObject.put(GetRemoteShareesOperation.NODE_VALUE, value) + + return jsonObject + } } diff --git a/owncloudData/src/test-common/java/com/owncloud/android/data/utils/LiveDataTestUtil.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/utils/LiveDataTestUtil.kt similarity index 100% rename from owncloudData/src/test-common/java/com/owncloud/android/data/utils/LiveDataTestUtil.kt rename to owncloudData/src/androidTest/java/com/owncloud/android/data/utils/LiveDataTestUtil.kt diff --git a/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt b/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt deleted file mode 100644 index a2b181e2fcb..00000000000 --- a/owncloudData/src/test-common/java/com/owncloud/android/data/utils/DataTestUtil.kt +++ /dev/null @@ -1,90 +0,0 @@ -/** - * ownCloud Android client application - * - * @author David González Verdugo - * @author Abel García de Prada - * Copyright (C) 2019 ownCloud GmbH. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program 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 this program. If not, see . - */ - -package com.owncloud.android.data.utils - -import com.owncloud.android.lib.common.operations.RemoteOperationResult -import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation -import io.mockk.every -import io.mockk.mockk -import org.json.JSONObject - -object DataTestUtil { - /** - * Sharees - */ - fun createSharee( - label: String, - shareType: String, - shareWith: String, - shareWithAdditionalInfo: String - ): JSONObject { - val jsonObject = JSONObject() - - jsonObject.put(GetRemoteShareesOperation.PROPERTY_LABEL, label) - - val value = JSONObject() - value.put(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE, shareType) - value.put(GetRemoteShareesOperation.PROPERTY_SHARE_WITH, shareWith) - value.put(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO, shareWithAdditionalInfo) - - jsonObject.put(GetRemoteShareesOperation.NODE_VALUE, value) - - return jsonObject - } - - fun createRemoteOperationResultMock( - data: T, - isSuccess: Boolean, - httpPhrase: String? = null, - resultCode: RemoteOperationResult.ResultCode? = null, - exception: Exception? = null - ): RemoteOperationResult { - val remoteOperationResult = mockk>(relaxed = true) - - every { - remoteOperationResult.data - } returns data - - every { - remoteOperationResult.isSuccess - } returns isSuccess - - if (httpPhrase != null) { - every { - remoteOperationResult.httpPhrase - } returns httpPhrase - } - - if (resultCode != null) { - every { - remoteOperationResult.code - } returns resultCode - } - - if (exception != null) { - every { - remoteOperationResult.exception - } returns exception - } - - return remoteOperationResult - } -} From 668c00c78f00cd5002183d799534a774e466bbd7 Mon Sep 17 00:00:00 2001 From: davigonz Date: Tue, 26 Nov 2019 17:47:27 +0100 Subject: [PATCH 30/41] Fix sqlite dependencies broken in FileContentProvider --- build.gradle | 1 + owncloudApp/build.gradle | 3 +++ 2 files changed, 4 insertions(+) diff --git a/build.gradle b/build.gradle index 5c6168a5764..8a435cf2c6b 100644 --- a/build.gradle +++ b/build.gradle @@ -6,6 +6,7 @@ buildscript { archLifecycleVersion = "2.1.0" roomVersion = "2.2.2" appCompat = "1.1.0" + sqliteVersion = "2.0.1" // Kotlin kotlinVersion = "1.3.50" diff --git a/owncloudApp/build.gradle b/owncloudApp/build.gradle index 02537878e4e..ab4798bb537 100644 --- a/owncloudApp/build.gradle +++ b/owncloudApp/build.gradle @@ -24,6 +24,7 @@ dependencies { implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation "androidx.browser:browser:$androidX" implementation 'commons-io:commons-io:2.6' + implementation "androidx.sqlite:sqlite:$sqliteVersion" // Tests testImplementation project(':owncloudTestUtil') @@ -67,6 +68,8 @@ dependencies { implementation "androidx.lifecycle:lifecycle-viewmodel:$archLifecycleVersion" kapt "androidx.lifecycle:lifecycle-common-java8:$archLifecycleVersion" + implementation "androidx.room:room-runtime:$roomVersion" + // Koin dependency injector implementation "org.koin:koin-androidx-viewmodel:$koinVersion" From c8115ba2de5381c8a444bceac337dab395b6a857 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Wed, 27 Nov 2019 10:01:36 +0100 Subject: [PATCH 31/41] Fix owncloudData tests --- .../data/sharing/shares/db/OCShareDaoTest.kt | 2 +- .../data/sharing/shares/db/OCShareEntity.kt | 2 - .../OCLocalCapabilitiesDataSourceTest.kt | 11 +- .../OCRemoteCapabilitiesDataSourceTest.kt | 18 ++-- .../OCLocalSharesDataSourceTest.kt | 101 +++++++----------- .../OCRemoteShareesDataSourceTest.kt | 42 +------- .../OCRemoteSharesDataSourceTest.kt | 20 ++-- .../mapper/OCRemoteShareMapperTest.kt | 12 ++- .../android/utils/InstantExecutors.kt | 26 ----- .../android/utils/RemoteOperationMock.kt | 33 ++++++ owncloudTestUtil/build.gradle | 4 +- .../com/owncloud/android/testutil/OCShare.kt | 1 + 12 files changed, 107 insertions(+), 165 deletions(-) rename owncloudData/src/{androidTest/java/com/owncloud/android/data/sharing/sharees => test/java/com/owncloud/android/data/shares}/datasources/OCRemoteShareesDataSourceTest.kt (80%) delete mode 100644 owncloudData/src/test/java/com/owncloud/android/utils/InstantExecutors.kt create mode 100644 owncloudData/src/test/java/com/owncloud/android/utils/RemoteOperationMock.kt diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt index d112aa27127..8bd47151af3 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt @@ -172,7 +172,7 @@ class OCShareDaoTest { ) )!!, ocShareMapper.toEntity( - OC_PUBLIC_SHARE.copy( + OC_PRIVATE_SHARE.copy( path = "/Documents/document1.docx", isFolder = false, accountOwner = "user3@server", diff --git a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/db/OCShareEntity.kt b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/db/OCShareEntity.kt index 00720c93f1e..09cecc9dbd6 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/db/OCShareEntity.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/db/OCShareEntity.kt @@ -27,8 +27,6 @@ import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.owncloud.android.data.ProviderMeta.ProviderTableMeta -import com.owncloud.android.domain.sharing.shares.model.ShareType -import com.owncloud.android.lib.resources.shares.RemoteShare /** * Represents one record of the Shares table. diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt index 5c517263627..3e60f80308e 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt @@ -26,8 +26,8 @@ import com.owncloud.android.data.capabilities.datasources.implementation.OCLocal import com.owncloud.android.data.capabilities.datasources.mapper.OCCapabilityMapper import com.owncloud.android.data.capabilities.db.OCCapabilityDao import com.owncloud.android.data.capabilities.db.OCCapabilityEntity -import com.owncloud.android.data.utils.LiveDataTestUtil.getValue import com.owncloud.android.testutil.OC_CAPABILITY +import com.owncloud.android.testutil.livedata.getLastEmittedValue import io.mockk.every import io.mockk.mockk import io.mockk.verify @@ -64,7 +64,8 @@ class OCLocalCapabilitiesDataSourceTest { capabilitiesLiveData.postValue(ocCapabilityMapper.toEntity(OC_CAPABILITY)) val capabilityEmitted = - getValue(ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!)) + ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!) + .getLastEmittedValue() assertEquals(OC_CAPABILITY, capabilityEmitted) } @@ -75,7 +76,8 @@ class OCLocalCapabilitiesDataSourceTest { every { ocCapabilityDao.getCapabilitiesForAccountAsLiveData(any()) } returns capabilitiesLiveData val capabilityEmitted = - getValue(ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!)) + ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!) + .getLastEmittedValue() assertNull(capabilityEmitted) } @@ -94,7 +96,8 @@ class OCLocalCapabilitiesDataSourceTest { every { ocCapabilityDao.getCapabilitiesForAccountAsLiveData(any()) } returns MutableLiveData() val capabilityEmitted = - getValue(ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!)) + ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!) + .getLastEmittedValue() assertNull(capabilityEmitted) } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt index 41449901355..af9b6c2aef1 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt @@ -23,14 +23,13 @@ package com.owncloud.android.data.capabilities.datasources import com.owncloud.android.data.capabilities.datasources.implementation.OCRemoteCapabilitiesDataSource import com.owncloud.android.data.capabilities.network.OCCapabilityService import com.owncloud.android.data.capabilities.datasources.mapper.RemoteCapabilityMapper -import com.owncloud.android.data.utils.DataTestUtil import com.owncloud.android.testutil.OC_ACCOUNT_NAME import com.owncloud.android.testutil.OC_CAPABILITY +import com.owncloud.android.utils.createRemoteOperationResultMock import io.mockk.every import io.mockk.mockk -import org.hamcrest.CoreMatchers.notNullValue -import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Test @@ -53,21 +52,16 @@ class OCRemoteCapabilitiesDataSourceTest { fun readRemoteCapabilities() { val accountName = OC_ACCOUNT_NAME - val remoteCapability = remoteCapabilityMapper.toRemote(OC_CAPABILITY) + val remoteCapability = remoteCapabilityMapper.toRemote(OC_CAPABILITY)!! - val getRemoteCapabilitiesOperationResult = DataTestUtil.createRemoteOperationResultMock( - remoteCapability, - true - ) + val getRemoteCapabilitiesOperationResult = createRemoteOperationResultMock(remoteCapability, true) - every { - ocCapabilityService.getCapabilities() - } returns getRemoteCapabilitiesOperationResult + every { ocCapabilityService.getCapabilities() } returns getRemoteCapabilitiesOperationResult // Get capability from remote datasource val capabilities = ocRemoteCapabilitiesDataSource.getCapabilities(accountName) - assertThat(capabilities, notNullValue()) + assertNotNull(capabilities) assertEquals(OC_CAPABILITY.accountName, capabilities.accountName) assertEquals(OC_CAPABILITY.versionMayor, capabilities.versionMayor) diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt index 5d402a46fdd..79b3812de3f 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCLocalSharesDataSourceTest.kt @@ -26,10 +26,10 @@ import com.owncloud.android.data.sharing.shares.datasources.implementation.OCLoc import com.owncloud.android.data.sharing.shares.datasources.mapper.OCShareMapper import com.owncloud.android.data.sharing.shares.db.OCShareDao import com.owncloud.android.data.sharing.shares.db.OCShareEntity -import com.owncloud.android.data.utils.LiveDataTestUtil.getValue import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.testutil.OC_PRIVATE_SHARE import com.owncloud.android.testutil.OC_PUBLIC_SHARE +import com.owncloud.android.testutil.livedata.getLastEmittedValue import io.mockk.every import io.mockk.mockkClass import org.junit.Assert.assertEquals @@ -82,9 +82,7 @@ class OCLocalDataSourceTest { )!! ) - private val privateShareTypes = listOf( - ShareType.USER, ShareType.GROUP, ShareType.FEDERATED - ) + private val privateShareTypes = listOf(ShareType.USER, ShareType.GROUP, ShareType.FEDERATED) @Test fun readLocalPrivateShares() { @@ -93,17 +91,15 @@ class OCLocalDataSourceTest { every { ocSharesDao.getSharesAsLiveData( - "/Docs/doc1.doc", "admin@server", privateShareTypes.map { - it.value - } - ) + "/Docs/doc1.doc", + "admin@server", + privateShareTypes.map { it.value }) } returns privateSharesAsLiveData - val shares = getValue( + val shares = ocLocalSharesDataSource.getSharesAsLiveData( "/Docs/doc1.doc", "admin@server", privateShareTypes - ) - ) + ).getLastEmittedValue()!! assertEquals(2, shares.size) @@ -123,13 +119,9 @@ class OCLocalDataSourceTest { val privateShareAsLiveData: MutableLiveData = MutableLiveData() privateShareAsLiveData.value = privateShares.first() - every { - ocSharesDao.getShareAsLiveData(1) - } returns privateShareAsLiveData + every { ocSharesDao.getShareAsLiveData(1) } returns privateShareAsLiveData - val share = getValue( - ocLocalSharesDataSource.getShareAsLiveData(1) - ) + val share = ocLocalSharesDataSource.getShareAsLiveData(1).getLastEmittedValue()!! assertEquals("/Docs/doc1.doc", share.path) assertEquals(false, share.isFolder) @@ -142,11 +134,7 @@ class OCLocalDataSourceTest { val privateSharesAsLiveData: MutableLiveData> = MutableLiveData() privateSharesAsLiveData.value = privateShares - every { - ocSharesDao.insert( - privateSharesAsLiveData.value!![0] - ) - } returns 10 + every { ocSharesDao.insert(privateSharesAsLiveData.value!![0]) } returns 10 val insertedShareId = ocLocalSharesDataSource.insert( OC_PRIVATE_SHARE.copy( @@ -163,11 +151,7 @@ class OCLocalDataSourceTest { val privateSharesAsLiveData: MutableLiveData> = MutableLiveData() privateSharesAsLiveData.value = privateShares - every { - ocSharesDao.update( - privateSharesAsLiveData.value!![1] - ) - } returns 3 + every { ocSharesDao.update(privateSharesAsLiveData.value!![1]) } returns 3 val updatedShareId = ocLocalSharesDataSource.update( OC_PRIVATE_SHARE.copy( @@ -186,18 +170,20 @@ class OCLocalDataSourceTest { private val publicShares = listOf( ocShareMapper.toEntity( OC_PUBLIC_SHARE.copy( - path = "/Photos/", - isFolder = true, - name = "Photos link", - shareLink = "http://server:port/s/1" - ))!!, - ocShareMapper.toEntity( - OC_PUBLIC_SHARE.copy( - path = "/Photos/", - isFolder = true, - name = "Photos link 2", - shareLink = "http://server:port/s/2" - ))!! + path = "/Photos/", + isFolder = true, + name = "Photos link", + shareLink = "http://server:port/s/1" + ) + )!!, + ocShareMapper.toEntity( + OC_PUBLIC_SHARE.copy( + path = "/Photos/", + isFolder = true, + name = "Photos link 2", + shareLink = "http://server:port/s/2" + ) + )!! ) @Test @@ -207,15 +193,17 @@ class OCLocalDataSourceTest { every { ocSharesDao.getSharesAsLiveData( - "/Photos/", "admin@server", listOf(ShareType.PUBLIC_LINK.value) + "/Photos/", + "admin@server", + listOf(ShareType.PUBLIC_LINK.value) ) } returns publicSharesAsLiveData - val shares = getValue( - ocLocalSharesDataSource.getSharesAsLiveData( - "/Photos/", "admin@server", listOf(ShareType.PUBLIC_LINK) - ) - ) + val shares = ocLocalSharesDataSource.getSharesAsLiveData( + "/Photos/", + "admin@server", + listOf(ShareType.PUBLIC_LINK) + ).getLastEmittedValue()!! assertEquals(2, shares.size) @@ -235,11 +223,7 @@ class OCLocalDataSourceTest { val publicSharesAsLiveData: MutableLiveData> = MutableLiveData() publicSharesAsLiveData.value = publicShares - every { - ocSharesDao.insert( - publicSharesAsLiveData.value!![0] - ) - } returns 7 + every { ocSharesDao.insert(publicSharesAsLiveData.value!![0]) } returns 7 val insertedShareId = ocLocalSharesDataSource.insert( OC_PUBLIC_SHARE.copy( @@ -257,11 +241,7 @@ class OCLocalDataSourceTest { val publicSharesAsLiveData: MutableLiveData> = MutableLiveData() publicSharesAsLiveData.value = publicShares - every { - ocSharesDao.update( - publicSharesAsLiveData.value!![1] - ) - } returns 8 + every { ocSharesDao.update(publicSharesAsLiveData.value!![1]) } returns 8 val updatedShareId = ocLocalSharesDataSource.update( OC_PUBLIC_SHARE.copy( @@ -280,15 +260,10 @@ class OCLocalDataSourceTest { @Test fun deleteShare() { - every { - ocSharesDao.deleteShare( - 5 - ) - } returns 1 + every { ocSharesDao.deleteShare(5) } returns 1 + + val deletedRows = ocLocalSharesDataSource.deleteShare(5) - val deletedRows = ocLocalSharesDataSource.deleteShare( - 5 - ) assertEquals(1, deletedRows) } } diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteShareesDataSourceTest.kt similarity index 80% rename from owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt rename to owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteShareesDataSourceTest.kt index 3bbd52ba205..05535d8cd4e 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/sharees/datasources/OCRemoteShareesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteShareesDataSourceTest.kt @@ -17,12 +17,12 @@ * along with this program. If not, see . */ -package com.owncloud.android.data.sharing.sharees.datasources +package com.owncloud.android.data.shares.datasources import com.owncloud.android.data.sharing.sharees.datasources.implementation.OCRemoteShareeDataSource import com.owncloud.android.data.sharing.sharees.network.OCShareeService -import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation +import com.owncloud.android.utils.createRemoteOperationResultMock import io.mockk.every import io.mockk.mockk import org.json.JSONObject @@ -93,44 +93,6 @@ class OCRemoteShareesDataSourceTest { assertEquals(value3.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH_ADDITIONAL_INFO), "user3@mail.com") } - private fun createRemoteOperationResultMock( - data: T, - isSuccess: Boolean, - httpPhrase: String? = null, - resultCode: RemoteOperationResult.ResultCode? = null, - exception: Exception? = null - ): RemoteOperationResult { - val remoteOperationResult = mockk>(relaxed = true) - - every { - remoteOperationResult.data - } returns data - - every { - remoteOperationResult.isSuccess - } returns isSuccess - - if (httpPhrase != null) { - every { - remoteOperationResult.httpPhrase - } returns httpPhrase - } - - if (resultCode != null) { - every { - remoteOperationResult.code - } returns resultCode - } - - if (exception != null) { - every { - remoteOperationResult.exception - } returns exception - } - - return remoteOperationResult - } - private fun createSharee( label: String, shareType: String, diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt index 4080fe3775f..482b470d2a1 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/OCRemoteSharesDataSourceTest.kt @@ -23,13 +23,13 @@ package com.owncloud.android.data.shares.datasources import com.owncloud.android.data.sharing.shares.datasources.implementation.OCRemoteShareDataSource import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteShareMapper import com.owncloud.android.data.sharing.shares.network.OCShareService -import com.owncloud.android.data.utils.DataTestUtil import com.owncloud.android.domain.exceptions.ShareForbiddenException import com.owncloud.android.domain.exceptions.ShareNotFoundException import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.shares.ShareParserResult import com.owncloud.android.testutil.OC_SHARE +import com.owncloud.android.utils.createRemoteOperationResultMock import io.mockk.every import io.mockk.mockk import org.hamcrest.CoreMatchers.notNullValue @@ -55,7 +55,7 @@ class OCRemoteShareDataSourceTest { @Test fun insertPrivateShare() { - val createRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( + val createRemoteShareOperationResult = createRemoteOperationResultMock( ShareParserResult( listOf( remoteShareMapper.toRemote( @@ -96,7 +96,7 @@ class OCRemoteShareDataSourceTest { @Test fun updatePrivateShare() { - val updateRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( + val updateRemoteShareOperationResult = createRemoteOperationResultMock( ShareParserResult( listOf( remoteShareMapper.toRemote( @@ -140,7 +140,7 @@ class OCRemoteShareDataSourceTest { @Test fun insertPublicShare() { - val createRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( + val createRemoteShareOperationResult = createRemoteOperationResultMock( ShareParserResult( listOf( remoteShareMapper.toRemote( @@ -181,7 +181,7 @@ class OCRemoteShareDataSourceTest { @Test fun updatePublicShare() { - val updateRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( + val updateRemoteShareOperationResult = createRemoteOperationResultMock( ShareParserResult( listOf( remoteShareMapper.toRemote( @@ -261,7 +261,7 @@ class OCRemoteShareDataSourceTest { )!! ) - val getRemoteSharesOperationResult = DataTestUtil.createRemoteOperationResultMock( + val getRemoteSharesOperationResult = createRemoteOperationResultMock( ShareParserResult(remoteShares), true ) @@ -320,7 +320,7 @@ class OCRemoteShareDataSourceTest { } private fun createShareOperationWithError(resultCode: RemoteOperationResult.ResultCode? = null) { - val createRemoteSharesOperationResult = DataTestUtil.createRemoteOperationResultMock( + val createRemoteSharesOperationResult = createRemoteOperationResultMock( ShareParserResult(arrayListOf()), false, null, @@ -351,7 +351,7 @@ class OCRemoteShareDataSourceTest { } private fun updateShareOperationWithError(resultCode: RemoteOperationResult.ResultCode? = null) { - val updateRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( + val updateRemoteShareOperationResult = createRemoteOperationResultMock( ShareParserResult(arrayListOf()), false, null, @@ -371,7 +371,7 @@ class OCRemoteShareDataSourceTest { @Test fun deleteShare() { - val removeRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( + val removeRemoteShareOperationResult = createRemoteOperationResultMock( ShareParserResult(arrayListOf()), isSuccess = true ) @@ -396,7 +396,7 @@ class OCRemoteShareDataSourceTest { } private fun deleteShareOperationWithError(resultCode: RemoteOperationResult.ResultCode? = null) { - val removeRemoteShareOperationResult = DataTestUtil.createRemoteOperationResultMock( + val removeRemoteShareOperationResult = createRemoteOperationResultMock( ShareParserResult(arrayListOf()), false, null, diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt index 211e3a447fd..688f1118fcf 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCRemoteShareMapperTest.kt @@ -21,7 +21,9 @@ package com.owncloud.android.data.shares.datasources.mapper import com.owncloud.android.data.sharing.shares.datasources.mapper.RemoteShareMapper import com.owncloud.android.testutil.OC_SHARE -import org.junit.Assert +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull import org.junit.Test class OCRemoteShareMapperTest { @@ -30,16 +32,16 @@ class OCRemoteShareMapperTest { @Test fun checkToModelNull() { - Assert.assertNull(ocRemoteShareMapper.toModel(null)) + assertNull(ocRemoteShareMapper.toModel(null)) } @Test fun checkToModelNotNull() { val remoteShare = ocRemoteShareMapper.toRemote(OC_SHARE) - Assert.assertNotNull(remoteShare) + assertNotNull(remoteShare) val share = ocRemoteShareMapper.toModel(remoteShare) - Assert.assertNotNull(share) - Assert.assertEquals(OC_SHARE, share) + assertNotNull(share) + assertEquals(OC_SHARE, share) } } diff --git a/owncloudData/src/test/java/com/owncloud/android/utils/InstantExecutors.kt b/owncloudData/src/test/java/com/owncloud/android/utils/InstantExecutors.kt deleted file mode 100644 index 0f2a09cb68a..00000000000 --- a/owncloudData/src/test/java/com/owncloud/android/utils/InstantExecutors.kt +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.owncloud.android.utils - -import com.owncloud.android.data.Executors -import java.util.concurrent.Executor - -class InstantExecutors : Executors(instant, instant, instant) { - companion object { - private val instant = Executor { it.run() } - } -} diff --git a/owncloudData/src/test/java/com/owncloud/android/utils/RemoteOperationMock.kt b/owncloudData/src/test/java/com/owncloud/android/utils/RemoteOperationMock.kt new file mode 100644 index 00000000000..03d1087f012 --- /dev/null +++ b/owncloudData/src/test/java/com/owncloud/android/utils/RemoteOperationMock.kt @@ -0,0 +1,33 @@ +package com.owncloud.android.utils + +import com.owncloud.android.lib.common.operations.RemoteOperationResult +import io.mockk.every +import io.mockk.mockk + + fun createRemoteOperationResultMock( + data: T, + isSuccess: Boolean, + httpPhrase: String? = null, + resultCode: RemoteOperationResult.ResultCode? = null, + exception: Exception? = null +): RemoteOperationResult { + val remoteOperationResult = mockk>(relaxed = true) + + every { remoteOperationResult.data } returns data + + every { remoteOperationResult.isSuccess } returns isSuccess + + if (httpPhrase != null) { + every { remoteOperationResult.httpPhrase } returns httpPhrase + } + + if (resultCode != null) { + every { remoteOperationResult.code } returns resultCode + } + + if (exception != null) { + every { remoteOperationResult.exception } returns exception + } + + return remoteOperationResult +} diff --git a/owncloudTestUtil/build.gradle b/owncloudTestUtil/build.gradle index 81fbf262d42..f3222dcc8b7 100644 --- a/owncloudTestUtil/build.gradle +++ b/owncloudTestUtil/build.gradle @@ -20,6 +20,6 @@ android { dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation project(':owncloudDomain') - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" - implementation "androidx.lifecycle:lifecycle-livedata-ktx:$ktxLiveData" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" + implementation "androidx.lifecycle:lifecycle-livedata:2.0.0" } diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt index 2eee756af03..b067d16fca5 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt @@ -4,6 +4,7 @@ import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType val OC_SHARE = OCShare( + id = 0, fileSource = 7, itemSource = 7, shareType = ShareType.USER, // Private share by default From 2f58165ad8a5a494b2c1fbc4a2aa5d13420888dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Wed, 27 Nov 2019 12:29:49 +0100 Subject: [PATCH 32/41] Update schemas location --- .../27.json | 0 .../28.json | 48 +++++++++---------- 2 files changed, 24 insertions(+), 24 deletions(-) rename {owncloudApp/schemas/com.owncloud.android.db.OwncloudDatabase => owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase}/27.json (100%) rename {owncloudApp/schemas/com.owncloud.android.db.OwncloudDatabase => owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase}/28.json (84%) diff --git a/owncloudApp/schemas/com.owncloud.android.db.OwncloudDatabase/27.json b/owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase/27.json similarity index 100% rename from owncloudApp/schemas/com.owncloud.android.db.OwncloudDatabase/27.json rename to owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase/27.json diff --git a/owncloudApp/schemas/com.owncloud.android.db.OwncloudDatabase/28.json b/owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase/28.json similarity index 84% rename from owncloudApp/schemas/com.owncloud.android.db.OwncloudDatabase/28.json rename to owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase/28.json index 6317f3f566f..44e4702a066 100644 --- a/owncloudApp/schemas/com.owncloud.android.db.OwncloudDatabase/28.json +++ b/owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase/28.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 28, - "identityHash": "8ed0b6d76a72af8df6e792f9dcb43b2d", + "identityHash": "a1afd9487db21ba5b69279ed4f42749d", "entities": [ { "tableName": "ocshares", @@ -128,7 +128,7 @@ }, { "tableName": "capabilities", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL, `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `sharing_api_enabled` INTEGER, `search_min_length` INTEGER, `sharing_public_enabled` INTEGER, `sharing_public_password_enforced` INTEGER, `sharing_public_password_enforced_read_only` INTEGER, `sharing_public_password_enforced_read_write` INTEGER, `sharing_public_password_enforced_public_only` INTEGER, `sharing_public_expire_date_enabled` INTEGER, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced` INTEGER, `sharing_public_send_mail` INTEGER, `sharing_public_upload` INTEGER, `sharing_public_multiple` INTEGER, `supports_upload_only` INTEGER, `sharing_user_send_mail` INTEGER, `sharing_resharing` INTEGER, `sharing_federation_outgoing` INTEGER, `sharing_federation_incoming` INTEGER, `files_bigfilechunking` INTEGER, `files_undelete` INTEGER, `files_versioning` INTEGER)", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL, `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `filesSharingApiEnabled` INTEGER NOT NULL, `search_min_length` INTEGER NOT NULL, `sharing_public_enabled` INTEGER NOT NULL, `sharing_public_password_enforced` INTEGER NOT NULL, `sharing_public_password_enforced_read_only` INTEGER NOT NULL, `sharing_public_password_enforced_read_write` INTEGER NOT NULL, `sharing_public_password_enforced_public_only` INTEGER NOT NULL, `sharing_public_expire_date_enabled` INTEGER NOT NULL, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced` INTEGER NOT NULL, `sharing_public_send_mail` INTEGER NOT NULL, `sharing_public_upload` INTEGER NOT NULL, `sharing_public_multiple` INTEGER NOT NULL, `supports_upload_only` INTEGER NOT NULL, `sharing_user_send_mail` INTEGER NOT NULL, `sharing_resharing` INTEGER NOT NULL, `sharing_federation_outgoing` INTEGER NOT NULL, `sharing_federation_incoming` INTEGER NOT NULL, `files_bigfilechunking` INTEGER NOT NULL, `files_undelete` INTEGER NOT NULL, `files_versioning` INTEGER NOT NULL)", "fields": [ { "fieldPath": "id", @@ -180,51 +180,51 @@ }, { "fieldPath": "filesSharingApiEnabled", - "columnName": "sharing_api_enabled", + "columnName": "filesSharingApiEnabled", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingSearchMinLength", "columnName": "search_min_length", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicEnabled", "columnName": "sharing_public_enabled", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicPasswordEnforced", "columnName": "sharing_public_password_enforced", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicPasswordEnforcedReadOnly", "columnName": "sharing_public_password_enforced_read_only", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicPasswordEnforcedReadWrite", "columnName": "sharing_public_password_enforced_read_write", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicPasswordEnforcedUploadOnly", "columnName": "sharing_public_password_enforced_public_only", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicExpireDateEnabled", "columnName": "sharing_public_expire_date_enabled", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicExpireDateDays", @@ -236,73 +236,73 @@ "fieldPath": "filesSharingPublicExpireDateEnforced", "columnName": "sharing_public_expire_date_enforced", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicSendMail", "columnName": "sharing_public_send_mail", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicUpload", "columnName": "sharing_public_upload", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicMultiple", "columnName": "sharing_public_multiple", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingPublicSupportsUploadOnly", "columnName": "supports_upload_only", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingUserSendMail", "columnName": "sharing_user_send_mail", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingResharing", "columnName": "sharing_resharing", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingFederationOutgoing", "columnName": "sharing_federation_outgoing", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesSharingFederationIncoming", "columnName": "sharing_federation_incoming", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesBigFileChunking", "columnName": "files_bigfilechunking", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesUndelete", "columnName": "files_undelete", "affinity": "INTEGER", - "notNull": false + "notNull": true }, { "fieldPath": "filesVersioning", "columnName": "files_versioning", "affinity": "INTEGER", - "notNull": false + "notNull": true } ], "primaryKey": { @@ -318,7 +318,7 @@ "views": [], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", - "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '8ed0b6d76a72af8df6e792f9dcb43b2d')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'a1afd9487db21ba5b69279ed4f42749d')" ] } } \ No newline at end of file From ed92c45c6db6df51d3623659821a19a6b275fe1a Mon Sep 17 00:00:00 2001 From: davigonz Date: Wed, 27 Nov 2019 13:24:41 +0100 Subject: [PATCH 33/41] Fix a few more tests after the recent changes --- .../ui/helpers/FileOperationsHelper.java | 1 - .../data/sharing/shares/db/OCShareDaoTest.kt | 9 ++-- .../mapper/RemoteCapabilityMapper.kt | 47 +++++++++++++++++-- .../datasources/mapper/RemoteShareMapper.kt | 28 +++++++++-- .../OCLocalCapabilitiesDataSourceTest.kt | 23 +++++---- .../mapper/OCCapabilityMapperTest.kt | 7 +-- .../datasources/mapper/OCShareMapperTest.kt | 20 +------- .../owncloud/android/testutil/OCCapability.kt | 3 +- .../com/owncloud/android/testutil/OCShare.kt | 2 - 9 files changed, 92 insertions(+), 48 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java b/owncloudApp/src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java index d685aeaa006..53abdcd4c62 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java +++ b/owncloudApp/src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java @@ -187,7 +187,6 @@ public boolean isSharedSupported() { * @param share The {@link OCShare} to remove (unshare). */ public void removeShare(OCShare share) { - Intent unshareService = new Intent(mFileActivity, OperationsService.class); unshareService.setAction(OperationsService.ACTION_UNSHARE); unshareService.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId()); diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt index 8bd47151af3..aefc212e2a0 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt @@ -87,7 +87,8 @@ class OCShareDaoTest { path = "/Photos/", isFolder = true, name = "Photos folder link", - shareLink = "http://server:port/s/1" + shareLink = "http://server:port/s/1", + accountOwner = "admin@server" ) )!!, ocShareMapper.toEntity( @@ -95,7 +96,8 @@ class OCShareDaoTest { path = "/Photos/image1.jpg", isFolder = false, name = "Image 1 link", - shareLink = "http://server:port/s/2" + shareLink = "http://server:port/s/2", + accountOwner = "admin@server" ) )!!, ocShareMapper.toEntity( @@ -103,7 +105,8 @@ class OCShareDaoTest { path = "/Photos/image2.jpg", isFolder = false, shareWith = "username", - sharedWithDisplayName = "John" + sharedWithDisplayName = "John", + accountOwner = "admin@server" ) )!! ) diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt index ecbb0fc383b..0fefdef4ef8 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt @@ -23,6 +23,7 @@ import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.mappers.RemoteMapper import com.owncloud.android.lib.resources.status.RemoteCapability +import com.owncloud.android.lib.resources.status.CapabilityBooleanType as RemoteCapabilityBooleanType class RemoteCapabilityMapper : RemoteMapper { override fun toModel(remote: RemoteCapability?): OCCapability? = @@ -68,7 +69,47 @@ class RemoteCapabilityMapper : RemoteMapper { ) } - override fun toRemote(model: OCCapability?): RemoteCapability? { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } + override fun toRemote(model: OCCapability?): RemoteCapability? = + model?.let { + RemoteCapability( + accountName = model.accountName!!, + versionMayor = model.versionMayor, + versionMinor = model.versionMinor, + versionMicro = model.versionMicro, + versionString = model.versionString!!, + versionEdition = model.versionEdition!!, + corePollinterval = model.corePollInterval, + filesSharingApiEnabled = RemoteCapabilityBooleanType.fromValue(model.filesSharingApiEnabled.value)!!, + filesSharingSearchMinLength = model.filesSharingSearchMinLength, + filesSharingPublicEnabled = RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicEnabled.value)!!, + filesSharingPublicPasswordEnforced = + RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicPasswordEnforced.value)!!, + filesSharingPublicPasswordEnforcedReadOnly = + RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicPasswordEnforcedReadOnly.value)!!, + filesSharingPublicPasswordEnforcedReadWrite = + RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicPasswordEnforcedReadWrite.value)!!, + filesSharingPublicPasswordEnforcedUploadOnly = + RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicPasswordEnforcedUploadOnly.value)!!, + filesSharingPublicExpireDateEnabled = + RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicExpireDateEnabled.value)!!, + filesSharingPublicExpireDateDays = model.filesSharingPublicExpireDateDays, + filesSharingPublicExpireDateEnforced = + RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicExpireDateEnforced.value)!!, + filesSharingPublicSendMail = RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicSendMail.value)!!, + filesSharingPublicUpload = RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicUpload.value)!!, + filesSharingPublicMultiple = RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicMultiple.value)!!, + filesSharingPublicSupportsUploadOnly = + RemoteCapabilityBooleanType.fromValue(model.filesSharingPublicSupportsUploadOnly.value)!!, + filesSharingUserSendMail = RemoteCapabilityBooleanType.fromValue(model.filesSharingUserSendMail.value)!!, + filesSharingResharing = RemoteCapabilityBooleanType.fromValue(model.filesSharingResharing.value)!!, + filesSharingFederationOutgoing = + RemoteCapabilityBooleanType.fromValue(model.filesSharingFederationOutgoing.value)!!, + filesSharingFederationIncoming = + RemoteCapabilityBooleanType.fromValue(model.filesSharingFederationIncoming.value)!!, + filesBigFileChunking = RemoteCapabilityBooleanType.fromValue(model.filesBigFileChunking.value)!!, + filesUndelete = RemoteCapabilityBooleanType.fromValue(model.filesUndelete.value)!!, + filesVersioning = RemoteCapabilityBooleanType.fromValue(model.filesVersioning.value)!! + ) + } + } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/mapper/RemoteShareMapper.kt b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/mapper/RemoteShareMapper.kt index 51435b9bdfe..0baa5748d28 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/mapper/RemoteShareMapper.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/mapper/RemoteShareMapper.kt @@ -23,6 +23,8 @@ import com.owncloud.android.domain.mappers.RemoteMapper import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.lib.resources.shares.RemoteShare +import org.jetbrains.annotations.TestOnly +import com.owncloud.android.lib.resources.shares.ShareType as RemoteShareType class RemoteShareMapper : RemoteMapper { override fun toModel(remote: RemoteShare?): OCShare? = @@ -47,7 +49,27 @@ class RemoteShareMapper : RemoteMapper { ) } - override fun toRemote(model: OCShare?): RemoteShare? { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } + @TestOnly + override fun toRemote(model: OCShare?): RemoteShare? = + model?.let { + RemoteShare( + id = model.remoteId, + shareWith = model.shareWith!!, + path = model.path, + token = model.token!!, + sharedWithDisplayName = model.sharedWithDisplayName!!, + sharedWithAdditionalInfo = model.sharedWithAdditionalInfo!!, + name = model.name!!, + shareLink = model.shareLink!!, + fileSource = model.fileSource, + itemSource = model.itemSource, + shareType = RemoteShareType.fromValue(model.shareType.value), + permissions = model.permissions, + sharedDate = model.sharedDate, + expirationDate = model.expirationDate, + isFolder = model.isFolder, + userId = model.userId, + isValid = model.remoteId > -1 + ) + } } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt index 3e60f80308e..256e1a52c15 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCLocalCapabilitiesDataSourceTest.kt @@ -43,6 +43,9 @@ class OCLocalCapabilitiesDataSourceTest { private val ocCapabilityDao = mockk(relaxed = true) private val ocCapabilityMapper = OCCapabilityMapper() + private val ocCapability = OC_CAPABILITY.copy(id = 0) + private val ocCapabilityEntity = ocCapabilityMapper.toEntity(ocCapability) + @Rule @JvmField var rule: TestRule = InstantTaskExecutorRule() @@ -61,13 +64,13 @@ class OCLocalCapabilitiesDataSourceTest { val capabilitiesLiveData = MutableLiveData() every { ocCapabilityDao.getCapabilitiesForAccountAsLiveData(any()) } returns capabilitiesLiveData - capabilitiesLiveData.postValue(ocCapabilityMapper.toEntity(OC_CAPABILITY)) + capabilitiesLiveData.postValue(ocCapabilityEntity) val capabilityEmitted = - ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!) + ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(ocCapability.accountName!!) .getLastEmittedValue() - assertEquals(OC_CAPABILITY, capabilityEmitted) + assertEquals(ocCapability, capabilityEmitted) } @Test @@ -76,7 +79,7 @@ class OCLocalCapabilitiesDataSourceTest { every { ocCapabilityDao.getCapabilitiesForAccountAsLiveData(any()) } returns capabilitiesLiveData val capabilityEmitted = - ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!) + ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(ocCapability.accountName!!) .getLastEmittedValue() assertNull(capabilityEmitted) @@ -84,11 +87,11 @@ class OCLocalCapabilitiesDataSourceTest { @Test fun getCapabilitiesForAccount() { - every { ocCapabilityDao.getCapabilitiesForAccount(any()) } returns ocCapabilityMapper.toEntity(OC_CAPABILITY)!! + every { ocCapabilityDao.getCapabilitiesForAccount(any()) } returns ocCapabilityEntity!! - val capabilityEmitted = ocLocalCapabilitiesDataSource.getCapabilityForAccount(OC_CAPABILITY.accountName!!) + val capabilityEmitted = ocLocalCapabilitiesDataSource.getCapabilityForAccount(ocCapability.accountName!!) - assertEquals(OC_CAPABILITY, capabilityEmitted) + assertEquals(ocCapability, capabilityEmitted) } @Test @@ -96,7 +99,7 @@ class OCLocalCapabilitiesDataSourceTest { every { ocCapabilityDao.getCapabilitiesForAccountAsLiveData(any()) } returns MutableLiveData() val capabilityEmitted = - ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!) + ocLocalCapabilitiesDataSource.getCapabilitiesForAccountAsLiveData(ocCapability.accountName!!) .getLastEmittedValue() assertNull(capabilityEmitted) @@ -106,8 +109,8 @@ class OCLocalCapabilitiesDataSourceTest { fun insertCapabilities() { every { ocCapabilityDao.replace(any()) } returns Unit - ocLocalCapabilitiesDataSource.insert(listOf(OC_CAPABILITY)) + ocLocalCapabilitiesDataSource.insert(listOf(ocCapability)) - verify(exactly = 1) { ocCapabilityDao.replace(listOf(ocCapabilityMapper.toEntity(OC_CAPABILITY)!!)) } + verify(exactly = 1) { ocCapabilityDao.replace(listOf(ocCapabilityEntity!!)) } } } diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt index 1bd7826e7a9..9b1d197b766 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapperTest.kt @@ -27,7 +27,7 @@ class OCCapabilityMapperTest { private val ocCapabilityMapper = OCCapabilityMapper() - private val ocCapability = OC_CAPABILITY + private val ocCapability = OC_CAPABILITY.copy(id = 0) private val ocCapabilityEntity = ocCapabilityMapper.toEntity(ocCapability) @Test @@ -42,11 +42,6 @@ class OCCapabilityMapperTest { val model = ocCapabilityMapper.toModel(ocCapabilityEntity) Assert.assertNotNull(model) Assert.assertEquals(ocCapability, model) - - val mappedEntity = ocCapabilityMapper.toEntity(model) - Assert.assertNotNull(mappedEntity) - - Assert.assertEquals(ocCapabilityEntity, mappedEntity) } @Test diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt index 68d55ea34c7..c363f14ffff 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/datasources/mapper/OCShareMapperTest.kt @@ -27,19 +27,8 @@ import org.junit.Test class OCShareMapperTest { private val ocShareMapper = OCShareMapper() - private val ocShare = - OC_SHARE.copy( - isFolder = false, - path = "/Photos/image2.jpg" - ) - - private val ocShareEntity = - ocShareMapper.toEntity( - OC_SHARE.copy( - isFolder = false, - path = "/Photos/image2.jpg" - ) - ) + private val ocShare = OC_SHARE.copy(id = 0) + private val ocShareEntity = ocShareMapper.toEntity(OC_SHARE) @Test fun checkToModelNull() { @@ -53,11 +42,6 @@ class OCShareMapperTest { val model = ocShareMapper.toModel(ocShareEntity) Assert.assertNotNull(model) Assert.assertEquals(ocShare, model) - - val mappedEntity = ocShareMapper.toEntity(model) - Assert.assertNotNull(mappedEntity) - - Assert.assertEquals(ocShareEntity, mappedEntity) } @Test diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt index 47a70dabff1..f84e71f512c 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCCapability.kt @@ -5,8 +5,7 @@ import com.owncloud.android.domain.capabilities.model.OCCapability val OC_CAPABILITY = OCCapability( - id = 0, - accountName = "user@server", + accountName = "admin@server", versionMayor = 2, versionMinor = 1, versionMicro = 0, diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt index b067d16fca5..5437176e2f8 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/OCShare.kt @@ -4,7 +4,6 @@ import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType val OC_SHARE = OCShare( - id = 0, fileSource = 7, itemSource = 7, shareType = ShareType.USER, // Private share by default @@ -19,7 +18,6 @@ val OC_SHARE = OCShare( isFolder = false, userId = -1, remoteId = 1, - accountOwner = "admin@server", name = "", shareLink = "" ) From 52bf7272c339ae9653cdc9eb3400bd9ce574bca5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Thu, 28 Nov 2019 13:56:17 +0100 Subject: [PATCH 34/41] Fix migration tests --- .../datamodel/FileDataStorageManager.kt | 190 ++++++++++----- .../sharing/UsersAndGroupsSearchProvider.kt | 1 - .../ui/sharing/fragments/ShareFileFragment.kt | 12 +- .../28.json | 70 ++++-- .../owncloud/android/data/MigrationTest.kt | 143 +++++++----- .../owncloud/android/data/OwncloudDatabase.kt | 17 +- .../datasources/mapper/OCCapabilityMapper.kt | 48 ++-- .../mapper/RemoteCapabilityMapper.kt | 38 +-- .../capabilities/db/OCCapabilityEntity.kt | 218 ++++++++++-------- .../domain/capabilities/model/OCCapability.kt | 18 +- .../capabilities/model/OCCapabilityTest.kt | 3 +- 11 files changed, 439 insertions(+), 319 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt index 1d17c4e4bef..6c0b48c1bb2 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.kt @@ -1122,16 +1122,16 @@ class FileDataStorageManager { whereBuffer.append("?") whereBuffer.append(")") - try { - performUpdate( - uri = CONTENT_URI_FILE, - contentValues = cv, - where = whereBuffer.toString(), - selectionArgs = ancestorIds.toTypedArray() - ) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) - } + try { + performUpdate( + uri = CONTENT_URI_FILE, + contentValues = cv, + where = whereBuffer.toString(), + selectionArgs = ancestorIds.toTypedArray() + ) + } catch (e: RemoteException) { + Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) + } } // else file is ROOT folder, no parent to set in conflict } else { @@ -1167,16 +1167,16 @@ class FileDataStorageManager { if (descendantsInConflict == null || descendantsInConflict.count == 0) { Log_OC.d(TAG, "NO MORE conflicts in $parentPath") - try { - performUpdate( - uri = CONTENT_URI_FILE, - contentValues = cv, - where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?", - selectionArgs = arrayOf(account.name, parentPath) - ) - } catch (e: RemoteException) { - Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) - } + try { + performUpdate( + uri = CONTENT_URI_FILE, + contentValues = cv, + where = "$FILE_ACCOUNT_OWNER=? AND $FILE_PATH=?", + selectionArgs = arrayOf(account.name, parentPath) + ) + } catch (e: RemoteException) { + Log_OC.e(TAG, "Failed saving conflict in database ${e.message}", e) + } } else { Log_OC.d(TAG, "STILL ${descendantsInConflict.count} in $parentPath") @@ -1311,63 +1311,137 @@ class FileDataStorageManager { versionEdition = c.getString(c.getColumnIndex(CAPABILITIES_VERSION_EDITION)), corePollInterval = c.getInt(c.getColumnIndex(CAPABILITIES_CORE_POLLINTERVAL)), filesSharingApiEnabled = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_API_ENABLED)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_API_ENABLED + ) + ) + ), filesSharingPublicEnabled = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_ENABLED)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_ENABLED + ) + ) + ), filesSharingPublicPasswordEnforced = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED + ) + ) + ), filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY + ) + ) + ), filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE + ) + ) + ), filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY + ) + ) + ), filesSharingPublicExpireDateEnabled = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED + ) + ) + ), filesSharingPublicExpireDateDays = c.getInt( - c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS) + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS + ) ), filesSharingPublicExpireDateEnforced = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED + ) + ) + ), filesSharingPublicSendMail = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_SEND_MAIL)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_SEND_MAIL + ) + ) + ), filesSharingPublicUpload = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_UPLOAD)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_UPLOAD + ) + ) + ), filesSharingPublicMultiple = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_MULTIPLE)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_MULTIPLE + ) + ) + ), filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY + ) + ) + ), filesSharingUserSendMail = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_USER_SEND_MAIL)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_USER_SEND_MAIL + ) + ) + ), filesSharingResharing = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_RESHARING)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_RESHARING + ) + ) + ), filesSharingFederationOutgoing = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_FEDERATION_OUTGOING)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_FEDERATION_OUTGOING + ) + ) + ), filesSharingFederationIncoming = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_SHARING_FEDERATION_INCOMING)) - )!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_SHARING_FEDERATION_INCOMING + ) + ) + ), filesBigFileChunking = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_FILES_BIGFILECHUNKING)) - )!!, - filesUndelete = CapabilityBooleanType.fromValue(c.getInt(c.getColumnIndex(CAPABILITIES_FILES_UNDELETE)))!!, + c.getInt( + c.getColumnIndex( + CAPABILITIES_FILES_BIGFILECHUNKING + ) + ) + ), + filesUndelete = CapabilityBooleanType.fromValue(c.getInt(c.getColumnIndex(CAPABILITIES_FILES_UNDELETE))), filesVersioning = CapabilityBooleanType.fromValue( - c.getInt(c.getColumnIndex(CAPABILITIES_FILES_VERSIONING)) - )!! + c.getInt( + c.getColumnIndex( + CAPABILITIES_FILES_VERSIONING + ) + ) + ) ) } return capability diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/providers/sharing/UsersAndGroupsSearchProvider.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/providers/sharing/UsersAndGroupsSearchProvider.kt index 6bae0e5ccab..b8c0689d0bb 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/providers/sharing/UsersAndGroupsSearchProvider.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/providers/sharing/UsersAndGroupsSearchProvider.kt @@ -37,7 +37,6 @@ import android.provider.BaseColumns import android.widget.Toast import com.owncloud.android.R import com.owncloud.android.authentication.AccountUtils -import com.owncloud.android.datamodel.FileDataStorageManager import com.owncloud.android.domain.capabilities.usecases.GetStoredCapabilitiesUseCase import com.owncloud.android.domain.sharing.sharees.GetShareesAsyncUseCase import com.owncloud.android.domain.sharing.shares.model.ShareType diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt index 8337b3f2847..22a9fbc6429 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt @@ -26,7 +26,6 @@ package com.owncloud.android.presentation.ui.sharing.fragments import android.accounts.Account import android.content.Context import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -179,16 +178,9 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe ) } - private val isShareApiEnabled: Boolean - get() = capabilities?.filesSharingApiEnabled == CapabilityBooleanType.TRUE || - capabilities?.filesSharingApiEnabled == CapabilityBooleanType.UNKNOWN + private val isShareApiEnabled = capabilities?.filesSharingApiEnabled == CapabilityBooleanType.TRUE - /** - * @return 'True' when public share is disabled in the server - */ - private val isPublicShareEnabled: Boolean - get() = capabilities?.filesSharingPublicEnabled == CapabilityBooleanType.TRUE || - capabilities?.filesSharingPublicEnabled == CapabilityBooleanType.UNKNOWN + private val isPublicShareEnabled = capabilities?.filesSharingPublicEnabled == CapabilityBooleanType.TRUE private val ocCapabilityViewModel: OCCapabilityViewModel by viewModel { parametersOf( diff --git a/owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase/28.json b/owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase/28.json index 44e4702a066..32b36d24bc0 100644 --- a/owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase/28.json +++ b/owncloudData/schemas/com.owncloud.android.data.OwncloudDatabase/28.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 28, - "identityHash": "a1afd9487db21ba5b69279ed4f42749d", + "identityHash": "20602132a618657e72b338b1e7c1850c", "entities": [ { "tableName": "ocshares", @@ -128,7 +128,7 @@ }, { "tableName": "capabilities", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL, `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `filesSharingApiEnabled` INTEGER NOT NULL, `search_min_length` INTEGER NOT NULL, `sharing_public_enabled` INTEGER NOT NULL, `sharing_public_password_enforced` INTEGER NOT NULL, `sharing_public_password_enforced_read_only` INTEGER NOT NULL, `sharing_public_password_enforced_read_write` INTEGER NOT NULL, `sharing_public_password_enforced_public_only` INTEGER NOT NULL, `sharing_public_expire_date_enabled` INTEGER NOT NULL, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced` INTEGER NOT NULL, `sharing_public_send_mail` INTEGER NOT NULL, `sharing_public_upload` INTEGER NOT NULL, `sharing_public_multiple` INTEGER NOT NULL, `supports_upload_only` INTEGER NOT NULL, `sharing_user_send_mail` INTEGER NOT NULL, `sharing_resharing` INTEGER NOT NULL, `sharing_federation_outgoing` INTEGER NOT NULL, `sharing_federation_incoming` INTEGER NOT NULL, `files_bigfilechunking` INTEGER NOT NULL, `files_undelete` INTEGER NOT NULL, `files_versioning` INTEGER NOT NULL)", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL, `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `sharing_api_enabled` INTEGER NOT NULL DEFAULT -1, `search_min_length` INTEGER, `sharing_public_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_write` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_public_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_days` INTEGER NOT NULL DEFAULT 0, `sharing_public_expire_date_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_public_upload` INTEGER NOT NULL DEFAULT -1, `sharing_public_multiple` INTEGER NOT NULL DEFAULT -1, `supports_upload_only` INTEGER NOT NULL DEFAULT -1, `sharing_user_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_resharing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_outgoing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_incoming` INTEGER NOT NULL DEFAULT -1, `files_bigfilechunking` INTEGER NOT NULL DEFAULT -1, `files_undelete` INTEGER NOT NULL DEFAULT -1, `files_versioning` INTEGER NOT NULL DEFAULT -1)", "fields": [ { "fieldPath": "id", @@ -180,129 +180,149 @@ }, { "fieldPath": "filesSharingApiEnabled", - "columnName": "filesSharingApiEnabled", + "columnName": "sharing_api_enabled", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingSearchMinLength", "columnName": "search_min_length", "affinity": "INTEGER", - "notNull": true + "notNull": false }, { "fieldPath": "filesSharingPublicEnabled", "columnName": "sharing_public_enabled", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicPasswordEnforced", "columnName": "sharing_public_password_enforced", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicPasswordEnforcedReadOnly", "columnName": "sharing_public_password_enforced_read_only", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicPasswordEnforcedReadWrite", "columnName": "sharing_public_password_enforced_read_write", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicPasswordEnforcedUploadOnly", "columnName": "sharing_public_password_enforced_public_only", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicExpireDateEnabled", "columnName": "sharing_public_expire_date_enabled", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicExpireDateDays", "columnName": "sharing_public_expire_date_days", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "0" }, { "fieldPath": "filesSharingPublicExpireDateEnforced", "columnName": "sharing_public_expire_date_enforced", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicSendMail", "columnName": "sharing_public_send_mail", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicUpload", "columnName": "sharing_public_upload", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicMultiple", "columnName": "sharing_public_multiple", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingPublicSupportsUploadOnly", "columnName": "supports_upload_only", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingUserSendMail", "columnName": "sharing_user_send_mail", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingResharing", "columnName": "sharing_resharing", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingFederationOutgoing", "columnName": "sharing_federation_outgoing", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesSharingFederationIncoming", "columnName": "sharing_federation_incoming", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesBigFileChunking", "columnName": "files_bigfilechunking", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesUndelete", "columnName": "files_undelete", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" }, { "fieldPath": "filesVersioning", "columnName": "files_versioning", "affinity": "INTEGER", - "notNull": true + "notNull": true, + "defaultValue": "-1" } ], "primaryKey": { @@ -318,7 +338,7 @@ "views": [], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", - "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'a1afd9487db21ba5b69279ed4f42749d')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '20602132a618657e72b338b1e7c1850c')" ] } } \ No newline at end of file diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt index 22ead35dcf7..baa02f8b249 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt @@ -32,12 +32,14 @@ import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MAYOR import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MICRO import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MINOR +import com.owncloud.android.data.capabilities.db.OCCapabilityEntity.Companion.toContentValues +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType.Companion.capabilityBooleanTypeUnknownInt import com.owncloud.android.testutil.OC_CAPABILITY import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -55,37 +57,6 @@ class MigrationTest { FrameworkSQLiteOpenHelperFactory() ) - @Test - fun startInVersion27_containsCorrectData() { - // Create the database with version 27 - with( - helper.createDatabase( - TEST_DB_NAME, - DB_VERSION_27 - ) - ) { - - // Insert some data - insert(ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) - - // Close database - close() - } - - // Verify that the data is correct - val dbCapability = - getMigratedRoomDatabase().capabilityDao().getCapabilitiesForAccount(OC_CAPABILITY.accountName!!) - assertEquals(dbCapability.accountName, cv.getAsString(CAPABILITIES_ACCOUNT_NAME)) - assertEquals(dbCapability.versionMayor, cv.getAsInteger(CAPABILITIES_VERSION_MAYOR)) - assertEquals(dbCapability.versionMinor, cv.getAsInteger(CAPABILITIES_VERSION_MINOR)) - assertEquals(dbCapability.versionMicro, cv.getAsInteger(CAPABILITIES_VERSION_MICRO)) - assertEquals(dbCapability.corePollInterval, cv.getAsInteger(CAPABILITIES_CORE_POLLINTERVAL)) - assertEquals( - dbCapability.filesSharingPublicExpireDateDays, - cv.getAsInteger(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS) - ) - } - @Test @Throws(IOException::class) fun migrate27To28() { @@ -95,35 +66,19 @@ class MigrationTest { DB_VERSION_27 ) ) { - // Database has schema version 27. Insert some values to test if they are migrated successfully. - // We cannot use DAO classes because they expect the latest schema and we may not have some fields there. - insert(ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) + insert(CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) + insert(CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cvWithDefaultValues) close() } - // Re-open the database with version 28 and provide - // MIGRATION_27_28 as the migration process. helper.runMigrationsAndValidate( TEST_DB_NAME, DB_VERSION_28, true, OwncloudDatabase.MIGRATION_27_28 ) - // MigrationTestHelper automatically verifies the schema changes. - // Verify that the data was migrated properly. - val dbCapability = - getMigratedRoomDatabase().capabilityDao().getCapabilitiesForAccount(OC_CAPABILITY.accountName!!) - assertEquals(dbCapability.accountName, cv.getAsString(CAPABILITIES_ACCOUNT_NAME)) - assertEquals(dbCapability.versionMayor, cv.getAsInteger(CAPABILITIES_VERSION_MAYOR)) - assertEquals(dbCapability.versionMinor, cv.getAsInteger(CAPABILITIES_VERSION_MINOR)) - assertEquals(dbCapability.versionMicro, cv.getAsInteger(CAPABILITIES_VERSION_MICRO)) - assertEquals(dbCapability.corePollInterval, cv.getAsInteger(CAPABILITIES_CORE_POLLINTERVAL)) - assertEquals( - dbCapability.filesSharingPublicExpireDateDays, - cv.getAsInteger(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS) - ) - // Field introduced in this version (DB_VERSION_28), so it should be null. - assertNull(dbCapability.filesSharingSearchMinLength) + + validateMigrationTo28() } @Test @@ -134,17 +89,12 @@ class MigrationTest { DB_VERSION_28 ) ) { - insert(ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) + insert(CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cv) + insert(CAPABILITIES_TABLE_NAME, SQLiteDatabase.CONFLICT_NONE, cvWithDefaultValues) close() } - val dbCapability = getMigratedRoomDatabase().capabilityDao().getCapabilitiesForAccount(OC_CAPABILITY.accountName!!) - assertEquals(OC_CAPABILITY.accountName, dbCapability.accountName) - assertEquals(OC_CAPABILITY.versionMayor, dbCapability.versionMayor) - assertEquals(OC_CAPABILITY.versionMinor, dbCapability.versionMinor) - assertEquals(OC_CAPABILITY.versionMicro, dbCapability.versionMicro) - assertEquals(OC_CAPABILITY.corePollInterval, dbCapability.corePollInterval) - assertEquals(OC_CAPABILITY.filesSharingPublicExpireDateDays, dbCapability.filesSharingPublicExpireDateDays) + validateMigrationTo28() } private fun getMigratedRoomDatabase(): OwncloudDatabase { @@ -160,21 +110,88 @@ class MigrationTest { return database } + private fun validateMigrationTo28() { + val dbCapability = + getMigratedRoomDatabase().capabilityDao().getCapabilitiesForAccount(OC_CAPABILITY.accountName!!) + with(dbCapability) { + assertEquals(OC_CAPABILITY.accountName, accountName) + assertEquals(OC_CAPABILITY.versionMayor, versionMayor) + assertEquals(OC_CAPABILITY.versionMinor, versionMinor) + assertEquals(OC_CAPABILITY.versionMicro, versionMicro) + assertEquals(OC_CAPABILITY.versionString, versionString) + assertEquals(OC_CAPABILITY.versionEdition, versionEdition) + assertEquals(OC_CAPABILITY.corePollInterval, corePollInterval) + assertEquals(OC_CAPABILITY.filesSharingApiEnabled.value, filesSharingApiEnabled) + assertEquals(null, filesSharingSearchMinLength) + assertEquals(OC_CAPABILITY.filesSharingPublicEnabled.value, filesSharingPublicEnabled) + assertEquals(OC_CAPABILITY.filesSharingPublicPasswordEnforced.value, filesSharingPublicPasswordEnforced) + assertEquals(OC_CAPABILITY.filesSharingPublicPasswordEnforcedReadOnly.value, filesSharingPublicPasswordEnforcedReadOnly) + assertEquals(OC_CAPABILITY.filesSharingPublicPasswordEnforcedReadWrite.value, filesSharingPublicPasswordEnforcedReadWrite) + assertEquals(OC_CAPABILITY.filesSharingPublicPasswordEnforcedUploadOnly.value, filesSharingPublicPasswordEnforcedUploadOnly) + assertEquals(OC_CAPABILITY.filesSharingPublicExpireDateEnabled.value, filesSharingPublicExpireDateEnabled) + assertEquals(OC_CAPABILITY.filesSharingPublicExpireDateDays, filesSharingPublicExpireDateDays) + assertEquals(OC_CAPABILITY.filesSharingPublicExpireDateEnforced.value, filesSharingPublicExpireDateEnforced) + assertEquals(OC_CAPABILITY.filesSharingPublicSendMail.value, filesSharingPublicSendMail) + assertEquals(OC_CAPABILITY.filesSharingPublicUpload.value, filesSharingPublicUpload) + assertEquals(OC_CAPABILITY.filesSharingPublicMultiple.value, filesSharingPublicMultiple) + assertEquals(OC_CAPABILITY.filesSharingPublicSupportsUploadOnly.value, filesSharingPublicSupportsUploadOnly) + assertEquals(OC_CAPABILITY.filesSharingResharing.value, filesSharingResharing) + assertEquals(OC_CAPABILITY.filesSharingFederationOutgoing.value, filesSharingFederationOutgoing) + assertEquals(OC_CAPABILITY.filesSharingFederationIncoming.value, filesSharingFederationIncoming) + assertEquals(OC_CAPABILITY.filesBigFileChunking.value, filesBigFileChunking) + assertEquals(OC_CAPABILITY.filesUndelete.value, filesUndelete) + assertEquals(OC_CAPABILITY.filesVersioning.value, filesVersioning) + } + + val capabilityDefaultValue = + getMigratedRoomDatabase().capabilityDao().getCapabilitiesForAccount("accountWithDefaultValues") + with(capabilityDefaultValue) { + assertEquals("accountWithDefaultValues", accountName) + assertEquals(OC_CAPABILITY.versionMayor, versionMayor) + assertEquals(OC_CAPABILITY.versionMinor, versionMinor) + assertEquals(OC_CAPABILITY.versionMicro, versionMicro) + assertEquals(null, versionString) + assertEquals(null, versionEdition) + assertEquals(OC_CAPABILITY.corePollInterval, corePollInterval) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingApiEnabled) + assertEquals(null, filesSharingSearchMinLength) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicEnabled) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicPasswordEnforced) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicPasswordEnforcedReadOnly) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicPasswordEnforcedReadWrite) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicPasswordEnforcedUploadOnly) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicExpireDateEnabled) + assertEquals(0, filesSharingPublicExpireDateDays) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicExpireDateEnforced) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicSendMail) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicUpload) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicMultiple) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingPublicSupportsUploadOnly) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingResharing) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingFederationOutgoing) + assertEquals(capabilityBooleanTypeUnknownInt, filesSharingFederationIncoming) + assertEquals(capabilityBooleanTypeUnknownInt, filesBigFileChunking) + assertEquals(capabilityBooleanTypeUnknownInt, filesUndelete) + assertEquals(capabilityBooleanTypeUnknownInt, filesVersioning) + } + } + companion object { private const val TEST_DB_NAME = "migration-test" private const val DB_VERSION_27 = 27 - // Added a new capability: "search_min_length" private const val DB_VERSION_28 = 28 - private val cv = ContentValues().apply { - put(CAPABILITIES_ACCOUNT_NAME, OC_CAPABILITY.accountName) + private val cvWithDefaultValues = ContentValues().apply { + put(CAPABILITIES_ACCOUNT_NAME, "accountWithDefaultValues") put(CAPABILITIES_VERSION_MAYOR, OC_CAPABILITY.versionMayor) put(CAPABILITIES_VERSION_MINOR, OC_CAPABILITY.versionMinor) put(CAPABILITIES_VERSION_MICRO, OC_CAPABILITY.versionMicro) put(CAPABILITIES_CORE_POLLINTERVAL, OC_CAPABILITY.corePollInterval) put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS, OC_CAPABILITY.filesSharingPublicExpireDateDays) } + + private val cv = toContentValues(OC_CAPABILITY.copy(filesSharingSearchMinLength = null)) } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt b/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt index a29b9b1808a..8443ae9e210 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/OwncloudDatabase.kt @@ -28,6 +28,8 @@ import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_SHARING_SEARCH_MIN_LENGTH +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME import com.owncloud.android.data.capabilities.db.OCCapabilityDao import com.owncloud.android.data.capabilities.db.OCCapabilityEntity import com.owncloud.android.data.sharing.shares.db.OCShareDao @@ -51,10 +53,17 @@ abstract class OwncloudDatabase : RoomDatabase() { val MIGRATION_27_28 = object : Migration(27, 28) { override fun migrate(database: SupportSQLiteDatabase) { - database.execSQL( - "ALTER TABLE ${ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME} " + - "ADD COLUMN ${ProviderMeta.ProviderTableMeta.CAPABILITIES_SHARING_SEARCH_MIN_LENGTH} INTEGER" - ) + database.run { + execSQL( + "CREATE TABLE IF NOT EXISTS `${CAPABILITIES_TABLE_NAME}2` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `version_mayor` INTEGER NOT NULL, `version_minor` INTEGER NOT NULL, `version_micro` INTEGER NOT NULL, `version_string` TEXT, `version_edition` TEXT, `core_pollinterval` INTEGER NOT NULL, `sharing_api_enabled` INTEGER NOT NULL DEFAULT -1, `search_min_length` INTEGER, `sharing_public_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_read_write` INTEGER NOT NULL DEFAULT -1, `sharing_public_password_enforced_public_only` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_enabled` INTEGER NOT NULL DEFAULT -1, `sharing_public_expire_date_days` INTEGER NOT NULL, `sharing_public_expire_date_enforced` INTEGER NOT NULL DEFAULT -1, `sharing_public_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_public_upload` INTEGER NOT NULL DEFAULT -1, `sharing_public_multiple` INTEGER NOT NULL DEFAULT -1, `supports_upload_only` INTEGER NOT NULL DEFAULT -1, `sharing_user_send_mail` INTEGER NOT NULL DEFAULT -1, `sharing_resharing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_outgoing` INTEGER NOT NULL DEFAULT -1, `sharing_federation_incoming` INTEGER NOT NULL DEFAULT -1, `files_bigfilechunking` INTEGER NOT NULL DEFAULT -1, `files_undelete` INTEGER NOT NULL DEFAULT -1, `files_versioning` INTEGER NOT NULL DEFAULT -1)" + ) + execSQL("ALTER TABLE $CAPABILITIES_TABLE_NAME ADD COLUMN $CAPABILITIES_SHARING_SEARCH_MIN_LENGTH INTEGER") + execSQL( + "INSERT INTO `${CAPABILITIES_TABLE_NAME}2` SELECT id, account, version_mayor, version_minor, version_micro, version_string, version_edition,core_pollinterval, IFNULL(sharing_api_enabled, -1), search_min_length, IFNULL(sharing_public_enabled, -1), IFNULL(sharing_public_password_enforced, -1),IFNULL(sharing_public_password_enforced_read_only, -1),IFNULL(sharing_public_password_enforced_read_write, -1),IFNULL(sharing_public_password_enforced_public_only, -1),IFNULL(sharing_public_expire_date_enabled, -1),IFNULL(sharing_public_expire_date_days, 0),IFNULL(sharing_public_expire_date_enforced, -1),IFNULL(sharing_public_send_mail, -1),IFNULL(sharing_public_upload, -1),IFNULL(sharing_public_multiple, -1), IFNULL(supports_upload_only, -1), IFNULL(sharing_user_send_mail, -1),IFNULL(sharing_resharing, -1),IFNULL(sharing_federation_outgoing, -1),IFNULL(sharing_federation_incoming, -1),IFNULL(files_bigfilechunking, -1),IFNULL(files_undelete, -1),IFNULL(files_versioning, -1) FROM $CAPABILITIES_TABLE_NAME" + ) + execSQL("DROP TABLE $CAPABILITIES_TABLE_NAME") + execSQL("ALTER TABLE ${CAPABILITIES_TABLE_NAME}2 RENAME TO $CAPABILITIES_TABLE_NAME") + } } } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapper.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapper.kt index 4110ef4fdfc..1f82292bff4 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapper.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/OCCapabilityMapper.kt @@ -36,37 +36,27 @@ class OCCapabilityMapper : Mapper { versionString = entity.versionString, versionEdition = entity.versionEdition, corePollInterval = entity.corePollInterval, - filesSharingApiEnabled = CapabilityBooleanType.fromValue(entity.filesSharingApiEnabled)!!, + filesSharingApiEnabled = CapabilityBooleanType.fromValue(entity.filesSharingApiEnabled), filesSharingSearchMinLength = entity.filesSharingSearchMinLength, - filesSharingPublicEnabled = CapabilityBooleanType.fromValue(entity.filesSharingPublicEnabled)!!, - filesSharingPublicPasswordEnforced = - CapabilityBooleanType.fromValue(entity.filesSharingPublicPasswordEnforced)!!, - filesSharingPublicPasswordEnforcedReadOnly = - CapabilityBooleanType.fromValue(entity.filesSharingPublicPasswordEnforcedReadOnly)!!, - filesSharingPublicPasswordEnforcedReadWrite = - CapabilityBooleanType.fromValue(entity.filesSharingPublicPasswordEnforcedReadWrite)!!, - filesSharingPublicPasswordEnforcedUploadOnly = - CapabilityBooleanType.fromValue(entity.filesSharingPublicPasswordEnforcedUploadOnly)!!, - filesSharingPublicExpireDateEnabled = - CapabilityBooleanType.fromValue(entity.filesSharingPublicExpireDateEnabled)!!, + filesSharingPublicEnabled = CapabilityBooleanType.fromValue(entity.filesSharingPublicEnabled), + filesSharingPublicPasswordEnforced = CapabilityBooleanType.fromValue(entity.filesSharingPublicPasswordEnforced), + filesSharingPublicPasswordEnforcedReadOnly = CapabilityBooleanType.fromValue(entity.filesSharingPublicPasswordEnforcedReadOnly), + filesSharingPublicPasswordEnforcedReadWrite = CapabilityBooleanType.fromValue(entity.filesSharingPublicPasswordEnforcedReadWrite), + filesSharingPublicPasswordEnforcedUploadOnly = CapabilityBooleanType.fromValue(entity.filesSharingPublicPasswordEnforcedUploadOnly), + filesSharingPublicExpireDateEnabled = CapabilityBooleanType.fromValue(entity.filesSharingPublicExpireDateEnabled), filesSharingPublicExpireDateDays = entity.filesSharingPublicExpireDateDays, - filesSharingPublicExpireDateEnforced = - CapabilityBooleanType.fromValue(entity.filesSharingPublicExpireDateEnforced)!!, - filesSharingPublicSendMail = - CapabilityBooleanType.fromValue(entity.filesSharingPublicSendMail)!!, - filesSharingPublicUpload = CapabilityBooleanType.fromValue(entity.filesSharingPublicUpload)!!, - filesSharingPublicMultiple = CapabilityBooleanType.fromValue(entity.filesSharingPublicMultiple)!!, - filesSharingPublicSupportsUploadOnly = - CapabilityBooleanType.fromValue(entity.filesSharingPublicSupportsUploadOnly)!!, - filesSharingUserSendMail = CapabilityBooleanType.fromValue(entity.filesSharingUserSendMail)!!, - filesSharingResharing = CapabilityBooleanType.fromValue(entity.filesSharingResharing)!!, - filesSharingFederationOutgoing = - CapabilityBooleanType.fromValue(entity.filesSharingFederationOutgoing)!!, - filesSharingFederationIncoming = - CapabilityBooleanType.fromValue(entity.filesSharingFederationIncoming)!!, - filesBigFileChunking = CapabilityBooleanType.fromValue(entity.filesBigFileChunking)!!, - filesUndelete = CapabilityBooleanType.fromValue(entity.filesUndelete)!!, - filesVersioning = CapabilityBooleanType.fromValue(entity.filesVersioning)!! + filesSharingPublicExpireDateEnforced = CapabilityBooleanType.fromValue(entity.filesSharingPublicExpireDateEnforced), + filesSharingPublicSendMail = CapabilityBooleanType.fromValue(entity.filesSharingPublicSendMail), + filesSharingPublicUpload = CapabilityBooleanType.fromValue(entity.filesSharingPublicUpload), + filesSharingPublicMultiple = CapabilityBooleanType.fromValue(entity.filesSharingPublicMultiple), + filesSharingPublicSupportsUploadOnly = CapabilityBooleanType.fromValue(entity.filesSharingPublicSupportsUploadOnly), + filesSharingUserSendMail = CapabilityBooleanType.fromValue(entity.filesSharingUserSendMail), + filesSharingResharing = CapabilityBooleanType.fromValue(entity.filesSharingResharing), + filesSharingFederationOutgoing = CapabilityBooleanType.fromValue(entity.filesSharingFederationOutgoing), + filesSharingFederationIncoming = CapabilityBooleanType.fromValue(entity.filesSharingFederationIncoming), + filesBigFileChunking = CapabilityBooleanType.fromValue(entity.filesBigFileChunking), + filesUndelete = CapabilityBooleanType.fromValue(entity.filesUndelete), + filesVersioning = CapabilityBooleanType.fromValue(entity.filesVersioning) ) } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt index 0fefdef4ef8..e9a4b15e3b3 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt @@ -36,36 +36,36 @@ class RemoteCapabilityMapper : RemoteMapper { versionString = remote.versionString, versionEdition = remote.versionEdition, corePollInterval = remote.corePollinterval, - filesSharingApiEnabled = CapabilityBooleanType.fromValue(remote.filesSharingApiEnabled.value)!!, + filesSharingApiEnabled = CapabilityBooleanType.fromValue(remote.filesSharingApiEnabled.value), filesSharingSearchMinLength = remote.filesSharingSearchMinLength, - filesSharingPublicEnabled = CapabilityBooleanType.fromValue(remote.filesSharingPublicEnabled.value)!!, + filesSharingPublicEnabled = CapabilityBooleanType.fromValue(remote.filesSharingPublicEnabled.value), filesSharingPublicPasswordEnforced = - CapabilityBooleanType.fromValue(remote.filesSharingPublicPasswordEnforced.value)!!, + CapabilityBooleanType.fromValue(remote.filesSharingPublicPasswordEnforced.value), filesSharingPublicPasswordEnforcedReadOnly = - CapabilityBooleanType.fromValue(remote.filesSharingPublicPasswordEnforcedReadOnly.value)!!, + CapabilityBooleanType.fromValue(remote.filesSharingPublicPasswordEnforcedReadOnly.value), filesSharingPublicPasswordEnforcedReadWrite = - CapabilityBooleanType.fromValue(remote.filesSharingPublicPasswordEnforcedReadWrite.value)!!, + CapabilityBooleanType.fromValue(remote.filesSharingPublicPasswordEnforcedReadWrite.value), filesSharingPublicPasswordEnforcedUploadOnly = - CapabilityBooleanType.fromValue(remote.filesSharingPublicPasswordEnforcedUploadOnly.value)!!, + CapabilityBooleanType.fromValue(remote.filesSharingPublicPasswordEnforcedUploadOnly.value), filesSharingPublicExpireDateEnabled = - CapabilityBooleanType.fromValue(remote.filesSharingPublicExpireDateEnabled.value)!!, + CapabilityBooleanType.fromValue(remote.filesSharingPublicExpireDateEnabled.value), filesSharingPublicExpireDateDays = remote.filesSharingPublicExpireDateDays, filesSharingPublicExpireDateEnforced = - CapabilityBooleanType.fromValue(remote.filesSharingPublicExpireDateEnforced.value)!!, - filesSharingPublicSendMail = CapabilityBooleanType.fromValue(remote.filesSharingPublicSendMail.value)!!, - filesSharingPublicUpload = CapabilityBooleanType.fromValue(remote.filesSharingPublicUpload.value)!!, - filesSharingPublicMultiple = CapabilityBooleanType.fromValue(remote.filesSharingPublicMultiple.value)!!, + CapabilityBooleanType.fromValue(remote.filesSharingPublicExpireDateEnforced.value), + filesSharingPublicSendMail = CapabilityBooleanType.fromValue(remote.filesSharingPublicSendMail.value), + filesSharingPublicUpload = CapabilityBooleanType.fromValue(remote.filesSharingPublicUpload.value), + filesSharingPublicMultiple = CapabilityBooleanType.fromValue(remote.filesSharingPublicMultiple.value), filesSharingPublicSupportsUploadOnly = - CapabilityBooleanType.fromValue(remote.filesSharingPublicSupportsUploadOnly.value)!!, - filesSharingUserSendMail = CapabilityBooleanType.fromValue(remote.filesSharingUserSendMail.value)!!, - filesSharingResharing = CapabilityBooleanType.fromValue(remote.filesSharingResharing.value)!!, + CapabilityBooleanType.fromValue(remote.filesSharingPublicSupportsUploadOnly.value), + filesSharingUserSendMail = CapabilityBooleanType.fromValue(remote.filesSharingUserSendMail.value), + filesSharingResharing = CapabilityBooleanType.fromValue(remote.filesSharingResharing.value), filesSharingFederationOutgoing = - CapabilityBooleanType.fromValue(remote.filesSharingFederationOutgoing.value)!!, + CapabilityBooleanType.fromValue(remote.filesSharingFederationOutgoing.value), filesSharingFederationIncoming = - CapabilityBooleanType.fromValue(remote.filesSharingFederationIncoming.value)!!, - filesBigFileChunking = CapabilityBooleanType.fromValue(remote.filesBigFileChunking.value)!!, - filesUndelete = CapabilityBooleanType.fromValue(remote.filesUndelete.value)!!, - filesVersioning = CapabilityBooleanType.fromValue(remote.filesVersioning.value)!! + CapabilityBooleanType.fromValue(remote.filesSharingFederationIncoming.value), + filesBigFileChunking = CapabilityBooleanType.fromValue(remote.filesBigFileChunking.value), + filesUndelete = CapabilityBooleanType.fromValue(remote.filesUndelete.value), + filesVersioning = CapabilityBooleanType.fromValue(remote.filesVersioning.value) ) } diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntity.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntity.kt index de88c428227..7630a4df8cc 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntity.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityEntity.kt @@ -25,145 +25,165 @@ import android.database.Cursor import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey -import com.owncloud.android.data.ProviderMeta.ProviderTableMeta -import com.owncloud.android.lib.resources.status.RemoteCapability +import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.* +import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType.Companion.capabilityBooleanTypeUnknownString +import com.owncloud.android.domain.capabilities.model.OCCapability /** * Represents one record of the Capabilities table. */ -@Entity(tableName = ProviderTableMeta.CAPABILITIES_TABLE_NAME) +@Entity(tableName = CAPABILITIES_TABLE_NAME) data class OCCapabilityEntity( - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME) + @ColumnInfo(name = CAPABILITIES_ACCOUNT_NAME) val accountName: String?, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_MAYOR) + @ColumnInfo(name = CAPABILITIES_VERSION_MAYOR) val versionMayor: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_MINOR) + @ColumnInfo(name = CAPABILITIES_VERSION_MINOR) val versionMinor: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_MICRO) + @ColumnInfo(name = CAPABILITIES_VERSION_MICRO) val versionMicro: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_STRING) + @ColumnInfo(name = CAPABILITIES_VERSION_STRING) val versionString: String?, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_VERSION_EDITION) + @ColumnInfo(name = CAPABILITIES_VERSION_EDITION) val versionEdition: String?, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL) + @ColumnInfo(name = CAPABILITIES_CORE_POLLINTERVAL) val corePollInterval: Int, + @ColumnInfo(name = CAPABILITIES_SHARING_API_ENABLED, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingApiEnabled: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_SEARCH_MIN_LENGTH) - val filesSharingSearchMinLength: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED) + @ColumnInfo(name = CAPABILITIES_SHARING_SEARCH_MIN_LENGTH) + val filesSharingSearchMinLength: Int?, + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_ENABLED, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicEnabled: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicPasswordEnforced: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicPasswordEnforcedReadOnly: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicPasswordEnforcedReadWrite: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicPasswordEnforcedUploadOnly: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicExpireDateEnabled: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS, defaultValue = "0") val filesSharingPublicExpireDateDays: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicExpireDateEnforced: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_SEND_MAIL, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicSendMail: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_UPLOAD, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicUpload: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_MULTIPLE, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicMultiple: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY) + @ColumnInfo(name = CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingPublicSupportsUploadOnly: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL) + @ColumnInfo(name = CAPABILITIES_SHARING_USER_SEND_MAIL, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingUserSendMail: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_RESHARING) + @ColumnInfo(name = CAPABILITIES_SHARING_RESHARING, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingResharing: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING) + @ColumnInfo(name = CAPABILITIES_SHARING_FEDERATION_OUTGOING, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingFederationOutgoing: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING) + @ColumnInfo(name = CAPABILITIES_SHARING_FEDERATION_INCOMING, defaultValue = capabilityBooleanTypeUnknownString) val filesSharingFederationIncoming: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING) + @ColumnInfo(name = CAPABILITIES_FILES_BIGFILECHUNKING, defaultValue = capabilityBooleanTypeUnknownString) val filesBigFileChunking: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_FILES_UNDELETE) + @ColumnInfo(name = CAPABILITIES_FILES_UNDELETE, defaultValue = capabilityBooleanTypeUnknownString) val filesUndelete: Int, - @ColumnInfo(name = ProviderTableMeta.CAPABILITIES_FILES_VERSIONING) + @ColumnInfo(name = CAPABILITIES_FILES_VERSIONING, defaultValue = capabilityBooleanTypeUnknownString) val filesVersioning: Int ) { @PrimaryKey(autoGenerate = true) var id: Int = 0 companion object { fun fromCursor(cursor: Cursor) = OCCapabilityEntity( - cursor.getString(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_MAYOR)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_MINOR)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_MICRO)), - cursor.getString(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_STRING)), - cursor.getString(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_VERSION_EDITION)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_SEARCH_MIN_LENGTH)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED)), - cursor.getInt( - cursor.getColumnIndex( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY - ) - ), - cursor.getInt( - cursor.getColumnIndex( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE - ) - ), - cursor.getInt( - cursor.getColumnIndex( - ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY - ) - ), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_RESHARING)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_FILES_UNDELETE)), - cursor.getInt(cursor.getColumnIndex(ProviderTableMeta.CAPABILITIES_FILES_VERSIONING)) + cursor.getString(cursor.getColumnIndex(CAPABILITIES_ACCOUNT_NAME)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_VERSION_MAYOR)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_VERSION_MINOR)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_VERSION_MICRO)), + cursor.getString(cursor.getColumnIndex(CAPABILITIES_VERSION_STRING)), + cursor.getString(cursor.getColumnIndex(CAPABILITIES_VERSION_EDITION)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_CORE_POLLINTERVAL)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_API_ENABLED)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_SEARCH_MIN_LENGTH)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_ENABLED)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_SEND_MAIL)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_UPLOAD)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_MULTIPLE)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_USER_SEND_MAIL)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_RESHARING)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_FEDERATION_OUTGOING)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_SHARING_FEDERATION_INCOMING)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_FILES_BIGFILECHUNKING)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_FILES_UNDELETE)), + cursor.getInt(cursor.getColumnIndex(CAPABILITIES_FILES_VERSIONING)) ) fun fromContentValues(values: ContentValues) = OCCapabilityEntity( - values.getAsString(ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_VERSION_MAYOR), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_VERSION_MINOR), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_VERSION_MICRO), - values.getAsString(ProviderTableMeta.CAPABILITIES_VERSION_STRING), - values.getAsString(ProviderTableMeta.CAPABILITIES_VERSION_EDITION), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_SEARCH_MIN_LENGTH), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_RESHARING), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_FILES_UNDELETE), - values.getAsInteger(ProviderTableMeta.CAPABILITIES_FILES_VERSIONING) + values.getAsString(CAPABILITIES_ACCOUNT_NAME), + values.getAsInteger(CAPABILITIES_VERSION_MAYOR), + values.getAsInteger(CAPABILITIES_VERSION_MINOR), + values.getAsInteger(CAPABILITIES_VERSION_MICRO), + values.getAsString(CAPABILITIES_VERSION_STRING), + values.getAsString(CAPABILITIES_VERSION_EDITION), + values.getAsInteger(CAPABILITIES_CORE_POLLINTERVAL), + values.getAsInteger(CAPABILITIES_SHARING_API_ENABLED), + values.getAsInteger(CAPABILITIES_SHARING_SEARCH_MIN_LENGTH), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_ENABLED), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_SEND_MAIL), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_UPLOAD), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_MULTIPLE), + values.getAsInteger(CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY), + values.getAsInteger(CAPABILITIES_SHARING_USER_SEND_MAIL), + values.getAsInteger(CAPABILITIES_SHARING_RESHARING), + values.getAsInteger(CAPABILITIES_SHARING_FEDERATION_OUTGOING), + values.getAsInteger(CAPABILITIES_SHARING_FEDERATION_INCOMING), + values.getAsInteger(CAPABILITIES_FILES_BIGFILECHUNKING), + values.getAsInteger(CAPABILITIES_FILES_UNDELETE), + values.getAsInteger(CAPABILITIES_FILES_VERSIONING) ) + + fun toContentValues(capability: OCCapability) = ContentValues().apply { + capability.accountName?.let { put(CAPABILITIES_ACCOUNT_NAME, it) } + put(CAPABILITIES_VERSION_MAYOR, capability.versionMayor) + put(CAPABILITIES_VERSION_MINOR, capability.versionMinor) + put(CAPABILITIES_VERSION_MICRO, capability.versionMicro) + capability.versionString?.let { put(CAPABILITIES_VERSION_STRING, it) } + capability.versionEdition?.let { put(CAPABILITIES_VERSION_EDITION, it) } + put(CAPABILITIES_CORE_POLLINTERVAL, capability.corePollInterval) + put(CAPABILITIES_SHARING_API_ENABLED, capability.filesSharingApiEnabled.value) + capability.filesSharingSearchMinLength?.let { put(CAPABILITIES_SHARING_SEARCH_MIN_LENGTH, it) } + put(CAPABILITIES_SHARING_PUBLIC_ENABLED, capability.filesSharingPublicEnabled.value) + put(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED, capability.filesSharingPublicPasswordEnforced.value) + put(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_ONLY, capability.filesSharingPublicPasswordEnforcedReadOnly.value) + put(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_READ_WRITE, capability.filesSharingPublicPasswordEnforcedReadWrite.value) + put(CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED_UPLOAD_ONLY, capability.filesSharingPublicPasswordEnforcedUploadOnly.value) + put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED, capability.filesSharingPublicExpireDateEnabled.value) + put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS, capability.filesSharingPublicExpireDateDays) + put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED, capability.filesSharingPublicExpireDateEnforced.value) + put(CAPABILITIES_SHARING_PUBLIC_SEND_MAIL, capability.filesSharingPublicSendMail.value) + put(CAPABILITIES_SHARING_PUBLIC_UPLOAD, capability.filesSharingPublicUpload.value) + put(CAPABILITIES_SHARING_PUBLIC_MULTIPLE, capability.filesSharingPublicMultiple.value) + put(CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY, capability.filesSharingPublicSupportsUploadOnly.value) + put(CAPABILITIES_SHARING_RESHARING, capability.filesSharingResharing.value) + put(CAPABILITIES_SHARING_FEDERATION_OUTGOING, capability.filesSharingFederationOutgoing.value) + put(CAPABILITIES_SHARING_FEDERATION_INCOMING, capability.filesSharingFederationIncoming.value) + put(CAPABILITIES_FILES_BIGFILECHUNKING, capability.filesBigFileChunking.value) + put(CAPABILITIES_FILES_UNDELETE, capability.filesUndelete.value) + put(CAPABILITIES_FILES_VERSIONING, capability.filesVersioning.value) + } } } diff --git a/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/model/OCCapability.kt b/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/model/OCCapability.kt index 2d13768c071..f6219ac418d 100644 --- a/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/model/OCCapability.kt +++ b/owncloudDomain/src/main/java/com/owncloud/android/domain/capabilities/model/OCCapability.kt @@ -29,7 +29,7 @@ data class OCCapability( val versionEdition: String?, val corePollInterval: Int, val filesSharingApiEnabled: CapabilityBooleanType, - val filesSharingSearchMinLength: Int = 0, + val filesSharingSearchMinLength: Int? = null, val filesSharingPublicEnabled: CapabilityBooleanType, val filesSharingPublicPasswordEnforced: CapabilityBooleanType, val filesSharingPublicPasswordEnforcedReadOnly: CapabilityBooleanType, @@ -72,21 +72,21 @@ enum class CapabilityBooleanType constructor(val value: Int) { get() = value == 1 companion object { - fun fromValue(value: Int): CapabilityBooleanType? { - return when (value) { - -1 -> UNKNOWN + const val capabilityBooleanTypeUnknownString = "-1" + const val capabilityBooleanTypeUnknownInt = -1 + + fun fromValue(value: Int): CapabilityBooleanType = + when (value) { 0 -> FALSE 1 -> TRUE - else -> null + else -> UNKNOWN } - } - fun fromBooleanValue(boolValue: Boolean): CapabilityBooleanType { - return if (boolValue) { + fun fromBooleanValue(boolValue: Boolean): CapabilityBooleanType = + if (boolValue) { TRUE } else { FALSE } - } } } diff --git a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt index 32915f484dc..3e754e55289 100644 --- a/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt +++ b/owncloudDomain/src/test/java/com/owncloud/android/domain/capabilities/model/OCCapabilityTest.kt @@ -27,7 +27,6 @@ import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType.Comp import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse -import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -252,7 +251,7 @@ class OCCapabilityTest { assertEquals(UNKNOWN, fromValueUnknownType) assertEquals(FALSE, fromValueFalseType) assertEquals(TRUE, fromValueTrueType) - assertNull(fromValueDifferentValue) + assertEquals(UNKNOWN, fromValueDifferentValue) assertEquals(TRUE, fromBooleanTrue) assertEquals(FALSE, fromBooleanFalse) assertEquals(true, capabilityUnknown.isUnknown) From c278a66e4805729d4d140c9c0cb43ea7ce776063 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Thu, 28 Nov 2019 14:15:10 +0100 Subject: [PATCH 35/41] Update RemoteCapability --- owncloud-android-library | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/owncloud-android-library b/owncloud-android-library index e1530716547..d5242eba3c1 160000 --- a/owncloud-android-library +++ b/owncloud-android-library @@ -1 +1 @@ -Subproject commit e1530716547b1ed3f4b8e1d72f8f1a832e925ea5 +Subproject commit d5242eba3c1b68a1baff7667f0c17bf54cbd2ce3 From 33b8582344aa39a27374a63a80e3345675c88c42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Thu, 28 Nov 2019 14:41:06 +0100 Subject: [PATCH 36/41] Remove utils from owncloudData --- .../capabilities/db/OCCapabilityDaoTest.kt | 18 +- .../data/sharing/shares/db/OCShareDaoTest.kt | 258 +++++++++--------- .../android/data/utils/LiveDataTestUtil.kt | 41 --- 3 files changed, 143 insertions(+), 174 deletions(-) delete mode 100644 owncloudData/src/androidTest/java/com/owncloud/android/data/utils/LiveDataTestUtil.kt diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt index b9b5a1b4f6a..2f1f2c6ba97 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt @@ -25,9 +25,9 @@ import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.capabilities.datasources.mapper.OCCapabilityMapper -import com.owncloud.android.data.utils.LiveDataTestUtil.getValue import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.testutil.OC_CAPABILITY +import com.owncloud.android.testutil.livedata.getLastEmittedValue import org.junit.Assert.assertNull import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull @@ -64,7 +64,7 @@ class OCCapabilityDaoTest { ocCapabilityDao.insert(entityList) val capability = ocCapabilityDao.getCapabilitiesForAccount(user2) - val capabilityAsLiveData = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2)) + val capabilityAsLiveData = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2).getLastEmittedValue() assertNotNull(capability) assertNotNull(capabilityAsLiveData) @@ -81,7 +81,7 @@ class OCCapabilityDaoTest { ocCapabilityDao.insert(entity2) val capability = ocCapabilityDao.getCapabilitiesForAccount(user2) - val capabilityAsLiveData = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2)) + val capabilityAsLiveData = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2).getLastEmittedValue() assertNotNull(capability) assertNotNull(capabilityAsLiveData) @@ -93,7 +93,7 @@ class OCCapabilityDaoTest { fun getNonExistingCapabilities() { ocCapabilityDao.insert(ocCapabilityMapper.toEntity(OC_CAPABILITY.copy(accountName = user1))!!) - val capability = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2)) + val capability = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2).getLastEmittedValue() assertNull(capability) } @@ -106,7 +106,7 @@ class OCCapabilityDaoTest { ocCapabilityDao.insert(entity1) ocCapabilityDao.replace(listOf(entity2)) - val capability = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!)) + val capability = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!).getLastEmittedValue() assertNotNull(capability) assertEquals(entity2, capability) @@ -121,13 +121,13 @@ class OCCapabilityDaoTest { ocCapabilityDao.replace(listOf(entity2)) - val capability1 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1)) + val capability1 = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1).getLastEmittedValue() assertNotNull(capability1) assertEquals(entity1, capability1) // capability2 didn't exist before, it should not replace the old one but got created - val capability2 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2)) + val capability2 = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2).getLastEmittedValue() assertNotNull(capability2) assertEquals(entity2, capability2) @@ -139,13 +139,13 @@ class OCCapabilityDaoTest { ocCapabilityDao.insert(entity) - val capability1 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1)) + val capability1 = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1).getLastEmittedValue() assertNotNull(capability1) ocCapabilityDao.delete(user1) - val capability2 = getValue(ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1)) + val capability2 = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1).getLastEmittedValue() assertNull(capability2) } diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt index aefc212e2a0..2f71c6b1915 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt @@ -24,12 +24,10 @@ import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.sharing.shares.datasources.mapper.OCShareMapper -import com.owncloud.android.data.utils.LiveDataTestUtil.getValue import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.testutil.OC_PRIVATE_SHARE import com.owncloud.android.testutil.OC_PUBLIC_SHARE -import org.hamcrest.CoreMatchers.notNullValue -import org.hamcrest.MatcherAssert.assertThat +import com.owncloud.android.testutil.livedata.getLastEmittedValue import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Before @@ -65,16 +63,13 @@ class OCShareDaoTest { fun insertEmptySharesList() { ocShareDao.insert(listOf()) - val shares = getValue( - ocShareDao.getSharesAsLiveData( - "/Test/", "admin@server", mutableListOf( - ShareType.PUBLIC_LINK.value - ).plus( - privateShareTypeValues - ) - ) - ) - assertThat(shares, notNullValue()) + val shares = ocShareDao.getSharesAsLiveData( + "/Test/", + "admin@server", + mutableListOf(ShareType.PUBLIC_LINK.value).plus(privateShareTypeValues) + ).getLastEmittedValue()!! + + assertNotNull(shares) assertEquals(0, shares.size) } @@ -112,12 +107,13 @@ class OCShareDaoTest { ) ) - val photosFolderPublicShares = getValue( - ocShareDao.getSharesAsLiveData( - "/Photos/", "admin@server", listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(photosFolderPublicShares, notNullValue()) + val photosFolderPublicShares = ocShareDao.getSharesAsLiveData( + "/Photos/", + "admin@server", + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + + assertNotNull(photosFolderPublicShares) assertEquals(1, photosFolderPublicShares.size) assertEquals("/Photos/", photosFolderPublicShares[0].path) assertEquals(true, photosFolderPublicShares[0].isFolder) @@ -125,12 +121,13 @@ class OCShareDaoTest { assertEquals("Photos folder link", photosFolderPublicShares[0].name) assertEquals("http://server:port/s/1", photosFolderPublicShares[0].shareLink) - val image1PublicShares = getValue( - ocShareDao.getSharesAsLiveData( - "/Photos/image1.jpg", "admin@server", listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(image1PublicShares, notNullValue()) + val image1PublicShares = ocShareDao.getSharesAsLiveData( + "/Photos/image1.jpg", + "admin@server", + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + + assertNotNull(image1PublicShares) assertEquals(1, image1PublicShares.size) assertEquals("/Photos/image1.jpg", image1PublicShares[0].path) assertEquals(false, image1PublicShares[0].isFolder) @@ -138,12 +135,11 @@ class OCShareDaoTest { assertEquals("Image 1 link", image1PublicShares[0].name) assertEquals("http://server:port/s/2", image1PublicShares[0].shareLink) - val image2PrivateShares = getValue( + val image2PrivateShares = ocShareDao.getSharesAsLiveData( "/Photos/image2.jpg", "admin@server", privateShareTypeValues - ) - ) - assertThat(image2PrivateShares, notNullValue()) + ).getLastEmittedValue()!! + assertNotNull(image2PrivateShares) assertEquals(1, image2PrivateShares.size) assertEquals("/Photos/image2.jpg", image2PrivateShares[0].path) assertEquals(false, image2PrivateShares[0].isFolder) @@ -186,12 +182,13 @@ class OCShareDaoTest { ) ) - val document1PublicSharesForUser1 = getValue( - ocShareDao.getSharesAsLiveData( - "/Documents/document1.docx", "user1@server", listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(document1PublicSharesForUser1, notNullValue()) + val document1PublicSharesForUser1 = ocShareDao.getSharesAsLiveData( + "/Documents/document1.docx", + "user1@server", + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + + assertNotNull(document1PublicSharesForUser1) assertEquals(1, document1PublicSharesForUser1.size) assertEquals("/Documents/document1.docx", document1PublicSharesForUser1[0].path) assertEquals(false, document1PublicSharesForUser1[0].isFolder) @@ -199,12 +196,13 @@ class OCShareDaoTest { assertEquals("Document 1 link", document1PublicSharesForUser1[0].name) assertEquals("http://server:port/s/1", document1PublicSharesForUser1[0].shareLink) - val document1PublicSharesForUser2 = getValue( - ocShareDao.getSharesAsLiveData( - "/Documents/document1.docx", "user2@server", listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(document1PublicSharesForUser2, notNullValue()) + val document1PublicSharesForUser2 = ocShareDao.getSharesAsLiveData( + "/Documents/document1.docx", + "user2@server", + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + + assertNotNull(document1PublicSharesForUser2) assertEquals(1, document1PublicSharesForUser2.size) assertEquals("/Documents/document1.docx", document1PublicSharesForUser2[0].path) assertEquals(false, document1PublicSharesForUser2[0].isFolder) @@ -212,12 +210,13 @@ class OCShareDaoTest { assertEquals("Document 1 link", document1PublicSharesForUser2[0].name) assertEquals("http://server:port/s/2", document1PublicSharesForUser2[0].shareLink) - val document1PrivateSharesForUser3 = getValue( - ocShareDao.getSharesAsLiveData( - "/Documents/document1.docx", "user3@server", privateShareTypeValues - ) - ) - assertThat(document1PrivateSharesForUser3, notNullValue()) + val document1PrivateSharesForUser3 = ocShareDao.getSharesAsLiveData( + "/Documents/document1.docx", + "user3@server", + privateShareTypeValues + ).getLastEmittedValue()!! + + assertNotNull(document1PrivateSharesForUser3) assertEquals(1, document1PrivateSharesForUser3.size) assertEquals("/Documents/document1.docx", document1PrivateSharesForUser3[0].path) assertEquals(false, document1PrivateSharesForUser3[0].isFolder) @@ -249,11 +248,12 @@ class OCShareDaoTest { ) ) - val sharesWithSameValues = getValue( - ocShareDao.getSharesAsLiveData( - "/Documents/document1.docx", "user1@server", listOf(ShareType.PUBLIC_LINK.value) - ) - ) + val sharesWithSameValues = ocShareDao.getSharesAsLiveData( + "/Documents/document1.docx", + "user1@server", + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + assertNotNull(sharesWithSameValues) assertEquals(2, sharesWithSameValues.size) assertEquals("/Documents/document1.docx", sharesWithSameValues[0].path) @@ -281,12 +281,13 @@ class OCShareDaoTest { ocShareDao.insert(privateShare) - val nonExistingPrivateShare = getValue( - ocShareDao.getSharesAsLiveData( - privateShare.path, "user@server", privateShareTypeValues - ) - ) - assertThat(nonExistingPrivateShare, notNullValue()) + val nonExistingPrivateShare = ocShareDao.getSharesAsLiveData( + privateShare.path, + "user@server", + privateShareTypeValues + ).getLastEmittedValue()!! + + assertNotNull(nonExistingPrivateShare) assertEquals(0, nonExistingPrivateShare.size) } @@ -302,12 +303,13 @@ class OCShareDaoTest { listOf(privateShareToReplace) ) - val textShares = getValue( - ocShareDao.getSharesAsLiveData( - privateShare.path, privateShare.accountOwner, listOf(ShareType.USER.value) - ) - ) - assertThat(textShares, notNullValue()) + val textShares = ocShareDao.getSharesAsLiveData( + privateShare.path, + privateShare.accountOwner, + listOf(ShareType.USER.value) + ).getLastEmittedValue()!! + + assertNotNull(textShares) assertEquals(1, textShares.size) assertEquals(privateShareToReplace.shareWith, textShares[0].shareWith) } @@ -330,22 +332,24 @@ class OCShareDaoTest { listOf(privateShareToReplace) ) - val text1Shares = getValue( - ocShareDao.getSharesAsLiveData( - privateShare.path, privateShare.accountOwner, listOf(ShareType.GROUP.value) - ) - ) - assertThat(text1Shares, notNullValue()) + val text1Shares = ocShareDao.getSharesAsLiveData( + privateShare.path, + privateShare.accountOwner, + listOf(ShareType.GROUP.value) + ).getLastEmittedValue()!! + + assertNotNull(text1Shares) assertEquals(1, text1Shares.size) assertEquals(privateShare.shareWith, text1Shares[0].shareWith) // text2 link didn't exist before, it should not replace the old one but be created - val text2Shares = getValue( - ocShareDao.getSharesAsLiveData( - privateShareToReplace.path, privateShareToReplace.accountOwner, listOf(ShareType.GROUP.value) - ) - ) - assertThat(text2Shares, notNullValue()) + val text2Shares = ocShareDao.getSharesAsLiveData( + privateShareToReplace.path, + privateShareToReplace.accountOwner, + listOf(ShareType.GROUP.value) + ).getLastEmittedValue()!! + + assertNotNull(text2Shares) assertEquals(1, text2Shares.size) assertEquals(privateShareToReplace.shareWith, text2Shares[0].shareWith) } @@ -360,13 +364,13 @@ class OCShareDaoTest { createDefaultPrivateShareEntity(permissions = 17) ) - val textShares = getValue( - ocShareDao.getSharesAsLiveData( - privateShare.path, privateShare.accountOwner, listOf(ShareType.USER.value) - ) - ) + val textShares = ocShareDao.getSharesAsLiveData( + privateShare.path, + privateShare.accountOwner, + listOf(ShareType.USER.value) + ).getLastEmittedValue()!! - assertThat(textShares, notNullValue()) + assertNotNull(textShares) assertEquals(1, textShares.size) assertEquals(17, textShares[0].permissions) } @@ -379,12 +383,13 @@ class OCShareDaoTest { ocShareDao.deleteShare(privateShare.remoteId) - val textShares = getValue( - ocShareDao.getSharesAsLiveData( - privateShare.path, privateShare.accountOwner, listOf(ShareType.USER.value) - ) - ) - assertThat(textShares, notNullValue()) + val textShares = ocShareDao.getSharesAsLiveData( + privateShare.path, + privateShare.accountOwner, + listOf(ShareType.USER.value) + ).getLastEmittedValue()!! + + assertNotNull(textShares) assertEquals(0, textShares.size) // List of textShares empty after deleting the existing share } @@ -415,12 +420,13 @@ class OCShareDaoTest { ocShareDao.insert(publicShare) - val nonExistingPublicShare = getValue( - ocShareDao.getSharesAsLiveData( - publicShare.path, "user@server", listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(nonExistingPublicShare, notNullValue()) + val nonExistingPublicShare = ocShareDao.getSharesAsLiveData( + publicShare.path, + "user@server", + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + + assertNotNull(nonExistingPublicShare) assertEquals(0, nonExistingPublicShare.size) } @@ -436,12 +442,12 @@ class OCShareDaoTest { listOf(publicShareToReplace) ) - val textShares = getValue( - ocShareDao.getSharesAsLiveData( - publicShare.path, publicShare.accountOwner, listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(textShares, notNullValue()) + val textShares = ocShareDao.getSharesAsLiveData( + publicShare.path, + publicShare.accountOwner, + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + assertNotNull(textShares) assertEquals(1, textShares.size) assertEquals(publicShareToReplace.name, textShares[0].name) } @@ -458,22 +464,24 @@ class OCShareDaoTest { listOf(publicShareToReplace) ) - val text1Shares = getValue( - ocShareDao.getSharesAsLiveData( - publicShare.path, publicShare.accountOwner, listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(text1Shares, notNullValue()) + val text1Shares = ocShareDao.getSharesAsLiveData( + publicShare.path, + publicShare.accountOwner, + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + + assertNotNull(text1Shares) assertEquals(1, text1Shares.size) assertEquals(publicShare.name, text1Shares[0].name) // text2 link didn't exist before, it should not replace the old one but be created - val text2Shares = getValue( - ocShareDao.getSharesAsLiveData( - publicShareToReplace.path, publicShareToReplace.accountOwner, listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(text2Shares, notNullValue()) + val text2Shares = ocShareDao.getSharesAsLiveData( + publicShareToReplace.path, + publicShareToReplace.accountOwner, + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + + assertNotNull(text2Shares) assertEquals(1, text2Shares.size) assertEquals(publicShareToReplace.name, text2Shares[0].name) } @@ -488,12 +496,13 @@ class OCShareDaoTest { ocShareDao.update(publicShareToUpdate) - val textShares = getValue( - ocShareDao.getSharesAsLiveData( - publicShareToUpdate.path, publicShareToUpdate.accountOwner, listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(textShares, notNullValue()) + val textShares = ocShareDao.getSharesAsLiveData( + publicShareToUpdate.path, + publicShareToUpdate.accountOwner, + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + + assertNotNull(textShares) assertEquals(1, textShares.size) assertEquals(publicShareToUpdate.name, textShares[0].name) assertEquals(publicShareToUpdate.expirationDate, textShares[0].expirationDate) @@ -507,12 +516,13 @@ class OCShareDaoTest { ocShareDao.deleteShare(publicShare.remoteId) - val textShares = getValue( - ocShareDao.getSharesAsLiveData( - publicShare.path, publicShare.accountOwner, listOf(ShareType.PUBLIC_LINK.value) - ) - ) - assertThat(textShares, notNullValue()) + val textShares = ocShareDao.getSharesAsLiveData( + publicShare.path, + publicShare.accountOwner, + listOf(ShareType.PUBLIC_LINK.value) + ).getLastEmittedValue()!! + + assertNotNull(textShares) assertEquals(0, textShares.size) // List of textShares empty after deleting the existing share } diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/utils/LiveDataTestUtil.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/utils/LiveDataTestUtil.kt deleted file mode 100644 index 34bad0903dc..00000000000 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/utils/LiveDataTestUtil.kt +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.owncloud.android.data.utils - -import androidx.lifecycle.LiveData -import androidx.lifecycle.Observer -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit - -object LiveDataTestUtil { - fun getValue(liveData: LiveData): T { - val data = arrayOfNulls(1) - val latch = CountDownLatch(1) - val observer = object : Observer { - override fun onChanged(o: T?) { - data[0] = o - latch.countDown() - liveData.removeObserver(this) - } - } - liveData.observeForever(observer) - latch.await(2, TimeUnit.SECONDS) - - @Suppress("UNCHECKED_CAST") - return data[0] as T - } -} From 60a87d08a7472027a61750332c2564f5bb7fa08c Mon Sep 17 00:00:00 2001 From: davigonz Date: Thu, 28 Nov 2019 15:22:08 +0100 Subject: [PATCH 37/41] Fix ShareFileFragment getters --- .../presentation/ui/sharing/fragments/ShareFileFragment.kt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt index 22a9fbc6429..a33e9b151fe 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt @@ -178,9 +178,11 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe ) } - private val isShareApiEnabled = capabilities?.filesSharingApiEnabled == CapabilityBooleanType.TRUE + private val isShareApiEnabled + get() = capabilities?.filesSharingApiEnabled == CapabilityBooleanType.TRUE - private val isPublicShareEnabled = capabilities?.filesSharingPublicEnabled == CapabilityBooleanType.TRUE + private val isPublicShareEnabled + get() = capabilities?.filesSharingPublicEnabled == CapabilityBooleanType.TRUE private val ocCapabilityViewModel: OCCapabilityViewModel by viewModel { parametersOf( From c60ade275e6aa649741470b2ddd026a5631688b9 Mon Sep 17 00:00:00 2001 From: davigonz Date: Tue, 3 Dec 2019 10:47:36 +0100 Subject: [PATCH 38/41] Apply changes requested in library code review --- owncloud-android-library | 2 +- .../main/java/com/owncloud/android/files/FileMenuFilter.java | 1 - .../capabilities/datasources/mapper/RemoteCapabilityMapper.kt | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/owncloud-android-library b/owncloud-android-library index d5242eba3c1..ce65bc97e42 160000 --- a/owncloud-android-library +++ b/owncloud-android-library @@ -1 +1 @@ -Subproject commit d5242eba3c1b68a1baff7667f0c17bf54cbd2ce3 +Subproject commit ce65bc97e4279bf4d45c4daaa5b8cbc7f5901a07 diff --git a/owncloudApp/src/main/java/com/owncloud/android/files/FileMenuFilter.java b/owncloudApp/src/main/java/com/owncloud/android/files/FileMenuFilter.java index 7f0964ba4d8..233f2d3454e 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/files/FileMenuFilter.java +++ b/owncloudApp/src/main/java/com/owncloud/android/files/FileMenuFilter.java @@ -33,7 +33,6 @@ import com.owncloud.android.domain.capabilities.model.OCCapability; import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder; import com.owncloud.android.files.services.FileUploader.FileUploaderBinder; -import com.owncloud.android.lib.resources.status.RemoteCapability; import com.owncloud.android.services.OperationsService.OperationsServiceBinder; import com.owncloud.android.ui.activity.ComponentsGetter; import com.owncloud.android.ui.preview.PreviewVideoFragment; diff --git a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt index e9a4b15e3b3..e0a565083c2 100644 --- a/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt +++ b/owncloudData/src/main/java/com/owncloud/android/data/capabilities/datasources/mapper/RemoteCapabilityMapper.kt @@ -23,7 +23,7 @@ import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.mappers.RemoteMapper import com.owncloud.android.lib.resources.status.RemoteCapability -import com.owncloud.android.lib.resources.status.CapabilityBooleanType as RemoteCapabilityBooleanType +import com.owncloud.android.lib.resources.status.RemoteCapability.CapabilityBooleanType as RemoteCapabilityBooleanType class RemoteCapabilityMapper : RemoteMapper { override fun toModel(remote: RemoteCapability?): OCCapability? = From 01e970cdbc465afb1ba0499373d44d127c7bd97b Mon Sep 17 00:00:00 2001 From: davigonz Date: Tue, 3 Dec 2019 12:40:23 +0100 Subject: [PATCH 39/41] Apply changes requested in code review --- .../sharees/ui/SearchShareesFragmentTest.kt | 11 +- .../shares/ui/ShareFileFragmentTest.kt | 4 +- .../fragments/EditPrivateShareFragment.kt | 6 +- .../fragments/PublicShareDialogFragment.kt | 4 +- .../ui/sharing/fragments/ShareFileFragment.kt | 10 +- .../capabilities/OCCapabilityViewModel.kt | 29 +-- .../viewmodels/sharing/OCShareViewModel.kt | 207 +++++++++--------- 7 files changed, 141 insertions(+), 130 deletions(-) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt index a7a1a25b611..9c2b408b4f7 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/sharees/ui/SearchShareesFragmentTest.kt @@ -96,11 +96,10 @@ class SearchShareesFragmentTest { ) ) - onView(withText("Sheldon")).check(matches(isDisplayed())) - onView(withText("Sheldon")).check(matches(hasSibling(withId(R.id.unshareButton)))) - .check(matches(isDisplayed())) - onView(withText("Sheldon")).check(matches(hasSibling(withId(R.id.editShareButton)))) + onView(withText("Sheldon")) .check(matches(isDisplayed())) + .check(matches(hasSibling(withId(R.id.unshareButton)))) + .check(matches(hasSibling(withId(R.id.editShareButton)))) onView(withText("Penny")).check(matches(isDisplayed())) } @@ -119,9 +118,9 @@ class SearchShareesFragmentTest { ) ) - onView(withText("Friends (group)")).check(matches(isDisplayed())) - onView(withText("Friends (group)")).check(matches(hasSibling(withId(R.id.icon)))) + onView(withText("Friends (group)")) .check(matches(isDisplayed())) + .check(matches(hasSibling(withId(R.id.icon)))) onView(ViewMatchers.withTagValue(CoreMatchers.equalTo(R.drawable.ic_group))).check(matches(isDisplayed())) } } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt index d4fe0eec6f5..3c10f317ac1 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFileFragmentTest.kt @@ -111,7 +111,7 @@ class ShareFileFragmentTest { private var userSharesList = listOf( OC_SHARE.copy(sharedWithDisplayName = "Batman"), - OC_SHARE.copy(sharedWithDisplayName = "Jocker") + OC_SHARE.copy(sharedWithDisplayName = "Joker") ) private var groupSharesList = listOf( @@ -145,7 +145,7 @@ class ShareFileFragmentTest { .check(matches(isDisplayed())) onView(withText("Batman")).check(matches(hasSibling(withId(R.id.editShareButton)))) .check(matches(isDisplayed())) - onView(withText("Jocker")).check(matches(isDisplayed())) + onView(withText("Joker")).check(matches(isDisplayed())) } @Test diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt index 0afb3f0579c..2154cccc43c 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt @@ -90,11 +90,7 @@ class EditPrivateShareFragment : DialogFragment() { if (arguments != null) { file = arguments?.getParcelable(ARG_FILE) account = arguments?.getParcelable(ARG_ACCOUNT) - share = if (savedInstanceState == null) { - arguments?.getParcelable(ARG_SHARE) - } else { - savedInstanceState.getParcelable(ARG_SHARE) - } + share = savedInstanceState?.getParcelable(ARG_SHARE) ?: arguments?.getParcelable(ARG_SHARE) Log_OC.e( TAG, String.format( Locale.getDefault(), "Share has id %1\$d remoteId %2\$d", share?.id, diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt index 85e70f26fdb..2a8797594a5 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/PublicShareDialogFragment.kt @@ -156,7 +156,9 @@ class PublicShareDialogFragment : DialogFragment() { publicShare = arguments!!.getParcelable(ARG_SHARE) } - check(!(file == null && publicShare == null)) { "Both ARG_FILE and ARG_SHARE cannot be NULL" } + check(file != null || publicShare != null) { + "Both ARG_FILE and ARG_SHARE cannot be NULL" + } setStyle(STYLE_NO_TITLE, 0) } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt index a33e9b151fe..b94c8d3f62b 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt @@ -154,10 +154,9 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe return defaultName } usedNumbers.sort() - var chosenNumber = -1 - if (usedNumbers.size == 0 || usedNumbers[0] != 2) { - chosenNumber = 2 - + var chosenNumber = UNUSED_NUMBER + if (usedNumbers.size == 0 || usedNumbers[0] != USED_NUMBER_SECOND) { + chosenNumber = USED_NUMBER_SECOND } else { for (i in 0 until usedNumbers.size - 1) { val current = usedNumbers[i] @@ -612,6 +611,9 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe private const val ARG_ACCOUNT = "ACCOUNT" private const val ARG_SERVER_VERSION = "SERVER_VERSION" + private const val UNUSED_NUMBER = -1 + private const val USED_NUMBER_SECOND = 2 + /** * Public factory method to create new ShareFileFragment instances. * diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt index c1d0ce0e469..85cd9118d7a 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModel.kt @@ -31,7 +31,6 @@ import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import com.owncloud.android.providers.CoroutinesDispatcherProvider import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext /** * View Model to keep a reference to the capability repository and an up-to-date capability @@ -61,23 +60,25 @@ class OCCapabilityViewModel( } fun refreshCapabilitiesFromNetwork() { - viewModelScope.launch { - _capabilities.postValue( - Event(UIResult.Loading(capabilitiesLiveData.value)) - ) - - val useCaseResult = withContext(coroutineDispatcherProvider.io) { - refreshCapabilitiesFromServerUseCase.execute( - RefreshCapabilitiesFromServerAsyncUseCase.Params( - accountName = accountName - ) + viewModelScope.launch(coroutineDispatcherProvider.io) { + viewModelScope.launch(coroutineDispatcherProvider.main) { + _capabilities.postValue( + Event(UIResult.Loading(capabilitiesLiveData.value)) ) } - if (useCaseResult.isError) { - _capabilities.postValue( - Event(UIResult.Error(useCaseResult.getThrowableOrNull(), capabilitiesLiveData.value)) + val useCaseResult = refreshCapabilitiesFromServerUseCase.execute( + RefreshCapabilitiesFromServerAsyncUseCase.Params( + accountName = accountName ) + ) + + viewModelScope.launch(coroutineDispatcherProvider.main) { + if (useCaseResult.isError) { + _capabilities.postValue( + Event(UIResult.Error(useCaseResult.getThrowableOrNull(), capabilitiesLiveData.value)) + ) + } } } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt index 952c8b4e8f6..094a01db5f4 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModel.kt @@ -38,7 +38,6 @@ import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult import com.owncloud.android.providers.CoroutinesDispatcherProvider import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext /** * View Model to keep a reference to the share repository and an up-to-date list of a shares @@ -73,22 +72,24 @@ class OCShareViewModel( } private fun refreshSharesFromNetwork() { - viewModelScope.launch { - _shares.postValue(Event(UIResult.Loading(sharesLiveData.value))) - - val useCaseResult = withContext(coroutineDispatcherProvider.io) { - refreshSharesFromServerAsyncUseCase.execute( - RefreshSharesFromServerAsyncUseCase.Params( - filePath = filePath, - accountName = accountName - ) - ) + viewModelScope.launch(coroutineDispatcherProvider.io) { + viewModelScope.launch(coroutineDispatcherProvider.main) { + _shares.postValue(Event(UIResult.Loading(sharesLiveData.value))) } - if (!useCaseResult.isSuccess) { - _shares.postValue( - Event(UIResult.Error(useCaseResult.getThrowableOrNull(), sharesLiveData.value)) + val useCaseResult = refreshSharesFromServerAsyncUseCase.execute( + RefreshSharesFromServerAsyncUseCase.Params( + filePath = filePath, + accountName = accountName ) + ) + + viewModelScope.launch(coroutineDispatcherProvider.main) { + if (!useCaseResult.isSuccess) { + _shares.postValue( + Event(UIResult.Error(useCaseResult.getThrowableOrNull(), sharesLiveData.value)) + ) + } } } } @@ -99,21 +100,23 @@ class OCShareViewModel( fun deleteShare( remoteId: Long ) { - viewModelScope.launch { - _shareDeletionStatus.postValue( - Event(UIResult.Loading()) - ) - - val useCaseResult = withContext(coroutineDispatcherProvider.io) { - deletePublicShareUseCase.execute( - DeleteShareAsyncUseCase.Params( - remoteId - ) + viewModelScope.launch(coroutineDispatcherProvider.io) { + viewModelScope.launch(coroutineDispatcherProvider.main) { + _shareDeletionStatus.postValue( + Event(UIResult.Loading()) ) } - if (useCaseResult.isError) { - _shareDeletionStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) + val useCaseResult = deletePublicShareUseCase.execute( + DeleteShareAsyncUseCase.Params( + remoteId + ) + ) + + viewModelScope.launch(coroutineDispatcherProvider.main) { + if (useCaseResult.isError) { + _shareDeletionStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) + } } } } @@ -132,29 +135,31 @@ class OCShareViewModel( permissions: Int, accountName: String ) { - viewModelScope.launch { - _privateShareCreationStatus.postValue( - Event(UIResult.Loading()) - ) - - val useCaseResult = withContext(coroutineDispatcherProvider.io) { - createPrivateShareUseCase.execute( - CreatePrivateShareAsyncUseCase.Params( - filePath, - shareType, - shareeName, - permissions, - accountName - ) + viewModelScope.launch(coroutineDispatcherProvider.io) { + viewModelScope.launch(coroutineDispatcherProvider.main) { + _privateShareCreationStatus.postValue( + Event(UIResult.Loading()) ) } - if (useCaseResult.isSuccess) { - _privateShareCreationStatus.postValue(Event(UIResult.Success())) - } else { - _privateShareCreationStatus.postValue( - Event(UIResult.Error(useCaseResult.getThrowableOrNull())) + val useCaseResult = createPrivateShareUseCase.execute( + CreatePrivateShareAsyncUseCase.Params( + filePath, + shareType, + shareeName, + permissions, + accountName ) + ) + + viewModelScope.launch(coroutineDispatcherProvider.main) { + if (useCaseResult.isSuccess) { + _privateShareCreationStatus.postValue(Event(UIResult.Success())) + } else { + _privateShareCreationStatus.postValue( + Event(UIResult.Error(useCaseResult.getThrowableOrNull())) + ) + } } } } @@ -183,23 +188,25 @@ class OCShareViewModel( permissions: Int, accountName: String ) { - viewModelScope.launch { - _privateShareEditionStatus.postValue( - Event(UIResult.Loading()) - ) - - val useCaseResult = withContext(coroutineDispatcherProvider.io) { - editPrivateShareUseCase.execute( - EditPrivateShareAsyncUseCase.Params( - remoteId, - permissions, - accountName - ) + viewModelScope.launch(coroutineDispatcherProvider.io) { + viewModelScope.launch(coroutineDispatcherProvider.main) { + _privateShareEditionStatus.postValue( + Event(UIResult.Loading()) ) } - if (useCaseResult.isError) { - _privateShareEditionStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) + val useCaseResult = editPrivateShareUseCase.execute( + EditPrivateShareAsyncUseCase.Params( + remoteId, + permissions, + accountName + ) + ) + + viewModelScope.launch(coroutineDispatcherProvider.main) { + if (useCaseResult.isError) { + _privateShareEditionStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) + } } } } @@ -220,29 +227,31 @@ class OCShareViewModel( publicUpload: Boolean, accountName: String ) { - viewModelScope.launch { - _publicShareCreationStatus.postValue( - Event(UIResult.Loading()) - ) - - val useCaseResult = withContext(coroutineDispatcherProvider.io) { - createPublicShareUseCase.execute( - CreatePublicShareAsyncUseCase.Params( - filePath, - permissions, - name, - password, - expirationTimeInMillis, - publicUpload, - accountName - ) + viewModelScope.launch(coroutineDispatcherProvider.io) { + viewModelScope.launch(coroutineDispatcherProvider.main) { + _publicShareCreationStatus.postValue( + Event(UIResult.Loading()) ) } - if (useCaseResult.isSuccess) { - _publicShareCreationStatus.postValue(Event(UIResult.Success())) - } else { - _publicShareCreationStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) + val useCaseResult = createPublicShareUseCase.execute( + CreatePublicShareAsyncUseCase.Params( + filePath, + permissions, + name, + password, + expirationTimeInMillis, + publicUpload, + accountName + ) + ) + + viewModelScope.launch(coroutineDispatcherProvider.main) { + if (useCaseResult.isSuccess) { + _publicShareCreationStatus.postValue(Event(UIResult.Success())) + } else { + _publicShareCreationStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) + } } } } @@ -259,27 +268,29 @@ class OCShareViewModel( publicUpload: Boolean, accountName: String ) { - viewModelScope.launch { - _publicShareEditionStatus.postValue(Event(UIResult.Loading())) - - val useCaseResult = withContext(coroutineDispatcherProvider.io) { - editPublicShareUseCase.execute( - EditPublicShareAsyncUseCase.Params( - remoteId, - name, - password, - expirationDateInMillis, - permissions, - publicUpload, - accountName - ) - ) + viewModelScope.launch(coroutineDispatcherProvider.io) { + viewModelScope.launch(coroutineDispatcherProvider.main) { + _publicShareEditionStatus.postValue(Event(UIResult.Loading())) } - if (useCaseResult.isSuccess) { - _publicShareEditionStatus.postValue(Event(UIResult.Success())) - } else { - _publicShareEditionStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) + val useCaseResult = editPublicShareUseCase.execute( + EditPublicShareAsyncUseCase.Params( + remoteId, + name, + password, + expirationDateInMillis, + permissions, + publicUpload, + accountName + ) + ) + + viewModelScope.launch(coroutineDispatcherProvider.main) { + if (useCaseResult.isSuccess) { + _publicShareEditionStatus.postValue(Event(UIResult.Success())) + } else { + _publicShareEditionStatus.postValue(Event(UIResult.Error(useCaseResult.getThrowableOrNull()))) + } } } } From 1e9168fdb42147bf3ea1c767ba63835768d7254f Mon Sep 17 00:00:00 2001 From: davigonz Date: Wed, 4 Dec 2019 10:16:05 +0100 Subject: [PATCH 40/41] More changes requested in code review --- build.gradle | 6 +- owncloud-android-library | 2 +- owncloudApp/build.gradle | 6 +- .../android/datamodel/OCFileUnitTest.java | 9 +-- .../OCSettingsCameraUploadsTest.kt | 48 ++++++----- .../OCSettingsLocalFolderPickerTest.kt | 12 +-- .../settings/more/OCSettingsLogTest.kt | 21 ++--- .../settings/more/OCSettingsMoreTest.kt | 79 +++++++++++-------- .../more/OCSettingsPrivacyPolicyTest.kt | 10 +-- .../security/OCSettingsPasscodeTest.kt | 22 +++--- .../security/OCSettingsPatternLockTest.kt | 12 +-- .../security/OCSettingsSecurityTest.kt | 45 +++++------ .../shares/ui/EditPrivateShareFragmentTest.kt | 3 - .../PublicShareEditionDialogFragmentTest.kt | 7 +- .../shares/ui/ShareFolderFragmentTest.kt | 3 - .../shares/ui/SharesContentProviderTest.kt | 3 - .../android/testing/SingleFragmentActivity.kt | 12 --- .../ui/sharing/fragments/ShareFileFragment.kt | 2 +- .../capabilities/OCCapabilityViewModelTest.kt | 4 - .../sharing/OCShareViewModelTest.kt | 18 ++--- owncloudData/build.gradle | 6 +- .../owncloud/android/data/MigrationTest.kt | 18 +++-- .../repository/OCCapabilityRepositoryTest.kt | 3 - .../repository/OCShareeRepositoryTest.kt | 3 - .../repository/OCShareRepositoryTest.kt | 3 - owncloudDomain/build.gradle | 6 +- owncloudTestUtil/build.gradle | 8 +- .../testutil/livedata/TestTimeOutConstants.kt | 3 +- 28 files changed, 171 insertions(+), 203 deletions(-) diff --git a/build.gradle b/build.gradle index 8a435cf2c6b..d6ba88f4500 100644 --- a/build.gradle +++ b/build.gradle @@ -1,12 +1,16 @@ buildscript { ext { - + // SDK + sdkCompileVersion = 28 + sdkMinVersion = 19 + sdkTargetVersion = 28 // Android jetpack archLifecycleVersion = "2.1.0" roomVersion = "2.2.2" appCompat = "1.1.0" sqliteVersion = "2.0.1" + lifecycleLiveData = "2.0.0" // Kotlin kotlinVersion = "1.3.50" diff --git a/owncloud-android-library b/owncloud-android-library index ce65bc97e42..78d6ca08e23 160000 --- a/owncloud-android-library +++ b/owncloud-android-library @@ -1 +1 @@ -Subproject commit ce65bc97e4279bf4d45c4daaa5b8cbc7f5901a07 +Subproject commit 78d6ca08e233de74413f6a8643c441ec0896be42 diff --git a/owncloudApp/build.gradle b/owncloudApp/build.gradle index ab4798bb537..a0da2479bbc 100644 --- a/owncloudApp/build.gradle +++ b/owncloudApp/build.gradle @@ -92,11 +92,11 @@ allOpen { } android { - compileSdkVersion 28 + compileSdkVersion sdkCompileVersion defaultConfig { - minSdkVersion 19 - targetSdkVersion 28 + minSdkVersion sdkMinVersion + targetSdkVersion sdkTargetVersion versionCode = 21300100 versionName = "2.13.1" diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/datamodel/OCFileUnitTest.java b/owncloudApp/src/androidTest/java/com/owncloud/android/datamodel/OCFileUnitTest.java index bc10e82d464..4857a755b20 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/datamodel/OCFileUnitTest.java +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/datamodel/OCFileUnitTest.java @@ -3,16 +3,16 @@ * * @author David A. Velasco * Copyright (C) 2017 ownCloud GmbH. - *

+ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. - *

+ * * This program 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 this program. If not, see . */ @@ -21,11 +21,9 @@ import android.os.Parcel; -import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -39,7 +37,6 @@ * * See http://developer.android.com/intl/es/training/testing/unit-testing/instrumented-unit-tests.html . */ -@RunWith(AndroidJUnit4.class) @SmallTest public class OCFileUnitTest { diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/camerauploads/OCSettingsCameraUploadsTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/camerauploads/OCSettingsCameraUploadsTest.kt index 9c6a6ae2471..bb6085b03b8 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/camerauploads/OCSettingsCameraUploadsTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/camerauploads/OCSettingsCameraUploadsTest.kt @@ -30,24 +30,19 @@ import androidx.test.espresso.intent.Intents import androidx.test.espresso.intent.matcher.IntentMatchers import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.ActivityTestRule import com.owncloud.android.R import com.owncloud.android.ui.activity.LocalFolderPickerActivity import com.owncloud.android.ui.activity.Preferences -import org.junit.Assert -import org.junit.Assert.assertTrue +import org.junit.After import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Before -import org.junit.After import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -@RunWith(AndroidJUnit4::class) class OCSettingsCameraUploadsTest { - @Rule @JvmField val activityRule = ActivityTestRule(Preferences::class.java, true, true) @@ -68,7 +63,7 @@ class OCSettingsCameraUploadsTest { } @After - fun tearDown(){ + fun tearDown() { //Clean preferences PreferenceManager.getDefaultSharedPreferences(context).edit().clear().commit() } @@ -100,9 +95,14 @@ class OCSettingsCameraUploadsTest { @Test fun optionsCameraFolderBehaviour() { //Asserts - onView(withText(String.format( - activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title), - activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title_required)))) + onView( + withText( + String.format( + activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title), + activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title_required) + ) + ) + ) .check(doesNotExist()) onView(withText(R.string.prefs_camera_upload_behaviour_title)).check(doesNotExist()) onView(withText(R.string.pref_behaviour_entries_keep_file)).check(doesNotExist()) @@ -176,9 +176,14 @@ class OCSettingsCameraUploadsTest { fun cameraFolderView() { enableCameraPictureUploads() //Asserts - onView(withText(String.format( - activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title), - activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title_required)))) + onView( + withText( + String.format( + activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title), + activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title_required) + ) + ) + ) .check(matches(isDisplayed())) } @@ -190,9 +195,14 @@ class OCSettingsCameraUploadsTest { ).absolutePath + "/Camera"; Intents.init() //Asserts - onView(withText(String.format( - activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title), - activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title_required)))) + onView( + withText( + String.format( + activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title), + activityRule.activity.getString(R.string.prefs_camera_upload_source_path_title_required) + ) + ) + ) .perform(click()) Intents.intended(IntentMatchers.hasComponent(LocalFolderPickerActivity::class.java.name)) IntentMatchers.hasExtra(LocalFolderPickerActivity.EXTRA_PATH, cameraFolder) @@ -209,12 +219,12 @@ class OCSettingsCameraUploadsTest { onView(withText(R.string.pref_behaviour_entries_move)).check(matches(isDisplayed())) } - fun enableCameraPictureUploads(){ + fun enableCameraPictureUploads() { onView(withText(R.string.prefs_camera_picture_upload)).perform(click()); onView(withText(android.R.string.ok)).perform(click()) } - fun enableCameraVideoUploads(){ + fun enableCameraVideoUploads() { onView(withText(R.string.prefs_camera_video_upload)).perform(click()); onView(withText(android.R.string.ok)).perform(click()) } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/camerauploads/OCSettingsLocalFolderPickerTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/camerauploads/OCSettingsLocalFolderPickerTest.kt index 40fce405f25..70f651975cb 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/camerauploads/OCSettingsLocalFolderPickerTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/camerauploads/OCSettingsLocalFolderPickerTest.kt @@ -17,7 +17,6 @@ * along with this program. If not, see . */ - package com.owncloud.android.settings.camerauploads import android.os.Environment @@ -27,16 +26,13 @@ import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import com.owncloud.android.R import com.owncloud.android.ui.activity.LocalFolderPickerActivity import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -@RunWith(AndroidJUnit4::class) class OCSettingsLocalFolderPickerTest { @Rule @@ -46,26 +42,26 @@ class OCSettingsLocalFolderPickerTest { val errorMessage = "Activity not finished" @Test - fun localFolderPickerView(){ + fun localFolderPickerView() { onView(withId(R.id.folder_picker_btn_cancel)).check(matches(isDisplayed())) onView(withId(R.id.folder_picker_btn_choose)).check(matches(isDisplayed())) onView(withId(R.id.folder_picker_btn_home)).check(matches(isDisplayed())) } @Test - fun cancelButtonDismiss(){ + fun cancelButtonDismiss() { onView(withId(R.id.folder_picker_btn_cancel)).perform(click()) assertTrue(errorMessage, activityRule.activity.isFinishing) } @Test - fun chooseButtonDismiss(){ + fun chooseButtonDismiss() { onView(withId(R.id.folder_picker_btn_choose)).perform(click()) assertTrue(errorMessage, activityRule.activity.isFinishing) } @Test - fun homeButtonBrowsesToHome(){ + fun homeButtonBrowsesToHome() { onView(withId(R.id.folder_picker_btn_home)).perform(click()) val path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsLogTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsLogTest.kt index c8e4f62ed71..26abbe0d176 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsLogTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsLogTest.kt @@ -36,7 +36,6 @@ import androidx.test.espresso.intent.matcher.IntentMatchers.hasType import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.ActivityTestRule import com.owncloud.android.R @@ -45,9 +44,7 @@ import org.hamcrest.Matchers import org.junit.Before import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -@RunWith(AndroidJUnit4::class) class OCSettingsLogTest { @Rule @@ -55,28 +52,29 @@ class OCSettingsLogTest { val activityRule = ActivityTestRule(LogHistoryActivity::class.java, true, true) @Before - fun setUp() {} + fun setUp() { + } @Test - fun checkTitle(){ + fun checkTitle() { onView(withText(R.string.actionbar_logger)).check(matches(isDisplayed())) } @Test - fun itemsToolbar(){ + fun itemsToolbar() { onView(withId(R.id.menu_search)).check(matches(isDisplayed())) openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getInstrumentation().targetContext) onView(withText("Logcat")).check(matches(isDisplayed())) } @Test - fun logHistoryButtons(){ + fun logHistoryButtons() { onView(withId(R.id.deleteLogHistoryButton)).check(matches(isDisplayed())) onView(withId(R.id.sendLogHistoryButton)).check(matches(isDisplayed())) } @Test - fun sendLogHistory(){ + fun sendLogHistory() { Intents.init() val intentResult = Instrumentation.ActivityResult(Activity.RESULT_OK, Intent()) intending(hasAction(Intent.ACTION_SEND_MULTIPLE)).respondWith(intentResult); @@ -84,10 +82,13 @@ class OCSettingsLogTest { intended( Matchers.allOf( hasAction(Intent.ACTION_SEND_MULTIPLE), - hasExtra(Intent.EXTRA_SUBJECT, + hasExtra( + Intent.EXTRA_SUBJECT, String.format( activityRule.activity.getString(R.string.log_send_mail_subject), - activityRule.activity.getString(R.string.app_name))), + activityRule.activity.getString(R.string.app_name) + ) + ), hasType("text/plain"), hasFlag(Intent.FLAG_ACTIVITY_NEW_TASK) ) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsMoreTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsMoreTest.kt index aa77e73d629..9c8f8fe5340 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsMoreTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsMoreTest.kt @@ -38,7 +38,6 @@ import androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra import androidx.test.espresso.intent.matcher.IntentMatchers.hasFlag import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import com.owncloud.android.BuildConfig import com.owncloud.android.R @@ -49,9 +48,7 @@ import org.hamcrest.Matchers.allOf import org.junit.Before import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -@RunWith(AndroidJUnit4::class) class OCSettingsMoreTest { @Rule @@ -71,14 +68,13 @@ class OCSettingsMoreTest { preferenceScreen.removePreference(securityCategory) } - @Test - fun helpView(){ + fun helpView() { onView(withText(R.string.prefs_help)).check(matches(isDisplayed())) } @Test - fun helpOptionOpensWeb(){ + fun helpOptionOpensWeb() { Intents.init() onView(withText(R.string.prefs_help)).perform(click()) val intentResult = ActivityResult(Activity.RESULT_OK, Intent()) @@ -88,13 +84,13 @@ class OCSettingsMoreTest { } @Test - fun davx5View(){ + fun davx5View() { onView(withText(R.string.prefs_sync_calendar_contacts)).check(matches(isDisplayed())) onView(withText(R.string.prefs_sync_calendar_contacts_summary)).check(matches(isDisplayed())) } @Test - fun davx5OpensLink(){ + fun davx5OpensLink() { Intents.init() val intentResult = ActivityResult(Activity.RESULT_OK, Intent()) intending(hasAction(Intent.ACTION_VIEW)).respondWith(intentResult); @@ -104,59 +100,72 @@ class OCSettingsMoreTest { } @Test - fun recommendView(){ + fun recommendView() { onView(withText(R.string.prefs_recommend)).check(matches(isDisplayed())) } @Test - fun recommendOpenSender(){ + fun recommendOpenSender() { Intents.init() val intentResult = ActivityResult(Activity.RESULT_OK, Intent()) intending(hasAction(Intent.ACTION_SENDTO)).respondWith(intentResult); onView(withText(R.string.prefs_recommend)).perform(click()) - intended(allOf( - hasAction(Intent.ACTION_SENDTO), - hasExtra(Intent.EXTRA_SUBJECT, - String.format( - activityRule.activity.getString(R.string.recommend_subject), - activityRule.activity.getString(R.string.app_name))), - hasExtra(Intent.EXTRA_TEXT, - String.format( - activityRule.activity.getString(R.string.recommend_text), - activityRule.activity.getString(R.string.app_name), - activityRule.activity.getString(R.string.url_app_download) - )), - hasFlag(Intent.FLAG_ACTIVITY_NEW_TASK))) + intended( + allOf( + hasAction(Intent.ACTION_SENDTO), + hasExtra( + Intent.EXTRA_SUBJECT, + String.format( + activityRule.activity.getString(R.string.recommend_subject), + activityRule.activity.getString(R.string.app_name) + ) + ), + hasExtra( + Intent.EXTRA_TEXT, + String.format( + activityRule.activity.getString(R.string.recommend_text), + activityRule.activity.getString(R.string.app_name), + activityRule.activity.getString(R.string.url_app_download) + ) + ), + hasFlag(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + ) Intents.release() } @Test - fun feedbackView(){ + fun feedbackView() { onView(withText(R.string.drawer_feedback)).check(matches(isDisplayed())) } @Test - fun feedbackOpenSender(){ + fun feedbackOpenSender() { Intents.init() val intentResult = ActivityResult(Activity.RESULT_OK, Intent()) intending(hasAction(Intent.ACTION_SENDTO)).respondWith(intentResult); onView(withText(R.string.drawer_feedback)).perform(click()) - intended(allOf( - hasAction(Intent.ACTION_SENDTO), - hasExtra(Intent.EXTRA_SUBJECT, - "Android v" + BuildConfig.VERSION_NAME + " - " + activityRule.activity.getText(R.string.prefs_feedback)), - hasData(Uri.parse(activityRule.activity.getText(R.string.mail_feedback) as String)), - hasFlag(Intent.FLAG_ACTIVITY_NEW_TASK))) + intended( + allOf( + hasAction(Intent.ACTION_SENDTO), + hasExtra( + Intent.EXTRA_SUBJECT, + "Android v" + BuildConfig.VERSION_NAME + " - " + activityRule.activity.getText(R.string.prefs_feedback) + ), + hasData(Uri.parse(activityRule.activity.getText(R.string.mail_feedback) as String)), + hasFlag(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + ) Intents.release() } @Test - fun loggerView(){ + fun loggerView() { onView(withText(R.string.actionbar_logger)).check(matches(isDisplayed())) } @Test - fun loggerOpen(){ + fun loggerOpen() { Intents.init() onView(withText(R.string.actionbar_logger)).perform(click()) intended(hasComponent(LogHistoryActivity::class.java.name)) @@ -164,12 +173,12 @@ class OCSettingsMoreTest { } @Test - fun privacyPolicyView(){ + fun privacyPolicyView() { onView(withText(R.string.prefs_privacy_policy)).check(matches(isDisplayed())) } @Test - fun privacyPolicyOpenWeb(){ + fun privacyPolicyOpenWeb() { Intents.init() onView(withText(R.string.prefs_privacy_policy)).perform(click()) intended(hasComponent(PrivacyPolicyActivity::class.java.name)) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsPrivacyPolicyTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsPrivacyPolicyTest.kt index ff66e6c3b38..928ea58b21a 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsPrivacyPolicyTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/more/OCSettingsPrivacyPolicyTest.kt @@ -27,7 +27,6 @@ import androidx.test.espresso.web.sugar.Web.onWebView import androidx.test.espresso.web.webdriver.DriverAtoms.findElement import androidx.test.espresso.web.webdriver.DriverAtoms.getText import androidx.test.espresso.web.webdriver.Locator -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import com.owncloud.android.R import com.owncloud.android.ui.activity.PrivacyPolicyActivity @@ -36,9 +35,7 @@ import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -@RunWith(AndroidJUnit4::class) class OCSettingsPrivacyPolicyTest { @Rule @@ -51,7 +48,8 @@ class OCSettingsPrivacyPolicyTest { private val contentText = "Privacy Policy" @Before - fun setUp() {} + fun setUp() { + } @After fun tearDown() { @@ -59,12 +57,12 @@ class OCSettingsPrivacyPolicyTest { } @Test - fun checkTitle(){ + fun checkTitle() { onView(withText(R.string.actionbar_privacy_policy)).check(matches(isDisplayed())) } @Test - fun privacyPolicyLoaded(){ + fun privacyPolicyLoaded() { onWebView().withElement(findElement(Locator.ID, introductionID)) .check(webMatches(getText(), containsString(introductionText))) onWebView().withElement(findElement(Locator.ID, contentID)) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsPasscodeTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsPasscodeTest.kt index 89131adfb15..cdfa1041a84 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsPasscodeTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsPasscodeTest.kt @@ -33,7 +33,6 @@ import androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.ActivityTestRule import com.owncloud.android.R @@ -44,9 +43,7 @@ import org.junit.Assert.assertTrue import org.junit.Ignore import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -@RunWith(AndroidJUnit4::class) class OCSettingsPasscodeTest { @Rule @@ -58,8 +55,8 @@ class OCSettingsPasscodeTest { private val KEY_PASSCODE = "KEY_PASSCODE" private val context = InstrumentationRegistry.getInstrumentation().targetContext - private val DEFAULT_PASSCODE = arrayOf('1','1','1','1') - private val WRONG_PASSCODE = arrayOf('1','1','1','2') + private val DEFAULT_PASSCODE = arrayOf('1', '1', '1', '1') + private val WRONG_PASSCODE = arrayOf('1', '1', '1', '2') private val PASSCODE_TOSAVE = "1111" @After @@ -68,9 +65,8 @@ class OCSettingsPasscodeTest { PreferenceManager.getDefaultSharedPreferences(context).edit().clear().commit() } - @Test - fun passcodeView(){ + fun passcodeView() { //Open Activity in passcode creation mode openPasscodeActivity(PassCodeActivity.ACTION_REQUEST_WITH_RESULT) @@ -86,7 +82,7 @@ class OCSettingsPasscodeTest { } @Test - fun firstTry(){ + fun firstTry() { //Open Activity in passcode creation mode openPasscodeActivity(PassCodeActivity.ACTION_REQUEST_WITH_RESULT) @@ -98,7 +94,7 @@ class OCSettingsPasscodeTest { } @Test - fun secondTryCorrect(){ + fun secondTryCorrect() { //Open Activity in passcode creation mode openPasscodeActivity(PassCodeActivity.ACTION_REQUEST_WITH_RESULT) @@ -116,7 +112,7 @@ class OCSettingsPasscodeTest { @Test @Ignore - fun secondTryIncorrect(){ + fun secondTryIncorrect() { //Open Activity in passcode creation mode openPasscodeActivity(PassCodeActivity.ACTION_REQUEST_WITH_RESULT) @@ -198,19 +194,19 @@ class OCSettingsPasscodeTest { onView(withText(R.string.pass_code_enter_pass_code)).check(matches(isDisplayed())) } - private fun openPasscodeActivity (mode: String) { + private fun openPasscodeActivity(mode: String) { intent.action = mode activityRule.launchActivity(intent) } - private fun typePasscode (digits: Array){ + private fun typePasscode(digits: Array) { onView(withId(R.id.txt0)).perform(replaceText(digits[0].toString())) onView(withId(R.id.txt1)).perform(replaceText(digits[1].toString())) onView(withId(R.id.txt2)).perform(replaceText(digits[2].toString())) onView(withId(R.id.txt3)).perform(replaceText(digits[3].toString())) } - private fun storePasscode (passcode: String = PASSCODE_TOSAVE){ + private fun storePasscode(passcode: String = PASSCODE_TOSAVE) { val appPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit(); for (i in 1..4) { appPrefs.putString( diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsPatternLockTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsPatternLockTest.kt index 1da0e7c40ba..f9d58935800 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsPatternLockTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsPatternLockTest.kt @@ -27,19 +27,15 @@ import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.ActivityTestRule import com.owncloud.android.R -import com.owncloud.android.ui.activity.PassCodeActivity import com.owncloud.android.ui.activity.PatternLockActivity import org.junit.After import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -@RunWith(AndroidJUnit4::class) class OCSettingsPatternLockTest { @Rule @@ -58,7 +54,7 @@ class OCSettingsPatternLockTest { } @Test - fun patternLockView(){ + fun patternLockView() { //Open Activity in pattern creation mode openPatternActivity(PatternLockActivity.ACTION_REQUEST_WITH_RESULT) @@ -69,7 +65,7 @@ class OCSettingsPatternLockTest { } @Test - fun cancelPatternLock(){ + fun cancelPatternLock() { //Open Activity in pattern creation mode openPatternActivity(PatternLockActivity.ACTION_REQUEST_WITH_RESULT) @@ -89,14 +85,14 @@ class OCSettingsPatternLockTest { onView(withText(R.string.pattern_no_longer_required)).check(matches(isDisplayed())) } - private fun storePattern(){ + private fun storePattern() { val appPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit(); appPrefs.putString(PatternLockActivity.KEY_PATTERN, PATTERN_TOSAVE) appPrefs.putBoolean(PatternLockActivity.PREFERENCE_SET_PATTERN, true) appPrefs.apply() } - private fun openPatternActivity (mode: String) { + private fun openPatternActivity(mode: String) { intent.action = mode activityRule.launchActivity(intent) } diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsSecurityTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsSecurityTest.kt index 2eb14c3fb80..286d99b6048 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsSecurityTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/settings/security/OCSettingsSecurityTest.kt @@ -29,15 +29,14 @@ import android.preference.PreferenceScreen import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.isEnabled -import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.espresso.intent.Intents import androidx.test.espresso.intent.Intents.intended import androidx.test.espresso.intent.Intents.intending import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent -import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.espresso.matcher.ViewMatchers.isDisplayed +import androidx.test.espresso.matcher.ViewMatchers.isEnabled +import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.ActivityTestRule import com.owncloud.android.R @@ -51,9 +50,7 @@ import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -@RunWith(AndroidJUnit4::class) class OCSettingsSecurityTest { @Rule @@ -95,14 +92,14 @@ class OCSettingsSecurityTest { } @After - fun tearDown(){ + fun tearDown() { Intents.release() //clear SharedPreferences PreferenceManager.getDefaultSharedPreferences(context).edit().clear().commit() } @Test - fun securityView(){ + fun securityView() { onView(withText(R.string.prefs_passcode)).check(matches(isDisplayed())) onView(withText(R.string.prefs_pattern)).check(matches(isDisplayed())) onView(withText(R.string.prefs_fingerprint)).check(matches(isDisplayed())) @@ -113,19 +110,19 @@ class OCSettingsSecurityTest { } @Test - fun passcodeOpen(){ + fun passcodeOpen() { onView(withText(R.string.prefs_passcode)).perform(click()) intended(hasComponent(PassCodeActivity::class.java.name)) } @Test - fun patternOpen(){ + fun patternOpen() { onView(withText(R.string.prefs_pattern)).perform(click()) intended(hasComponent(PatternLockActivity::class.java.name)) } @Test - fun passcodeLockEnabled(){ + fun passcodeLockEnabled() { val result = Intent() result.putExtra(KEY_PASSCODE, PASSCODE_VALUE) val intentResult = Instrumentation.ActivityResult(Activity.RESULT_OK, result) @@ -136,7 +133,7 @@ class OCSettingsSecurityTest { } @Test - fun patternLockEnabled(){ + fun patternLockEnabled() { val result = Intent() result.putExtra(KEY_PATTERN, PATTERN_VALUE) val intentResult = Instrumentation.ActivityResult(Activity.RESULT_OK, result) @@ -147,33 +144,33 @@ class OCSettingsSecurityTest { } @Test - fun enablePasscodeEnablesFingerprint(){ + fun enablePasscodeEnablesFingerprint() { firstEnablePasscode() onView(withText(R.string.prefs_fingerprint)).check(matches(isEnabled())) } @Test - fun enablePatternEnablesFingerprint(){ + fun enablePatternEnablesFingerprint() { firstEnablePattern() onView(withText(R.string.prefs_fingerprint)).check(matches(isEnabled())) } @Test - fun onlyOneMethodEnabledPattern(){ + fun onlyOneMethodEnabledPattern() { firstEnablePattern() onView(withText(R.string.prefs_passcode)).perform(click()) onView(withText(R.string.pattern_already_set)).check(matches(isEnabled())) } @Test - fun onlyOneMethodEnabledPasscode(){ + fun onlyOneMethodEnabledPasscode() { firstEnablePasscode() onView(withText(R.string.prefs_pattern)).perform(click()) onView(withText(R.string.passcode_already_set)).check(matches(isEnabled())) } @Test - fun disablePasscode(){ + fun disablePasscode() { firstEnablePasscode() val result = Intent() result.putExtra(KEY_CHECK_RESULT, true) @@ -186,7 +183,7 @@ class OCSettingsSecurityTest { } @Test - fun disablePattern(){ + fun disablePattern() { firstEnablePattern() val result = Intent() result.putExtra(KEY_CHECK_PATTERN_RESULT, true) @@ -199,7 +196,7 @@ class OCSettingsSecurityTest { } @Test - fun touchesDialog(){ + fun touchesDialog() { onView(withText(R.string.prefs_touches_with_other_visible_windows)).perform(click()) onView(withText(activityRule.activity.getString(R.string.confirmation_touches_with_other_windows_title))) .check(matches(isDisplayed())) @@ -208,28 +205,28 @@ class OCSettingsSecurityTest { } @Test - fun touchesEnable(){ + fun touchesEnable() { onView(withText(R.string.prefs_touches_with_other_visible_windows)).perform(click()) onView(withText(R.string.common_yes)).perform(click()) assertTrue(mPrefTouches.isChecked) } @Test - fun touchesRefuse(){ + fun touchesRefuse() { onView(withText(R.string.prefs_touches_with_other_visible_windows)).perform(click()) onView(withText(R.string.common_no)).perform(click()) assertFalse(mPrefTouches.isChecked) } @Test - fun disableTouches(){ + fun disableTouches() { onView(withText(R.string.prefs_touches_with_other_visible_windows)).perform(click()) onView(withText(R.string.common_yes)).perform(click()) onView(withText(R.string.prefs_touches_with_other_visible_windows)).perform(click()) assertFalse(mPrefTouches.isChecked) } - private fun firstEnablePasscode(){ + private fun firstEnablePasscode() { val result = Intent() result.putExtra(KEY_PASSCODE, PASSCODE_VALUE) val intentResult = Instrumentation.ActivityResult(Activity.RESULT_OK, result) @@ -237,7 +234,7 @@ class OCSettingsSecurityTest { onView(withText(R.string.prefs_passcode)).perform(click()) } - private fun firstEnablePattern(){ + private fun firstEnablePattern() { val result = Intent() result.putExtra(KEY_PATTERN, PATTERN_VALUE) val intentResult = Instrumentation.ActivityResult(Activity.RESULT_OK, result) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt index 284d060d6b3..3c83468a259 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/EditPrivateShareFragmentTest.kt @@ -31,7 +31,6 @@ import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.isNotChecked import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.R import com.owncloud.android.domain.sharing.shares.model.OCShare @@ -49,14 +48,12 @@ import io.mockk.mockk import org.hamcrest.CoreMatchers.not import org.junit.Before import org.junit.Test -import org.junit.runner.RunWith import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.dsl.module -@RunWith(AndroidJUnit4::class) class EditPrivateShareFragmentTest { private val targetContext = InstrumentationRegistry.getInstrumentation().targetContext private val defaultSharedWithDisplayName = "user" diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt index 50633bfaf6d..e504a05af2c 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/PublicShareEditionDialogFragmentTest.kt @@ -26,13 +26,12 @@ import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers -import androidx.test.espresso.matcher.ViewMatchers.isChecked import androidx.test.espresso.matcher.ViewMatchers.Visibility.VISIBLE +import androidx.test.espresso.matcher.ViewMatchers.isChecked import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility import androidx.test.espresso.matcher.ViewMatchers.withHint import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.runners.AndroidJUnit4 import com.owncloud.android.R import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.ShareType @@ -49,7 +48,6 @@ import io.mockk.every import io.mockk.mockk import org.junit.Before import org.junit.Test -import org.junit.runner.RunWith import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin @@ -60,7 +58,6 @@ import java.text.SimpleDateFormat import java.util.GregorianCalendar import java.util.TimeZone -@RunWith(AndroidJUnit4::class) class PublicShareEditionDialogFragmentTest { private val ocCapabilityViewModel = mockk(relaxed = true) private val capabilitiesLiveData = MutableLiveData>>() @@ -135,7 +132,7 @@ class PublicShareEditionDialogFragmentTest { val calendar = GregorianCalendar() calendar.timeInMillis = expirationDate - val formatter: DateFormat = SimpleDateFormat("MMM dd, yyyy") + val formatter: DateFormat = SimpleDateFormat.getDateInstance() formatter.timeZone = TimeZone.getDefault() val time = formatter.format(calendar.time) diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt index 7a0613acb7e..a3464eb43e2 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/ShareFolderFragmentTest.kt @@ -28,7 +28,6 @@ import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.ext.junit.runners.AndroidJUnit4 import com.owncloud.android.R import com.owncloud.android.domain.capabilities.model.OCCapability import com.owncloud.android.domain.sharing.shares.model.OCShare @@ -48,14 +47,12 @@ import io.mockk.mockkClass import org.hamcrest.CoreMatchers.not import org.junit.Before import org.junit.Test -import org.junit.runner.RunWith import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.dsl.module -@RunWith(AndroidJUnit4::class) class ShareFolderFragmentTest { private val ocCapabilityViewModel = mockk(relaxed = true) private val capabilitiesLiveData = MutableLiveData>>() diff --git a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/SharesContentProviderTest.kt b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/SharesContentProviderTest.kt index 21b4504b484..34cd7a7f1e6 100644 --- a/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/SharesContentProviderTest.kt +++ b/owncloudApp/src/androidTest/java/com/owncloud/android/sharing/shares/ui/SharesContentProviderTest.kt @@ -21,7 +21,6 @@ package com.owncloud.android.sharing.shares.ui import android.content.ContentResolver import android.content.ContentValues -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.OwncloudDatabase @@ -31,9 +30,7 @@ import org.hamcrest.Matchers.notNullValue import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test -import org.junit.runner.RunWith -@RunWith(AndroidJUnit4::class) @SmallTest class SharesContentProviderTest { private var mContentResolver: ContentResolver? = null diff --git a/owncloudApp/src/debug/java/com/owncloud/android/testing/SingleFragmentActivity.kt b/owncloudApp/src/debug/java/com/owncloud/android/testing/SingleFragmentActivity.kt index b9e09b558cd..62f6f88255f 100644 --- a/owncloudApp/src/debug/java/com/owncloud/android/testing/SingleFragmentActivity.kt +++ b/owncloudApp/src/debug/java/com/owncloud/android/testing/SingleFragmentActivity.kt @@ -38,16 +38,4 @@ open class SingleFragmentActivity : BaseActivity() { } setContentView(content) } - - fun setFragment(fragment: Fragment) { - supportFragmentManager.beginTransaction() - .add(R.id.container, fragment, "TEST FRAGMENT") - .commitAllowingStateLoss() - } - - fun replaceFragment(fragment: Fragment) { - supportFragmentManager.beginTransaction() - .replace(R.id.container, fragment) - .commit() - } } diff --git a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt index b94c8d3f62b..3225406d5b7 100644 --- a/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt +++ b/owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/ShareFileFragment.kt @@ -155,7 +155,7 @@ class ShareFileFragment : Fragment(), ShareUserListAdapter.ShareUserAdapterListe } usedNumbers.sort() var chosenNumber = UNUSED_NUMBER - if (usedNumbers.size == 0 || usedNumbers[0] != USED_NUMBER_SECOND) { + if (usedNumbers.firstOrNull() != USED_NUMBER_SECOND) { chosenNumber = USED_NUMBER_SECOND } else { for (i in 0 until usedNumbers.size - 1) { diff --git a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModelTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModelTest.kt index fadf2e9d6dc..c36f46e7e61 100644 --- a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModelTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/capabilities/OCCapabilityViewModelTest.kt @@ -28,7 +28,6 @@ import com.owncloud.android.domain.capabilities.usecases.GetCapabilitiesAsLiveDa import com.owncloud.android.domain.capabilities.usecases.RefreshCapabilitiesFromServerAsyncUseCase import com.owncloud.android.domain.utils.Event import com.owncloud.android.presentation.UIResult -import com.owncloud.android.presentation.viewmodels.capabilities.OCCapabilityViewModel import com.owncloud.android.providers.CoroutinesDispatcherProvider import com.owncloud.android.testutil.OC_ACCOUNT_NAME import com.owncloud.android.testutil.OC_CAPABILITY @@ -50,10 +49,7 @@ import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -import org.junit.runners.JUnit4 -@RunWith(JUnit4::class) @ExperimentalCoroutinesApi class OCCapabilityViewModelTest { private lateinit var ocCapabilityViewModel: OCCapabilityViewModel diff --git a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModelTest.kt b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModelTest.kt index 80d04d95174..990c0cce9c2 100644 --- a/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModelTest.kt +++ b/owncloudApp/src/test/java/com/owncloud/android/presentation/viewmodels/sharing/OCShareViewModelTest.kt @@ -37,7 +37,6 @@ import com.owncloud.android.presentation.UIResult import com.owncloud.android.providers.CoroutinesDispatcherProvider import com.owncloud.android.testutil.OC_ACCOUNT_NAME import com.owncloud.android.testutil.OC_SHARE -import com.owncloud.android.testutil.livedata.TIMEOUT_TEST_LONG import com.owncloud.android.testutil.livedata.getEmittedValues import com.owncloud.android.testutil.livedata.getLastEmittedValue import io.mockk.coEvery @@ -56,11 +55,8 @@ import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -import org.junit.runners.JUnit4 @ExperimentalCoroutinesApi -@RunWith(JUnit4::class) class OCShareViewModelTest { private lateinit var ocShareViewModel: OCShareViewModel @@ -175,7 +171,7 @@ class OCShareViewModelTest { } assertEquals(expectedValues, emittedValues) - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { createPrivateShareAsyncUseCase.execute(any()) } + coVerify(exactly = 1) { createPrivateShareAsyncUseCase.execute(any()) } coVerify(exactly = 0) { createPublicShareAsyncUseCase.execute(any()) } } @@ -191,7 +187,7 @@ class OCShareViewModelTest { } assertEquals(Event(UIResult.Success(OC_SHARE)), emittedValues) - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { getShareAsLiveDataUseCase.execute(any()) } + coVerify(exactly = 1) { getShareAsLiveDataUseCase.execute(any()) } } @Test @@ -228,9 +224,9 @@ class OCShareViewModelTest { val emittedValues = ocShareViewModel.privateShareEditionStatus.getEmittedValues(expectedValues.size) { testCoroutineDispatcher.resumeDispatcher() } - assertEquals(expectedValues, emittedValues ) + assertEquals(expectedValues, emittedValues) - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { editPrivateShareAsyncUseCase.execute(any()) } + coVerify(exactly = 1) { editPrivateShareAsyncUseCase.execute(any()) } coVerify(exactly = 0) { editPublicShareAsyncUseCase.execute(any()) } } @@ -279,7 +275,7 @@ class OCShareViewModelTest { assertEquals(expectedValues, emittedValues) coVerify(exactly = 0) { createPrivateShareAsyncUseCase.execute(any()) } - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { createPublicShareAsyncUseCase.execute(any()) } + coVerify(exactly = 1) { createPublicShareAsyncUseCase.execute(any()) } } @Test @@ -323,7 +319,7 @@ class OCShareViewModelTest { assertEquals(expectedValues, emittedValues) coVerify(exactly = 0) { editPrivateShareAsyncUseCase.execute(any()) } - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { editPublicShareAsyncUseCase.execute(any()) } + coVerify(exactly = 1) { editPublicShareAsyncUseCase.execute(any()) } } /****************************************************************************************************** @@ -363,7 +359,7 @@ class OCShareViewModelTest { assertEquals(expectedValues, emittedValues) - coVerify(exactly = 1, timeout = TIMEOUT_TEST_LONG) { + coVerify(exactly = 1) { deletePublicShareAsyncUseCase.execute(any()) } } diff --git a/owncloudData/build.gradle b/owncloudData/build.gradle index 6a4dd7f34e3..21bbcde732b 100644 --- a/owncloudData/build.gradle +++ b/owncloudData/build.gradle @@ -9,11 +9,11 @@ allOpen { } android { - compileSdkVersion 28 + compileSdkVersion sdkCompileVersion defaultConfig { - minSdkVersion 19 - targetSdkVersion 28 + minSdkVersion sdkMinVersion + targetSdkVersion sdkTargetVersion versionCode 1 versionName "1.0" diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt index baa02f8b249..05bdbcd858b 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt @@ -26,7 +26,6 @@ import androidx.room.Room import androidx.room.testing.MigrationTestHelper import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory import androidx.test.core.app.ApplicationProvider -import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME @@ -42,10 +41,8 @@ import com.owncloud.android.testutil.OC_CAPABILITY import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith import java.io.IOException -@RunWith(AndroidJUnit4::class) @SmallTest class MigrationTest { @@ -125,9 +122,18 @@ class MigrationTest { assertEquals(null, filesSharingSearchMinLength) assertEquals(OC_CAPABILITY.filesSharingPublicEnabled.value, filesSharingPublicEnabled) assertEquals(OC_CAPABILITY.filesSharingPublicPasswordEnforced.value, filesSharingPublicPasswordEnforced) - assertEquals(OC_CAPABILITY.filesSharingPublicPasswordEnforcedReadOnly.value, filesSharingPublicPasswordEnforcedReadOnly) - assertEquals(OC_CAPABILITY.filesSharingPublicPasswordEnforcedReadWrite.value, filesSharingPublicPasswordEnforcedReadWrite) - assertEquals(OC_CAPABILITY.filesSharingPublicPasswordEnforcedUploadOnly.value, filesSharingPublicPasswordEnforcedUploadOnly) + assertEquals( + OC_CAPABILITY.filesSharingPublicPasswordEnforcedReadOnly.value, + filesSharingPublicPasswordEnforcedReadOnly + ) + assertEquals( + OC_CAPABILITY.filesSharingPublicPasswordEnforcedReadWrite.value, + filesSharingPublicPasswordEnforcedReadWrite + ) + assertEquals( + OC_CAPABILITY.filesSharingPublicPasswordEnforcedUploadOnly.value, + filesSharingPublicPasswordEnforcedUploadOnly + ) assertEquals(OC_CAPABILITY.filesSharingPublicExpireDateEnabled.value, filesSharingPublicExpireDateEnabled) assertEquals(OC_CAPABILITY.filesSharingPublicExpireDateDays, filesSharingPublicExpireDateDays) assertEquals(OC_CAPABILITY.filesSharingPublicExpireDateEnforced.value, filesSharingPublicExpireDateEnforced) diff --git a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt index 46c2fa57acf..5f271190aec 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/capabilities/repository/OCCapabilityRepositoryTest.kt @@ -34,10 +34,7 @@ import io.mockk.verify import org.junit.Assert import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -import org.junit.runners.JUnit4 -@RunWith(JUnit4::class) class OCCapabilityRepositoryTest { @Rule @JvmField diff --git a/owncloudData/src/test/java/com/owncloud/android/data/sharees/repository/OCShareeRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/sharees/repository/OCShareeRepositoryTest.kt index 97f668c273a..870032b2779 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/sharees/repository/OCShareeRepositoryTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/sharees/repository/OCShareeRepositoryTest.kt @@ -28,10 +28,7 @@ import io.mockk.mockk import io.mockk.verify import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -import org.junit.runners.JUnit4 -@RunWith(JUnit4::class) class OCShareeRepositoryTest { @Rule @JvmField diff --git a/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt b/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt index df7d739d72a..f1e393b9cdc 100644 --- a/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt +++ b/owncloudData/src/test/java/com/owncloud/android/data/shares/repository/OCShareRepositoryTest.kt @@ -36,10 +36,7 @@ import io.mockk.verify import org.junit.Assert import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith -import org.junit.runners.JUnit4 -@RunWith(JUnit4::class) class OCShareRepositoryTest { @Rule @JvmField diff --git a/owncloudDomain/build.gradle b/owncloudDomain/build.gradle index c2c75d9fefb..3c959b2fa20 100644 --- a/owncloudDomain/build.gradle +++ b/owncloudDomain/build.gradle @@ -9,11 +9,11 @@ allOpen { } android { - compileSdkVersion 28 + compileSdkVersion sdkCompileVersion defaultConfig { - minSdkVersion 19 - targetSdkVersion 28 + minSdkVersion sdkMinVersion + targetSdkVersion sdkTargetVersion versionCode 1 versionName "1.0" diff --git a/owncloudTestUtil/build.gradle b/owncloudTestUtil/build.gradle index f3222dcc8b7..d0793bc20df 100644 --- a/owncloudTestUtil/build.gradle +++ b/owncloudTestUtil/build.gradle @@ -2,11 +2,11 @@ apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { - compileSdkVersion 28 + compileSdkVersion sdkCompileVersion defaultConfig { - minSdkVersion 19 - targetSdkVersion 28 + minSdkVersion sdkMinVersion + targetSdkVersion sdkTargetVersion } buildTypes { @@ -21,5 +21,5 @@ dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation project(':owncloudDomain') implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" - implementation "androidx.lifecycle:lifecycle-livedata:2.0.0" + implementation "androidx.lifecycle:lifecycle-livedata:$lifecycleLiveData" } diff --git a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/TestTimeOutConstants.kt b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/TestTimeOutConstants.kt index 7fa0077ac73..f414ea299bd 100644 --- a/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/TestTimeOutConstants.kt +++ b/owncloudTestUtil/src/main/java/com/owncloud/android/testutil/livedata/TestTimeOutConstants.kt @@ -19,5 +19,4 @@ package com.owncloud.android.testutil.livedata -const val TIMEOUT_TEST_LONG = 5_000L -const val TIMEOUT_TEST_SHORT = 2_000L \ No newline at end of file +const val TIMEOUT_TEST_SHORT = 2_000L From 62b6ec64ae832ba71ba956ffc08a979eee532611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abel=20Garc=C3=ADa=20de=20Prada?= Date: Wed, 4 Dec 2019 11:22:19 +0100 Subject: [PATCH 41/41] Rename migration test --- owncloud-android-library | 2 +- .../{MigrationTest.kt => roommigrations/MigrationToDB28.kt} | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) rename owncloudData/src/androidTest/java/com/owncloud/android/data/{MigrationTest.kt => roommigrations/MigrationToDB28.kt} (98%) diff --git a/owncloud-android-library b/owncloud-android-library index 78d6ca08e23..ce65bc97e42 160000 --- a/owncloud-android-library +++ b/owncloud-android-library @@ -1 +1 @@ -Subproject commit 78d6ca08e233de74413f6a8643c441ec0896be42 +Subproject commit ce65bc97e4279bf4d45c4daaa5b8cbc7f5901a07 diff --git a/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB28.kt similarity index 98% rename from owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt rename to owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB28.kt index 05bdbcd858b..25933fb8650 100644 --- a/owncloudData/src/androidTest/java/com/owncloud/android/data/MigrationTest.kt +++ b/owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB28.kt @@ -18,7 +18,7 @@ * */ -package com.owncloud.android.data +package com.owncloud.android.data.roommigrations import android.content.ContentValues import android.database.sqlite.SQLiteDatabase @@ -28,6 +28,7 @@ import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory import androidx.test.core.app.ApplicationProvider import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry +import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS @@ -44,7 +45,7 @@ import org.junit.Test import java.io.IOException @SmallTest -class MigrationTest { +class MigrationToDB28 { @Rule @JvmField