From df1b032dd13de621403735e151999ca839a7d43c Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 1 Apr 2021 17:57:08 +0200 Subject: [PATCH 01/60] start to add dependencies into build.gradle and add base for Service's test --- .idea/modules.xml | 11 ----------- app/build.gradle | 15 ++++++++++++++- .../test/java/foundation/e/drive/Test/doTest.java | 4 ---- .../e/drive/services/InitializerServiceTest.java | 8 ++++++++ .../e/drive/services/ObserverServiceTest.java | 10 ++++++++++ .../services/OperationManagerServiceTest.java | 8 ++++++++ .../e/drive/services/ResetServiceTest.java | 8 ++++++++ .../{Test => unitTest}/CommonUtilsUnitTest.java | 2 +- .../FileFilterTest/CrashlogFileFilterTest.java | 2 +- .../FileFilterTest/FileFilterUnitTest.java | 2 +- .../e/drive/{Test => unitTest}/MD5Test.java | 2 +- .../ObserverServiceUnitTest.java | 2 +- .../{Test => unitTest}/SyncedFolderUnitTest.java | 2 +- .../java/foundation/e/drive/unitTest/doTest.java | 4 ++++ .../mockObject/mockContext.java | 2 +- .../mockObject/mockRemoteFile.java | 2 +- .../{Test => unitTest}/mockObject/mockSfs.java | 2 +- 17 files changed, 61 insertions(+), 25 deletions(-) delete mode 100644 .idea/modules.xml delete mode 100644 app/src/test/java/foundation/e/drive/Test/doTest.java create mode 100644 app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java create mode 100644 app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java create mode 100644 app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java create mode 100644 app/src/test/java/foundation/e/drive/services/ResetServiceTest.java rename app/src/test/java/foundation/e/drive/{Test => unitTest}/CommonUtilsUnitTest.java (98%) rename app/src/test/java/foundation/e/drive/{Test => unitTest}/FileFilterTest/CrashlogFileFilterTest.java (97%) rename app/src/test/java/foundation/e/drive/{Test => unitTest}/FileFilterTest/FileFilterUnitTest.java (97%) rename app/src/test/java/foundation/e/drive/{Test => unitTest}/MD5Test.java (98%) rename app/src/test/java/foundation/e/drive/{Test => unitTest}/ObserverServiceUnitTest.java (98%) rename app/src/test/java/foundation/e/drive/{Test => unitTest}/SyncedFolderUnitTest.java (97%) create mode 100644 app/src/test/java/foundation/e/drive/unitTest/doTest.java rename app/src/test/java/foundation/e/drive/{Test => unitTest}/mockObject/mockContext.java (99%) rename app/src/test/java/foundation/e/drive/{Test => unitTest}/mockObject/mockRemoteFile.java (75%) rename app/src/test/java/foundation/e/drive/{Test => unitTest}/mockObject/mockSfs.java (72%) diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 73f2520e..00000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index 5b312b6a..7bd5d3f6 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -19,6 +19,8 @@ android { //versionName "1.0" versionName "beta-${versionMajor}-build-o-${buildTime()}" setProperty("archivesBaseName", "$applicationId.$versionName") + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + testBuildType System.getProperty('testBuildType', 'debug') } buildTypes { @@ -42,11 +44,22 @@ android { dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:26.1.0' - testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test:rules:1.0.2' androidTestImplementation 'com.android.support:support-annotations:27.1.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' api 'com.android.support:support-annotations:27.1.1' api project(':NextcloudLib') + + //start to add lib for test - 1/4/21 + //@TODO: add junit runner as lib for testImplementation + + testImplementation 'junit:junit:4.12' + testImplementation 'org.robolectric:robolectric:4.4' + testImplementation "org.mockito:mockito-core:2.19.0" + //testImplementation Libs.AndroidX.Test.archCoreTesting //TODO: replace by not android X version + implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0' + androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' + androidTestImplementation 'junit:junit:4.12' } diff --git a/app/src/test/java/foundation/e/drive/Test/doTest.java b/app/src/test/java/foundation/e/drive/Test/doTest.java deleted file mode 100644 index b1aa1589..00000000 --- a/app/src/test/java/foundation/e/drive/Test/doTest.java +++ /dev/null @@ -1,4 +0,0 @@ -package foundation.e.drive.Test; - -public class doTest { -} diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java new file mode 100644 index 00000000..dbd3d5f4 --- /dev/null +++ b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java @@ -0,0 +1,8 @@ +package foundation.e.drive.services; +import org.junit.runner.RunWith; +import org.junit.Rule; + +@RunWith(AndroidJUnit4ClassRunner.class) +public class InitializerServiceTest { + +} diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java new file mode 100644 index 00000000..14830061 --- /dev/null +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -0,0 +1,10 @@ +package foundation.e.drive.services; +import org.junit.runner.RunWith; +import org.junit.Rule; + + + +@RunWith(AndroidJUnit4ClassRunner.class) +public class ObserverServiceTest { + +} diff --git a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java new file mode 100644 index 00000000..993948d4 --- /dev/null +++ b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java @@ -0,0 +1,8 @@ +package foundation.e.drive.services; +import org.junit.runner.RunWith; +import org.junit.Rule; + + +@RunWith(AndroidJUnit4ClassRunner.class) +public class OperationManagerServiceTest { +} diff --git a/app/src/test/java/foundation/e/drive/services/ResetServiceTest.java b/app/src/test/java/foundation/e/drive/services/ResetServiceTest.java new file mode 100644 index 00000000..78358f43 --- /dev/null +++ b/app/src/test/java/foundation/e/drive/services/ResetServiceTest.java @@ -0,0 +1,8 @@ +package foundation.e.drive.services; +import org.junit.runner.RunWith; +import org.junit.Rule; + + +@RunWith(AndroidJUnit4ClassRunner.class) +public class ResetServiceTest { +} diff --git a/app/src/test/java/foundation/e/drive/Test/CommonUtilsUnitTest.java b/app/src/test/java/foundation/e/drive/unitTest/CommonUtilsUnitTest.java similarity index 98% rename from app/src/test/java/foundation/e/drive/Test/CommonUtilsUnitTest.java rename to app/src/test/java/foundation/e/drive/unitTest/CommonUtilsUnitTest.java index e76ac1e6..47154b43 100644 --- a/app/src/test/java/foundation/e/drive/Test/CommonUtilsUnitTest.java +++ b/app/src/test/java/foundation/e/drive/unitTest/CommonUtilsUnitTest.java @@ -5,7 +5,7 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ -package foundation.e.drive.Test; +package foundation.e.drive.unitTest; import android.accounts.Account; import org.junit.Assert; diff --git a/app/src/test/java/foundation/e/drive/Test/FileFilterTest/CrashlogFileFilterTest.java b/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/CrashlogFileFilterTest.java similarity index 97% rename from app/src/test/java/foundation/e/drive/Test/FileFilterTest/CrashlogFileFilterTest.java rename to app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/CrashlogFileFilterTest.java index 69950012..31b262ea 100644 --- a/app/src/test/java/foundation/e/drive/Test/FileFilterTest/CrashlogFileFilterTest.java +++ b/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/CrashlogFileFilterTest.java @@ -1,4 +1,4 @@ -package foundation.e.drive.Test.FileFilterTest; +package foundation.e.drive.unitTest.FileFilterTest; import org.junit.Assert; import org.junit.Test; diff --git a/app/src/test/java/foundation/e/drive/Test/FileFilterTest/FileFilterUnitTest.java b/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/FileFilterUnitTest.java similarity index 97% rename from app/src/test/java/foundation/e/drive/Test/FileFilterTest/FileFilterUnitTest.java rename to app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/FileFilterUnitTest.java index 6d3d3051..7607f0c4 100644 --- a/app/src/test/java/foundation/e/drive/Test/FileFilterTest/FileFilterUnitTest.java +++ b/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/FileFilterUnitTest.java @@ -7,7 +7,7 @@ */ -package foundation.e.drive.Test.FileFilterTest; +package foundation.e.drive.unitTest.FileFilterTest; import junit.framework.Assert; diff --git a/app/src/test/java/foundation/e/drive/Test/MD5Test.java b/app/src/test/java/foundation/e/drive/unitTest/MD5Test.java similarity index 98% rename from app/src/test/java/foundation/e/drive/Test/MD5Test.java rename to app/src/test/java/foundation/e/drive/unitTest/MD5Test.java index c68da4cf..2698b840 100644 --- a/app/src/test/java/foundation/e/drive/Test/MD5Test.java +++ b/app/src/test/java/foundation/e/drive/unitTest/MD5Test.java @@ -1,4 +1,4 @@ -package foundation.e.drive.Test; +package foundation.e.drive.unitTest; /* diff --git a/app/src/test/java/foundation/e/drive/Test/ObserverServiceUnitTest.java b/app/src/test/java/foundation/e/drive/unitTest/ObserverServiceUnitTest.java similarity index 98% rename from app/src/test/java/foundation/e/drive/Test/ObserverServiceUnitTest.java rename to app/src/test/java/foundation/e/drive/unitTest/ObserverServiceUnitTest.java index e96d7403..adc97d7b 100644 --- a/app/src/test/java/foundation/e/drive/Test/ObserverServiceUnitTest.java +++ b/app/src/test/java/foundation/e/drive/unitTest/ObserverServiceUnitTest.java @@ -5,7 +5,7 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ -package foundation.e.drive.Test; +package foundation.e.drive.unitTest; import org.junit.Assert; import org.junit.Test; diff --git a/app/src/test/java/foundation/e/drive/Test/SyncedFolderUnitTest.java b/app/src/test/java/foundation/e/drive/unitTest/SyncedFolderUnitTest.java similarity index 97% rename from app/src/test/java/foundation/e/drive/Test/SyncedFolderUnitTest.java rename to app/src/test/java/foundation/e/drive/unitTest/SyncedFolderUnitTest.java index d56228ec..baecb8f4 100644 --- a/app/src/test/java/foundation/e/drive/Test/SyncedFolderUnitTest.java +++ b/app/src/test/java/foundation/e/drive/unitTest/SyncedFolderUnitTest.java @@ -5,7 +5,7 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ -package foundation.e.drive.Test; +package foundation.e.drive.unitTest; import junit.framework.Assert; diff --git a/app/src/test/java/foundation/e/drive/unitTest/doTest.java b/app/src/test/java/foundation/e/drive/unitTest/doTest.java new file mode 100644 index 00000000..cd8bfd27 --- /dev/null +++ b/app/src/test/java/foundation/e/drive/unitTest/doTest.java @@ -0,0 +1,4 @@ +package foundation.e.drive.unitTest; + +public class doTest { +} diff --git a/app/src/test/java/foundation/e/drive/Test/mockObject/mockContext.java b/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockContext.java similarity index 99% rename from app/src/test/java/foundation/e/drive/Test/mockObject/mockContext.java rename to app/src/test/java/foundation/e/drive/unitTest/mockObject/mockContext.java index 9e782f6c..1125e35e 100644 --- a/app/src/test/java/foundation/e/drive/Test/mockObject/mockContext.java +++ b/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockContext.java @@ -1,4 +1,4 @@ -package foundation.e.drive.Test.mockObject; +package foundation.e.drive.unitTest.mockObject; import android.content.BroadcastReceiver; import android.content.ComponentName; diff --git a/app/src/test/java/foundation/e/drive/Test/mockObject/mockRemoteFile.java b/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockRemoteFile.java similarity index 75% rename from app/src/test/java/foundation/e/drive/Test/mockObject/mockRemoteFile.java rename to app/src/test/java/foundation/e/drive/unitTest/mockObject/mockRemoteFile.java index fcdedb31..94df626d 100644 --- a/app/src/test/java/foundation/e/drive/Test/mockObject/mockRemoteFile.java +++ b/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockRemoteFile.java @@ -1,4 +1,4 @@ -package foundation.e.drive.Test.mockObject; +package foundation.e.drive.unitTest.mockObject; import com.owncloud.android.lib.resources.files.model.RemoteFile; diff --git a/app/src/test/java/foundation/e/drive/Test/mockObject/mockSfs.java b/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockSfs.java similarity index 72% rename from app/src/test/java/foundation/e/drive/Test/mockObject/mockSfs.java rename to app/src/test/java/foundation/e/drive/unitTest/mockObject/mockSfs.java index 01d69d08..5e58d68c 100644 --- a/app/src/test/java/foundation/e/drive/Test/mockObject/mockSfs.java +++ b/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockSfs.java @@ -1,4 +1,4 @@ -package foundation.e.drive.Test.mockObject; +package foundation.e.drive.unitTest.mockObject; import foundation.e.drive.models.SyncedFileState; -- GitLab From 6e2413c594874a3569386dc5997e1fc00c4f13a2 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 2 Apr 2021 11:16:15 +0200 Subject: [PATCH 02/60] move base class from test folder to androidtest folder --- app/build.gradle | 3 ++- .../services/InitializerServiceTest.java | 19 +++++++++++++++++ .../e/drive/services/ObserverServiceTest.java | 21 +++++++++++++++++++ .../services/OperationManagerServiceTest.java | 21 +++++++++++++++++++ .../e/drive/services/ResetServiceTest.java | 21 +++++++++++++++++++ .../services/InitializerServiceTest.java | 8 ------- .../e/drive/services/ObserverServiceTest.java | 10 --------- .../services/OperationManagerServiceTest.java | 8 ------- .../e/drive/services/ResetServiceTest.java | 8 ------- 9 files changed, 84 insertions(+), 35 deletions(-) create mode 100644 app/src/androidTest/java/foundation/e/drive/services/InitializerServiceTest.java create mode 100644 app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java create mode 100644 app/src/androidTest/java/foundation/e/drive/services/OperationManagerServiceTest.java create mode 100644 app/src/androidTest/java/foundation/e/drive/services/ResetServiceTest.java delete mode 100644 app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java delete mode 100644 app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java delete mode 100644 app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java delete mode 100644 app/src/test/java/foundation/e/drive/services/ResetServiceTest.java diff --git a/app/build.gradle b/app/build.gradle index 7bd5d3f6..db495fa0 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -55,11 +55,12 @@ dependencies { //start to add lib for test - 1/4/21 //@TODO: add junit runner as lib for testImplementation + testImplementation 'com.android.support.test:runner:1.0.2' + testImplementation 'com.android.support.test:rules:1.0.2' testImplementation 'junit:junit:4.12' testImplementation 'org.robolectric:robolectric:4.4' testImplementation "org.mockito:mockito-core:2.19.0" //testImplementation Libs.AndroidX.Test.archCoreTesting //TODO: replace by not android X version implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0' - androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' androidTestImplementation 'junit:junit:4.12' } diff --git a/app/src/androidTest/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/InitializerServiceTest.java new file mode 100644 index 00000000..b3afefde --- /dev/null +++ b/app/src/androidTest/java/foundation/e/drive/services/InitializerServiceTest.java @@ -0,0 +1,19 @@ +package foundation.e.drive.services; +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class InitializerServiceTest { +} diff --git a/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java new file mode 100644 index 00000000..d6cb9c7a --- /dev/null +++ b/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java @@ -0,0 +1,21 @@ +package foundation.e.drive.services; +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + + + + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ObserverServiceTest { +} diff --git a/app/src/androidTest/java/foundation/e/drive/services/OperationManagerServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/OperationManagerServiceTest.java new file mode 100644 index 00000000..b8d2562e --- /dev/null +++ b/app/src/androidTest/java/foundation/e/drive/services/OperationManagerServiceTest.java @@ -0,0 +1,21 @@ +package foundation.e.drive.services; +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + + + + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class OperationManagerServiceTest { +} diff --git a/app/src/androidTest/java/foundation/e/drive/services/ResetServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/ResetServiceTest.java new file mode 100644 index 00000000..dd84488f --- /dev/null +++ b/app/src/androidTest/java/foundation/e/drive/services/ResetServiceTest.java @@ -0,0 +1,21 @@ +package foundation.e.drive.services; +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + + + + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ResetServiceTest { +} diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java deleted file mode 100644 index dbd3d5f4..00000000 --- a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java +++ /dev/null @@ -1,8 +0,0 @@ -package foundation.e.drive.services; -import org.junit.runner.RunWith; -import org.junit.Rule; - -@RunWith(AndroidJUnit4ClassRunner.class) -public class InitializerServiceTest { - -} diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java deleted file mode 100644 index 14830061..00000000 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ /dev/null @@ -1,10 +0,0 @@ -package foundation.e.drive.services; -import org.junit.runner.RunWith; -import org.junit.Rule; - - - -@RunWith(AndroidJUnit4ClassRunner.class) -public class ObserverServiceTest { - -} diff --git a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java deleted file mode 100644 index 993948d4..00000000 --- a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java +++ /dev/null @@ -1,8 +0,0 @@ -package foundation.e.drive.services; -import org.junit.runner.RunWith; -import org.junit.Rule; - - -@RunWith(AndroidJUnit4ClassRunner.class) -public class OperationManagerServiceTest { -} diff --git a/app/src/test/java/foundation/e/drive/services/ResetServiceTest.java b/app/src/test/java/foundation/e/drive/services/ResetServiceTest.java deleted file mode 100644 index 78358f43..00000000 --- a/app/src/test/java/foundation/e/drive/services/ResetServiceTest.java +++ /dev/null @@ -1,8 +0,0 @@ -package foundation.e.drive.services; -import org.junit.runner.RunWith; -import org.junit.Rule; - - -@RunWith(AndroidJUnit4ClassRunner.class) -public class ResetServiceTest { -} -- GitLab From d2fc351910207d828133a095adacbcc4c6bd0b23 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 2 Apr 2021 12:09:16 +0200 Subject: [PATCH 03/60] try to use ServiceTestRule --- .../e/drive/services/ObserverServiceTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java index d6cb9c7a..b765d2a2 100644 --- a/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java @@ -1,8 +1,11 @@ package foundation.e.drive.services; + import android.content.Context; import android.support.test.InstrumentationRegistry; +import android.support.test.rule.ServiceTestRule; import android.support.test.runner.AndroidJUnit4; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,4 +21,17 @@ import static org.junit.Assert.*; */ @RunWith(AndroidJUnit4.class) public class ObserverServiceTest { + + @Rule + public ServiceTestRule mObserverServiceTestRule = + new ServiceTestRule(ObserverService.class); + + @Test + public void useAppContext() throws Exception { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + + assertEquals("foundation.e.drive", appContext.getPackageName()); + } } -- GitLab From cf33c28cd802442bcfab945917facca52ad9889f Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Tue, 6 Apr 2021 11:49:05 +0200 Subject: [PATCH 04/60] add @before & @after method base --- .../e/drive/services/ObserverServiceTest.java | 67 ++++++++++++++++++- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java index b765d2a2..1726870c 100644 --- a/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java @@ -1,14 +1,28 @@ package foundation.e.drive.services; +import android.accounts.Account; +import android.accounts.AccountManager; +import android.app.Service; import android.content.Context; +import android.content.Intent; +import android.os.Environment; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ServiceTestRule; import android.support.test.runner.AndroidJUnit4; +import org.junit.After; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.concurrent.TimeoutException; + +import static android.support.test.InstrumentationRegistry.getContext; import static org.junit.Assert.*; @@ -21,10 +35,59 @@ import static org.junit.Assert.*; */ @RunWith(AndroidJUnit4.class) public class ObserverServiceTest { + private final static String NEW_SMALL_FILE_PATH = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DOCUMENTS+File.separator+"test-small-file.txt"; + private final static String ACCOUNT_NAME= ""; + private final static String ACCOUNT_PASS=""; + private final static String ACCOUNT_TYPE=""; + @Rule - public ServiceTestRule mObserverServiceTestRule = - new ServiceTestRule(ObserverService.class); + public final ServiceTestRule mServiceRule = new ServiceTestRule(); + + + @Before + public void RegisterAccount() throws Exception { + final Account account = new Account(ACCOUNT_NAME, ACCOUNT_TYPE); + AccountManager.get(getContext()).addAccountExplicitly(account, ACCOUNT_PASS, null); + + } + + + /** + * Souldn't it be more for a unit test ? + * @throws IOException + */ + @Before + public void createLocalSmallFile() throws IOException { + + File file = new File(NEW_SMALL_FILE_PATH); + file.createNewFile(); + String content = "this a very small content"; +//write the bytes in file + if(file.exists()) + { + OutputStream fo = new FileOutputStream(file); + fo.write(content.getBytes()); + fo.close(); + System.out.println("file created: "+file); + } + } + + + @After + public void deleteLocalSmallFile(){ + File file = new File(NEW_SMALL_FILE_PATH); + //deleting the file + file.delete(); + } + + + @Test + public void testWithStartedService() throws TimeoutException { + mServiceRule.startService( + new Intent(InstrumentationRegistry.getTargetContext(), ObserverService.class)); + //do something + } @Test public void useAppContext() throws Exception { -- GitLab From 28bf28ae6200472b55f03fc58fdafec15e138c77 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Tue, 6 Apr 2021 18:31:24 +0200 Subject: [PATCH 05/60] add a AbstractIT class for integration test like in the NC app --- .../java/foundation/e/drive/AbstractIT.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 app/src/test/java/foundation/e/drive/AbstractIT.java diff --git a/app/src/test/java/foundation/e/drive/AbstractIT.java b/app/src/test/java/foundation/e/drive/AbstractIT.java new file mode 100644 index 00000000..1c9956ad --- /dev/null +++ b/app/src/test/java/foundation/e/drive/AbstractIT.java @@ -0,0 +1,43 @@ +package foundation.e.drive; + +import android.accounts.Account; +import android.content.Context; + +import com.owncloud.android.lib.common.OwnCloudClient; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +import static org.junit.Assert.assertTrue; + +/** + * This class contains common method for integration Test + * This is inspired by Nextcloud's android app's test + */ +public class AbstractIT { + protected static OwnCloudClient client; + protected static Account account; + protected static Context targetContext; + + + public static File createFile(String name, int iteration) throws IOException { + String folder = "";//@TODO fix this + File file = new File(folder + File.separator + name); + if (!file.getParentFile().exists()) { + assertTrue(file.getParentFile().mkdirs()); + } + + file.createNewFile(); + + FileWriter writer = new FileWriter(file); + + for (int i = 0; i < iteration; i++) { + writer.write("123123123123123123123123123\n"); + } + writer.flush(); + writer.close(); + + return file; + } +} -- GitLab From 1874ce6577088e2f98fa9ae44f1a8053a3c4021e Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 12 Apr 2021 15:55:50 +0200 Subject: [PATCH 06/60] work on test implementation --- .../java/foundation/e/drive/AbstractIT.java | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 app/src/androidTest/java/foundation/e/drive/AbstractIT.java diff --git a/app/src/androidTest/java/foundation/e/drive/AbstractIT.java b/app/src/androidTest/java/foundation/e/drive/AbstractIT.java new file mode 100644 index 00000000..8b4cf2dd --- /dev/null +++ b/app/src/androidTest/java/foundation/e/drive/AbstractIT.java @@ -0,0 +1,116 @@ +package foundation.e.drive; + + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.app.Service; +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.rule.GrantPermissionRule; +import android.Manifest; +import com.owncloud.android.lib.common.OwnCloudClient; +import com.owncloud.android.lib.resources.files.FileUtils; + +import org.junit.BeforeClass; +import org.junit.Rule; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; + +import static android.support.test.InstrumentationRegistry.getInstrumentation; +import static junit.framework.TestCase.assertTrue; + +/** + * Common base for all integration tests + * Inspired by NC's android application's test + */ +public class AbstractIT { + @Rule + public final GrantPermissionRule permissionRule = GrantPermissionRule.grant( + Manifest.permission.WRITE_EXTERNAL_STORAGE); + + protected static OwnCloudClient client; + protected static Account account; + protected static Context targetContext; + + + protected Service currentService; + + @BeforeClass + public static void beforeAll() { + + } + + protected Account[] getAllAccounts() { + return AccountManager.get(targetContext).getAccounts(); + } + + protected static void createDummyFiles() throws IOException { + File tempPath = new File(FileStorageUtils.getTemporalPath(account.name)); + if (!tempPath.exists()) { + assertTrue(tempPath.mkdirs()); + } + + assertTrue(tempPath.exists()); + + createFile("empty.txt", 0); + createFile("nonEmpty.txt", 100); + createFile("chunkedFile.txt", 500000); + } + + public static File createFile(String name, int iteration) throws IOException { + File file = new File(FileStorageUtils.getTemporalPath(account.name) + File.separator + name); + if (!file.getParentFile().exists()) { + assertTrue(file.getParentFile().mkdirs()); + } + + file.createNewFile(); + + FileWriter writer = new FileWriter(file); + + for (int i = 0; i < iteration; i++) { + writer.write("123123123123123123123123123\n"); + } + writer.flush(); + writer.close(); + + return file; + } + + + + protected File getFile(String filename) throws IOException { + InputStream inputStream = getInstrumentation().getContext().getAssets().open(filename); + File temp = File.createTempFile("file", "file"); + //FileUtils.copyInputStreamToFile(inputStream, temp); + + return temp; + } + + + + protected void waitForIdleSync() { + InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + } + + /** Need to find a wya to make this work for service **/ + protected Service getCurrentService) { + InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { + Collection resumedServices; + /*ServiceLifecycleMonitorRegistry + .getInstance() + .getServices();*/ + //.getActivitiesInStage(Stage.RESUMED); + + if (resumedServices.iterator().hasNext()) { + currentService = resumedServices.iterator().next(); + } + }); + + return currentService; + } +} -- GitLab From f0019bc8902355e54a11d1406b4a47bb3c31f036 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 12 Apr 2021 15:57:11 +0200 Subject: [PATCH 07/60] update gradle version --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 88560b47..3378f0cd 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:3.1.3' + classpath 'com.android.tools.build:gradle:4.1.3' // NOTE: Do not place your application dependencies here; they belong -- GitLab From eabe5003b61b2eaa3057d3816bc6f78b93240914 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 12 Apr 2021 15:58:07 +0200 Subject: [PATCH 08/60] test imp --- app/src/test/java/foundation/e/drive/AbstractIT.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/AbstractIT.java b/app/src/test/java/foundation/e/drive/AbstractIT.java index 1c9956ad..7cd0cbfd 100644 --- a/app/src/test/java/foundation/e/drive/AbstractIT.java +++ b/app/src/test/java/foundation/e/drive/AbstractIT.java @@ -3,7 +3,7 @@ package foundation.e.drive; import android.accounts.Account; import android.content.Context; -import com.owncloud.android.lib.common.OwnCloudClient; +//import com.owncloud.android.lib.common.OwnCloudClient; import java.io.File; import java.io.FileWriter; @@ -16,7 +16,7 @@ import static org.junit.Assert.assertTrue; * This is inspired by Nextcloud's android app's test */ public class AbstractIT { - protected static OwnCloudClient client; + //protected static OwnCloudClient client; protected static Account account; protected static Context targetContext; -- GitLab From 8ee18341f0fd89193cf46da0cb52463128109577 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Tue, 13 Apr 2021 12:28:28 +0200 Subject: [PATCH 09/60] add Base for ObserverService Test --- app/build.gradle | 5 +- .../services/InitializerServiceUnitTest.java | 35 +++++++ .../e/drive/services/ObserverServiceTest.java | 91 +++++++++++++++++++ 3 files changed, 129 insertions(+), 2 deletions(-) create mode 100644 app/src/test/java/foundation/e/drive/services/InitializerServiceUnitTest.java create mode 100644 app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java diff --git a/app/build.gradle b/app/build.gradle index db495fa0..3c841042 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -58,9 +58,10 @@ dependencies { testImplementation 'com.android.support.test:runner:1.0.2' testImplementation 'com.android.support.test:rules:1.0.2' testImplementation 'junit:junit:4.12' - testImplementation 'org.robolectric:robolectric:4.4' + //testImplementation 'org.robolectric:robolectric:4.4' //need AndroidX + testCompile "org.robolectric:robolectric:3.1" testImplementation "org.mockito:mockito-core:2.19.0" //testImplementation Libs.AndroidX.Test.archCoreTesting //TODO: replace by not android X version - implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0' + //implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0' androidTestImplementation 'junit:junit:4.12' } diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceUnitTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceUnitTest.java new file mode 100644 index 00000000..48dc732c --- /dev/null +++ b/app/src/test/java/foundation/e/drive/services/InitializerServiceUnitTest.java @@ -0,0 +1,35 @@ +package foundation.e.drive.services; + +import android.accounts.AccountManager; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; + +import org.junit.Test; +import org.mockito.Mockito; + +import foundation.e.drive.utils.AppConstants; + +public class InitializerServiceUnitTest { + private final static String TEST_ACCOUNT_TYPE =""; + private final static String TEST_ACCOUNT_NAME=""; + + @Test + public void onStartCommand() { + final Intent intent = Mockito.mock(Intent.class); + final SharedPreferences sharedPrefs = Mockito.mock(SharedPreferences.class); + final Context context = Mockito.mock(Context.class); + + + Mockito.when(context.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE)).thenReturn(sharedPrefs); + + Mockito.when(sharedPrefs.getBoolean(AppConstants.INITIALIZATION_HAS_BEEN_DONE, false)).thenReturn(false); + Mockito.when(sharedPrefs.getString(AccountManager.KEY_ACCOUNT_NAME, "" )).thenReturn(TEST_ACCOUNT_NAME); + Mockito.when(sharedPrefs.getString(AccountManager.KEY_ACCOUNT_TYPE, "" )).thenReturn(TEST_ACCOUNT_TYPE); + } + + + @Test + public void onRemoteOperationFinish() { + } +} diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java new file mode 100644 index 00000000..986a136d --- /dev/null +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -0,0 +1,91 @@ +package foundation.e.drive.services; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.support.test.runner.AndroidJUnit4; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; + +import org.robolectric.Robolectric; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.util.ServiceController; + +import foundation.e.drive.utils.AppConstants; +import foundation.e.drive.utils.CommonUtils; + +import static org.junit.Assert.*; +import static org.robolectric.Shadows.shadowOf; + + +@RunWith(AndroidJUnit4.class) +public class ObserverServiceTest { + private ObserverService myService; + private ServiceController mServiceController; + private final static String TEST_ACCOUNT_TYPE ="eelo"; + private final static String TEST_ACCOUNT_NAME="vincent"; + private final static int INITIAL_FOLDER_NUMBER=0; + private final static long LAST_SYNC_TIME=0l; + + + + private AccountManager accountManager; + + @Before + public void setUp(){ + //Note: May be the SharedPrefs part could be created with robolectric instead of mockito.. + + prepareSharedPref(); + prepareAccount(); + mServiceController = Robolectric.buildService(ObserverService.class); + + + //This where I should create the DB, prepare mock object, etc... + + + } + + private void prepareSharedPref(){ + SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences( + AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); + + sharedPreferences.edit().putBoolean( AppConstants.INITIALIZATION_HAS_BEEN_DONE, true) + .putBoolean(AppConstants.KEY_OMS_IS_WORKING, false) + .putString(AccountManager.KEY_ACCOUNT_NAME, TEST_ACCOUNT_NAME) + .putString(AccountManager.KEY_ACCOUNT_TYPE, TEST_ACCOUNT_TYPE) + .putInt(AppConstants.INITIALFOLDERS_NUMBER, 0) + .putLong(AppConstants.KEY_LAST_SYNC_TIME, 0L) + + .commit(); + } + + + private void prepareAccount(){ + accountManager = AccountManager.get(RuntimeEnvironment.application); + Account account0 = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type + shadowOf(accountManager).addAccount(account0); + } + + @Test + public void testWithIntent() { + //Intent intent = new Intent(RuntimeEnvironment.application, ObserverService.class); + mServiceController.create().startCommand(0, 0); + myService = mServiceController.get(); + + + //There is issue with "CommonUtils.setServiceUnCaughtExceptionHandler(this);" + // assert here + Assert.fail(); + + } + +} \ No newline at end of file -- GitLab From cdd00fd7a9d65d0eb3ecfeab28c89a778db1724e Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Tue, 13 Apr 2021 18:00:58 +0200 Subject: [PATCH 10/60] update test for ObserverService --- app/build.gradle | 6 +- .../e/drive/services/ObserverServiceTest.java | 106 +++++++++++++++--- 2 files changed, 92 insertions(+), 20 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 3c841042..d84d464a 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -59,8 +59,10 @@ dependencies { testImplementation 'com.android.support.test:rules:1.0.2' testImplementation 'junit:junit:4.12' //testImplementation 'org.robolectric:robolectric:4.4' //need AndroidX - testCompile "org.robolectric:robolectric:3.1" - testImplementation "org.mockito:mockito-core:2.19.0" + testCompile "org.robolectric:robolectric:3.8" + //testImplementation "org.mockito:mockito-core:2.19.0" + testImplementation('org.mockito:mockito-inline:3.4.0') + //testImplementation Libs.AndroidX.Test.archCoreTesting //TODO: replace by not android X version //implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0' androidTestImplementation 'junit:junit:4.12' diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index 986a136d..58ba2365 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -3,9 +3,14 @@ package foundation.e.drive.services; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Service; +import android.app.job.JobInfo; +import android.app.job.JobScheduler; +import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; import android.support.test.runner.AndroidJUnit4; import junit.framework.Assert; @@ -14,44 +19,49 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; - +import org.mockito.MockedStatic; import org.robolectric.Robolectric; -import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; -import org.robolectric.util.ServiceController; +import org.robolectric.android.controller.ServiceController; +import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowLog; +import org.robolectric.shadows.ShadowNetworkInfo; +import foundation.e.drive.jobs.ScannerJob; import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; +import foundation.e.drive.utils.JobUtils; -import static org.junit.Assert.*; +import static foundation.e.drive.utils.JobUtils.ScannerJobId; import static org.robolectric.Shadows.shadowOf; @RunWith(AndroidJUnit4.class) +@Config(manifest=Config.NONE) public class ObserverServiceTest { private ObserverService myService; private ServiceController mServiceController; private final static String TEST_ACCOUNT_TYPE ="eelo"; - private final static String TEST_ACCOUNT_NAME="vincent"; + private final static String TEST_ACCOUNT_NAME="noone"; private final static int INITIAL_FOLDER_NUMBER=0; private final static long LAST_SYNC_TIME=0l; - - private AccountManager accountManager; + private JobScheduler jobScheduler; + private AccountManager accountManager; + private Account validAccount; @Before public void setUp(){ //Note: May be the SharedPrefs part could be created with robolectric instead of mockito.. - + ShadowLog.stream = System.out; prepareSharedPref(); prepareAccount(); + prepareJobScheduler(); + prepareNetworkStatus(); + //mockCommonUtils(); //uncomment this make validAccount to not work... Why ?! mServiceController = Robolectric.buildService(ObserverService.class); - - //This where I should create the DB, prepare mock object, etc... - - } private void prepareSharedPref(){ @@ -62,8 +72,8 @@ public class ObserverServiceTest { .putBoolean(AppConstants.KEY_OMS_IS_WORKING, false) .putString(AccountManager.KEY_ACCOUNT_NAME, TEST_ACCOUNT_NAME) .putString(AccountManager.KEY_ACCOUNT_TYPE, TEST_ACCOUNT_TYPE) - .putInt(AppConstants.INITIALFOLDERS_NUMBER, 0) - .putLong(AppConstants.KEY_LAST_SYNC_TIME, 0L) + .putInt(AppConstants.INITIALFOLDERS_NUMBER, INITIAL_FOLDER_NUMBER) + .putLong(AppConstants.KEY_LAST_SYNC_TIME, LAST_SYNC_TIME) //Set this value to currentTime to make it fails .commit(); } @@ -71,20 +81,80 @@ public class ObserverServiceTest { private void prepareAccount(){ accountManager = AccountManager.get(RuntimeEnvironment.application); - Account account0 = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type - shadowOf(accountManager).addAccount(account0); + validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type + shadowOf(accountManager).addAccount(validAccount); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... } + + private void prepareJobScheduler(){ + jobScheduler = (JobScheduler) RuntimeEnvironment.application.getSystemService(Context.JOB_SCHEDULER_SERVICE); + + ComponentName jobService = new ComponentName( RuntimeEnvironment.application, ScannerJob.class ); + + + Assert.assertNotNull(jobService); + + //Creating the job like in ScannerJob class isn't possible because Robolectric doesn't + // support chaining of function with JobInfo.Builder... + JobInfo.Builder jobBuilder = new JobInfo.Builder(ScannerJobId, jobService ); + Assert.assertNotNull(jobBuilder); + + jobBuilder.setPeriodic(1860000, 30000); + jobBuilder.setPersisted(true); + jobBuilder.setRequiredNetworkType( JobInfo.NETWORK_TYPE_ANY ); + + //JobInfo job = jobBuilder.build(); + //System.out.println("is Job null ??"); + //Assert.assertNotNull(job); //Can't find why it fails: NPE, job is null... + + + //Assert.assertTrue(jobScheduler.getAllPendingJobs().isEmpty()); //Get NPE too...why ? + + //shadowOf(jobScheduler).schedule(job); + + //Mockito.when(JobUtils.scheduleScannerJob(RuntimeEnvironment.application)).then(); + } + + + private void prepareNetworkStatus(){ + shadowOf((ConnectivityManager) RuntimeEnvironment.application + .getSystemService(Context.CONNECTIVITY_SERVICE)) + .setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null, + ConnectivityManager.TYPE_WIFI, 0, true, NetworkInfo.State.CONNECTED)); + } + + + + + private void mockCommonUtils(){ + MockedStatic mockedCommonUtils = Mockito.mockStatic(CommonUtils.class); + mockedCommonUtils.when(new MockedStatic.Verification() { + @Override + public void apply() throws Throwable { + CommonUtils.isMediaSyncEnabled(validAccount); + } + }).thenReturn(true); + + + mockedCommonUtils.when(new MockedStatic.Verification() { + @Override + public void apply() throws Throwable { + CommonUtils.isSettingsSyncEnabled(validAccount); + } + }).thenReturn(true); + + } + + @Test public void testWithIntent() { + //Intent intent = new Intent(RuntimeEnvironment.application, ObserverService.class); mServiceController.create().startCommand(0, 0); myService = mServiceController.get(); - //There is issue with "CommonUtils.setServiceUnCaughtExceptionHandler(this);" // assert here - Assert.fail(); } -- GitLab From c79aedb2a2a1cd15bcf446b2282149897eb30ce5 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Tue, 13 Apr 2021 18:22:10 +0200 Subject: [PATCH 11/60] update ObserverServiceTest. Fix ContentResolver issue but encounter Network detection issue --- .../e/drive/services/ObserverServiceTest.java | 35 ++++++++----------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index 58ba2365..98064b08 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -6,6 +6,7 @@ import android.app.Service; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; +import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -13,6 +14,8 @@ import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.test.runner.AndroidJUnit4; +import com.google.android.apps.common.testing.accessibility.framework.proto.FrameworkProtos; + import junit.framework.Assert; import org.junit.Before; @@ -24,6 +27,7 @@ import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.android.controller.ServiceController; import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowContentResolver; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowNetworkInfo; @@ -32,6 +36,8 @@ import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; import foundation.e.drive.utils.JobUtils; +import static foundation.e.drive.utils.AppConstants.MEDIASYNC_PROVIDER_AUTHORITY; +import static foundation.e.drive.utils.AppConstants.SETTINGSYNC_PROVIDER_AUTHORITY; import static foundation.e.drive.utils.JobUtils.ScannerJobId; import static org.robolectric.Shadows.shadowOf; @@ -50,7 +56,8 @@ public class ObserverServiceTest { private JobScheduler jobScheduler; private AccountManager accountManager; private Account validAccount; - + private ConnectivityManager connectivityManager; + private ContentResolver contentResolver; @Before public void setUp(){ //Note: May be the SharedPrefs part could be created with robolectric instead of mockito.. @@ -59,7 +66,7 @@ public class ObserverServiceTest { prepareAccount(); prepareJobScheduler(); prepareNetworkStatus(); - //mockCommonUtils(); //uncomment this make validAccount to not work... Why ?! + prepareContentResolver(); mServiceController = Robolectric.buildService(ObserverService.class); } @@ -117,32 +124,20 @@ public class ObserverServiceTest { private void prepareNetworkStatus(){ - shadowOf((ConnectivityManager) RuntimeEnvironment.application - .getSystemService(Context.CONNECTIVITY_SERVICE)) - .setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null, + connectivityManager = (ConnectivityManager) RuntimeEnvironment.application .getSystemService(Context.CONNECTIVITY_SERVICE); + shadowOf(connectivityManager).setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null, ConnectivityManager.TYPE_WIFI, 0, true, NetworkInfo.State.CONNECTED)); } - private void mockCommonUtils(){ - MockedStatic mockedCommonUtils = Mockito.mockStatic(CommonUtils.class); - mockedCommonUtils.when(new MockedStatic.Verification() { - @Override - public void apply() throws Throwable { - CommonUtils.isMediaSyncEnabled(validAccount); - } - }).thenReturn(true); - + private void prepareContentResolver(){ //replace this by robolectric the contentResolver - mockedCommonUtils.when(new MockedStatic.Verification() { - @Override - public void apply() throws Throwable { - CommonUtils.isSettingsSyncEnabled(validAccount); - } - }).thenReturn(true); + contentResolver = RuntimeEnvironment.application.getContentResolver(); + contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); + contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, true); } -- GitLab From a7ee68ecbc786fc24efe70a958d2d1d8f0c61478 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 14 Apr 2021 11:45:27 +0200 Subject: [PATCH 12/60] fix CommonUtils.haveNetworkConnexion() --- app/src/main/java/foundation/e/drive/utils/CommonUtils.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/foundation/e/drive/utils/CommonUtils.java b/app/src/main/java/foundation/e/drive/utils/CommonUtils.java index 2d1c16e2..c58bd6c1 100644 --- a/app/src/main/java/foundation/e/drive/utils/CommonUtils.java +++ b/app/src/main/java/foundation/e/drive/utils/CommonUtils.java @@ -17,6 +17,7 @@ import android.content.ContentResolver; import android.content.Context; import android.media.MediaScannerConnection; import android.net.ConnectivityManager; +import android.net.Network; import android.net.NetworkInfo; import android.net.Uri; import android.support.annotation.NonNull; @@ -206,10 +207,10 @@ public abstract class CommonUtils { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] netInfo = cm.getAllNetworkInfo(); for (NetworkInfo ni : netInfo) { - if (ni.getTypeName().equalsIgnoreCase("WIFI")) + if (ni.getType()== ConnectivityManager.TYPE_WIFI) // Replaced the ni.getTypeName by ni.getType to make the test from ObserverServiceTest to work. But looks a better solution in all case if (ni.isConnected()) haveConnectedWifi = true; - if (ni.getTypeName().equalsIgnoreCase("MOBILE")) + if (ni.getType()== ConnectivityManager.TYPE_MOBILE) if (ni.isConnected()) haveConnectedMobile = true; } -- GitLab From 12677c9366b0e056521546e071ad0050cf3c393d Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 14 Apr 2021 11:46:19 +0200 Subject: [PATCH 13/60] fix robolectric Networkmanager preparation --- .../foundation/e/drive/services/ObserverServiceTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index 98064b08..689684b3 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -125,8 +125,10 @@ public class ObserverServiceTest { private void prepareNetworkStatus(){ connectivityManager = (ConnectivityManager) RuntimeEnvironment.application .getSystemService(Context.CONNECTIVITY_SERVICE); - shadowOf(connectivityManager).setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null, - ConnectivityManager.TYPE_WIFI, 0, true, NetworkInfo.State.CONNECTED)); + NetworkInfo netInfo = ShadowNetworkInfo.newInstance(null, + ConnectivityManager.TYPE_WIFI, 0, true, NetworkInfo.State.CONNECTED); + Assert.assertEquals("NetworkInfo type is invalid",ConnectivityManager.TYPE_WIFI,netInfo.getType()); + shadowOf(connectivityManager).setActiveNetworkInfo(netInfo); } -- GitLab From 32a4b482262f228dd5bf5ee3d15239a066f8e77e Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 15 Apr 2021 17:04:07 +0200 Subject: [PATCH 14/60] refactor CommonUtils.setServiceUncaughtExceptionHandler to prevent defaultUEHC to be null. Refactor ObserverServiceTest class and start to add different test --- ...a => ObserverServiceInstrumentedTest.java} | 2 +- .../foundation/e/drive/utils/CommonUtils.java | 2 +- .../e/drive/services/ObserverServiceTest.java | 241 +++++++++++++++--- 3 files changed, 202 insertions(+), 43 deletions(-) rename app/src/androidTest/java/foundation/e/drive/services/{ObserverServiceTest.java => ObserverServiceInstrumentedTest.java} (98%) diff --git a/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceInstrumentedTest.java similarity index 98% rename from app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java rename to app/src/androidTest/java/foundation/e/drive/services/ObserverServiceInstrumentedTest.java index 1726870c..bd5fe22c 100644 --- a/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/androidTest/java/foundation/e/drive/services/ObserverServiceInstrumentedTest.java @@ -34,7 +34,7 @@ import static org.junit.Assert.*; * @see Testing documentation */ @RunWith(AndroidJUnit4.class) -public class ObserverServiceTest { +public class ObserverServiceInstrumentedTest { private final static String NEW_SMALL_FILE_PATH = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DOCUMENTS+File.separator+"test-small-file.txt"; private final static String ACCOUNT_NAME= ""; private final static String ACCOUNT_PASS=""; diff --git a/app/src/main/java/foundation/e/drive/utils/CommonUtils.java b/app/src/main/java/foundation/e/drive/utils/CommonUtils.java index c58bd6c1..b6de97e4 100644 --- a/app/src/main/java/foundation/e/drive/utils/CommonUtils.java +++ b/app/src/main/java/foundation/e/drive/utils/CommonUtils.java @@ -55,7 +55,7 @@ public abstract class CommonUtils { public static void setServiceUnCaughtExceptionHandler(Service service) { Thread.UncaughtExceptionHandler defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); - if (defaultUEH.getClass().getSimpleName().equals(ServiceExceptionHandler.class.getSimpleName())) { + if (defaultUEH != null && ServiceExceptionHandler.class.getSimpleName().equals(defaultUEH.getClass().getSimpleName())) { Log.d("ObserverService", "ServiceExceptionHandler already set!"); ((ServiceExceptionHandler) defaultUEH).setService(service); } else { diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index 689684b3..493be0a4 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -12,12 +12,21 @@ import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; +import android.os.FileUriExposedException; +import android.os.Handler; import android.support.test.runner.AndroidJUnit4; import com.google.android.apps.common.testing.accessibility.framework.proto.FrameworkProtos; +import com.owncloud.android.lib.common.OwnCloudClient; +import com.owncloud.android.lib.common.accounts.AccountUtils; +import com.owncloud.android.lib.common.operations.OnRemoteOperationListener; +import com.owncloud.android.lib.common.operations.RemoteOperation; +import com.owncloud.android.lib.common.operations.RemoteOperationResult; +import com.owncloud.android.lib.resources.files.FileUtils; import junit.framework.Assert; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,71 +40,97 @@ import org.robolectric.shadows.ShadowContentResolver; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowNetworkInfo; +import java.io.File; +import java.util.List; + +import foundation.e.drive.BuildConfig; +import foundation.e.drive.database.DbHelper; import foundation.e.drive.jobs.ScannerJob; +import foundation.e.drive.models.SyncedFolder; +import foundation.e.drive.operations.CreateInitialFolderRemoteOperation; import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; import foundation.e.drive.utils.JobUtils; +import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; +import static foundation.e.drive.utils.AppConstants.INITIALIZATION_HAS_BEEN_DONE; import static foundation.e.drive.utils.AppConstants.MEDIASYNC_PROVIDER_AUTHORITY; +import static foundation.e.drive.utils.AppConstants.MEDIA_SYNCABLE_CATEGORIES; import static foundation.e.drive.utils.AppConstants.SETTINGSYNC_PROVIDER_AUTHORITY; import static foundation.e.drive.utils.JobUtils.ScannerJobId; import static org.robolectric.Shadows.shadowOf; @RunWith(AndroidJUnit4.class) -@Config(manifest=Config.NONE) public class ObserverServiceTest { - private ObserverService myService; - private ServiceController mServiceController; + private static final String TEST_SERVER_URI ="https://eeo.one"; private final static String TEST_ACCOUNT_TYPE ="eelo"; - private final static String TEST_ACCOUNT_NAME="noone"; - private final static int INITIAL_FOLDER_NUMBER=0; - private final static long LAST_SYNC_TIME=0l; - + private final static String TEST_ACCOUNT_NAME="edrivetesting1"; + //private final static String PROD_ACCOUNT_NAME="vincent.bourgmayer@e.email"; + private int initial_folder_number=0; + private long last_sync_time=0l; + private boolean init_done = true; + private boolean oms_running=false; + private ObserverService myService; + private ServiceController mServiceController; + //Stuff Below could be defined in a abstractClass which would be extends by other test class private JobScheduler jobScheduler; private AccountManager accountManager; private Account validAccount; private ConnectivityManager connectivityManager; private ContentResolver contentResolver; + private SharedPreferences sharedPreferences; + + //private Handler handler; //Trial for SSL issue with remote folder creation + @Before public void setUp(){ //Note: May be the SharedPrefs part could be created with robolectric instead of mockito.. - ShadowLog.stream = System.out; - prepareSharedPref(); - prepareAccount(); - prepareJobScheduler(); - prepareNetworkStatus(); - prepareContentResolver(); - mServiceController = Robolectric.buildService(ObserverService.class); - - } + ShadowLog.stream = System.out; //give access to log - private void prepareSharedPref(){ - SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences( + accountManager = AccountManager.get(RuntimeEnvironment.application); + connectivityManager = (ConnectivityManager) RuntimeEnvironment.application .getSystemService(Context.CONNECTIVITY_SERVICE); + jobScheduler = (JobScheduler) RuntimeEnvironment.application.getSystemService(Context.JOB_SCHEDULER_SERVICE); + contentResolver = RuntimeEnvironment.application.getContentResolver(); + sharedPreferences = RuntimeEnvironment.application.getSharedPreferences( AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); + DbHelper helper = new DbHelper(RuntimeEnvironment.application); + + + mServiceController = Robolectric.buildService(ObserverService.class); + myService = mServiceController.get(); + } - sharedPreferences.edit().putBoolean( AppConstants.INITIALIZATION_HAS_BEEN_DONE, true) - .putBoolean(AppConstants.KEY_OMS_IS_WORKING, false) + /** + * Register all the preferences in SharedPref object + */ + private void registerSharedPref(){ + sharedPreferences.edit().putBoolean( AppConstants.INITIALIZATION_HAS_BEEN_DONE, init_done) + .putBoolean(AppConstants.KEY_OMS_IS_WORKING, oms_running) .putString(AccountManager.KEY_ACCOUNT_NAME, TEST_ACCOUNT_NAME) .putString(AccountManager.KEY_ACCOUNT_TYPE, TEST_ACCOUNT_TYPE) - .putInt(AppConstants.INITIALFOLDERS_NUMBER, INITIAL_FOLDER_NUMBER) - .putLong(AppConstants.KEY_LAST_SYNC_TIME, LAST_SYNC_TIME) //Set this value to currentTime to make it fails - + .putInt(AppConstants.INITIALFOLDERS_NUMBER, initial_folder_number) + .putLong(AppConstants.KEY_LAST_SYNC_TIME, last_sync_time) //Set this value to currentTime to make it fails .commit(); } - - private void prepareAccount(){ - accountManager = AccountManager.get(RuntimeEnvironment.application); + /** + * Create and register one validAccount + */ + private void prepareValidAccount(){ validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type + shadowOf(accountManager).addAccount(validAccount); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... + shadowOf(accountManager).setPassword(validAccount, "REPLACEATRUNTIMR"); + //shadowOf(accountManager).setAuthToken(validAccount, "dontknowWhatToDo", "REPLACEATRUNTIMR"); + shadowOf(accountManager).setUserData(validAccount, KEY_OC_BASE_URL, TEST_SERVER_URI); } - - private void prepareJobScheduler(){ - jobScheduler = (JobScheduler) RuntimeEnvironment.application.getSystemService(Context.JOB_SCHEDULER_SERVICE); - + /** + * Schedule a ScannerJob instance in JobScheduler + */ + private void registerScannerJobInJobScheduler(){ ComponentName jobService = new ComponentName( RuntimeEnvironment.application, ScannerJob.class ); @@ -123,36 +158,160 @@ public class ObserverServiceTest { } - private void prepareNetworkStatus(){ - connectivityManager = (ConnectivityManager) RuntimeEnvironment.application .getSystemService(Context.CONNECTIVITY_SERVICE); + /** + * Set the network status to an available wifi + */ + private void setWifiNetworkStatus(){ NetworkInfo netInfo = ShadowNetworkInfo.newInstance(null, ConnectivityManager.TYPE_WIFI, 0, true, NetworkInfo.State.CONNECTED); Assert.assertEquals("NetworkInfo type is invalid",ConnectivityManager.TYPE_WIFI,netInfo.getType()); shadowOf(connectivityManager).setActiveNetworkInfo(netInfo); } + private void setUnavailableWifiNetworkStatus(){ + NetworkInfo netInfo = ShadowNetworkInfo.newInstance(null, + ConnectivityManager.TYPE_WIFI, 0, false, NetworkInfo.State.CONNECTED); + Assert.assertEquals("NetworkInfo type is invalid",ConnectivityManager.TYPE_WIFI,netInfo.getType()); + shadowOf(connectivityManager).setActiveNetworkInfo(netInfo); + } + /** + * enable Media & settings sync + */ + private void enableMediaAndSettingsSync(){ //replace this by robolectric the contentResolver + contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); + contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, true); + } - private void prepareContentResolver(){ //replace this by robolectric the contentResolver - contentResolver = RuntimeEnvironment.application.getContentResolver(); + private SyncedFolder createSingleTestSyncedFolder(){ + //handler = new Handler(); + final String watchedFolderLocalPath = "/tmp/eDrive/test/"; + final String watchedFolderRemotePath="/eDrive-test/"; + final File folder = new File(watchedFolderLocalPath); + folder.mkdirs(); + final SyncedFolder sFolder = new SyncedFolder(MEDIA_SYNCABLE_CATEGORIES[0], watchedFolderLocalPath, watchedFolderRemotePath, true); + + return sFolder; - contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); - contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, true); + } + + + private void createRemoteSyncedFolder(SyncedFolder folder){ + OwnCloudClient client = CommonUtils.getOwnCloudClient(validAccount, RuntimeEnvironment.application); + CreateInitialFolderRemoteOperation op = new CreateInitialFolderRemoteOperation(folder, true, RuntimeEnvironment.application); + op.execute(client); //Give SSL issue + //op.execute(client, myService, this.handler); + //op.execute(client, true); + //op.execute(validAccount, RuntimeEnvironment.application); + + //Assert.assertTrue(folderList.contains(sFolder)); + initial_folder_number =1; } @Test - public void testWithIntent() { + public void shouldWork() { + setWifiNetworkStatus(); + prepareValidAccount(); + enableMediaAndSettingsSync(); + //createRemoteSyncedFolder(createSingleTestSyncedFolder()); + registerScannerJobInJobScheduler(); + registerSharedPref(); + + //Start the service + mServiceController.create().startCommand(0, 0); + + //@TODO add assertion! + Assert.fail("NO Assertion here!"); + //Tear down + //Assert.assertTrue("Database hasn't been removed", myService.deleteDatabase(DbHelper.DATABASE_NAME)); + } + + + + + /** + * This assert that ObserverService doesn't start scanning remote or local if there is no network + */ + @Test + public void shouldStopWithoutNetwork(){ + + //setUnavailableWifiNetworkStatus(); + prepareValidAccount(); + enableMediaAndSettingsSync(); + //createRemoteSyncedFolder(createSingleTestSyncedFolder()); + registerScannerJobInJobScheduler(); + registerSharedPref(); - //Intent intent = new Intent(RuntimeEnvironment.application, ObserverService.class); mServiceController.create().startCommand(0, 0); - myService = mServiceController.get(); - //There is issue with "CommonUtils.setServiceUnCaughtExceptionHandler(this);" - // assert here + List logs = ShadowLog.getLogs(); + ShadowLog.LogItem lastLog = logs.get(logs.size()-1); + Assert.assertEquals("Last log isn't the one expected", "There is no Internet connexion.", lastLog.msg); + + } + + + /** + * This assert that ObserverService won't start if the minimum delay between two sync isn't over + */ + @Test + public void lastSyncWas15minAgo_shouldStop(){ + Assert.fail("Not implemented yet"); + } + + /** + * This assert that ObserverService will do its job if the minimum delay between two sync is over + */ + @Test + public void lastSync15minAnd30secAgo_shouldStart(){ + Assert.fail("Not implemented yet"); + } + + /** + * This assert that ObserverService won't start if it's already running + */ + @Test + public void syncAlreadyStarted_shouldStop(){ + //@TODO need to find how to access the "isRunning" private field inside the ObserverService for this test + Assert.fail("Not implemented yet"); } + + /** + * This test will assert that the ObserverService won't do its job + * if Initialization hasn't been done + */ + @Test + public void InitializationNotDone_shouldStop(){ + init_done = false; //This is the key settings for this test + + setWifiNetworkStatus(); + prepareValidAccount(); + enableMediaAndSettingsSync(); + //createRemoteSyncedFolder(createSingleTestSyncedFolder()); + registerScannerJobInJobScheduler(); + registerSharedPref(); + + + Assert.assertFalse("SharedPref doesn't contains the expected value for Initialization_has_been_done key", sharedPreferences.getBoolean(INITIALIZATION_HAS_BEEN_DONE, true)); + + mServiceController.create().startCommand(0, 0); + + + //How to assert this... ? + + List logs = ShadowLog.getLogs(); + ShadowLog.LogItem lastLog = logs.get(logs.size()-1); + + //Note: Checking log is the only way I've found to check that the service stopped as expected + Assert.assertEquals("Last log isn't the one expected", "Initialization hasn't been done", lastLog.msg); + //Assert.assertTrue(logs.contains()); //@TODO how to assert that logs doesn't contain the expecteed message ? + + //tearDown - Remove DB if it had been created + myService.deleteDatabase(DbHelper.DATABASE_NAME); + } } \ No newline at end of file -- GitLab From 40595b544378f693086979b52e505fa3c2e0886a Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 16 Apr 2021 10:55:38 +0200 Subject: [PATCH 15/60] implement test and investigate commonUtils.haveNetworkConnexion issue with noNetwork test... --- .../e/drive/services/ObserverServiceTest.java | 76 ++++++++++++++----- 1 file changed, 57 insertions(+), 19 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index 493be0a4..a172ce63 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -2,30 +2,21 @@ package foundation.e.drive.services; import android.accounts.Account; import android.accounts.AccountManager; -import android.app.Service; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; -import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; +import android.net.Network; import android.net.NetworkInfo; -import android.os.FileUriExposedException; -import android.os.Handler; import android.support.test.runner.AndroidJUnit4; -import com.google.android.apps.common.testing.accessibility.framework.proto.FrameworkProtos; import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.accounts.AccountUtils; -import com.owncloud.android.lib.common.operations.OnRemoteOperationListener; -import com.owncloud.android.lib.common.operations.RemoteOperation; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.resources.files.FileUtils; import junit.framework.Assert; - +import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -169,9 +160,20 @@ public class ObserverServiceTest { } private void setUnavailableWifiNetworkStatus(){ + //Try to remove the two default Network available that are "MOBILE" and "CONNECTED" + //But doesn't work... + + //shadowOf(connectivityManager).clearAllNetworks(); + + /*for(Network network : shadowOf (connectivityManager).getAllNetworks()){ + shadowOf(connectivityManager).removeNetwork(network); + }*/ + NetworkInfo netInfo = ShadowNetworkInfo.newInstance(null, - ConnectivityManager.TYPE_WIFI, 0, false, NetworkInfo.State.CONNECTED); + ConnectivityManager.TYPE_WIFI, 0, true, NetworkInfo.State.DISCONNECTED); Assert.assertEquals("NetworkInfo type is invalid",ConnectivityManager.TYPE_WIFI,netInfo.getType()); + + shadowOf(connectivityManager).setActiveNetworkInfo(netInfo); } @@ -236,17 +238,20 @@ public class ObserverServiceTest { * This assert that ObserverService doesn't start scanning remote or local if there is no network */ @Test - public void shouldStopWithoutNetwork(){ - - //setUnavailableWifiNetworkStatus(); + public void noNetwork_shouldStop(){ + //setWifiNetworkStatus(); Make the test to fail as expected + //setUnavailableWifiNetworkStatus(); //Doesn't give the expected result at the moment so the test fails! prepareValidAccount(); enableMediaAndSettingsSync(); //createRemoteSyncedFolder(createSingleTestSyncedFolder()); registerScannerJobInJobScheduler(); registerSharedPref(); - mServiceController.create().startCommand(0, 0); + boolean haveNetworkConnexion = CommonUtils.haveNetworkConnexion(RuntimeEnvironment.application); + String msg = "CommonUtils.haveNetworkConnexion should return false but return "+haveNetworkConnexion; + Assert.assertFalse(msg, haveNetworkConnexion); + mServiceController.create().startCommand(0, 0); List logs = ShadowLog.getLogs(); ShadowLog.LogItem lastLog = logs.get(logs.size()-1); @@ -259,8 +264,26 @@ public class ObserverServiceTest { * This assert that ObserverService won't start if the minimum delay between two sync isn't over */ @Test - public void lastSyncWas15minAgo_shouldStop(){ - Assert.fail("Not implemented yet"); + public void lastSyncWasLessThan15minAgo_shouldStop(){ + last_sync_time = System.currentTimeMillis() - 899900; + setWifiNetworkStatus(); + prepareValidAccount(); + enableMediaAndSettingsSync(); + //createRemoteSyncedFolder(createSingleTestSyncedFolder()); + registerScannerJobInJobScheduler(); + registerSharedPref(); + + //Start the service + mServiceController.create().startCommand(0, 0); + + //How to assert this... ? + + List logs = ShadowLog.getLogs(); + ShadowLog.LogItem lastLog = logs.get(logs.size()-1); + + //Note: Checking log is the only way I've found to check that the service stopped as expected + Assert.assertEquals("Last log isn't the one expected", "Delay between now and last call is too short", lastLog.msg); + } /** @@ -268,7 +291,22 @@ public class ObserverServiceTest { */ @Test public void lastSync15minAnd30secAgo_shouldStart(){ - Assert.fail("Not implemented yet"); + //decrease 15min and 30sec + last_sync_time = System.currentTimeMillis() - 930000; + setWifiNetworkStatus(); + prepareValidAccount(); + enableMediaAndSettingsSync(); + //createRemoteSyncedFolder(createSingleTestSyncedFolder()); + registerScannerJobInJobScheduler(); + registerSharedPref(); + + //Start the service + mServiceController.create().startCommand(0, 0); + + List logs = ShadowLog.getLogs(); + for(ShadowLog.LogItem log : logs){ + Assert.assertFalse("Log shouldn't contains 'delay between now and last call is too short' but it does", log.msg.equals("Delay between now and last call is too short")); //There isn't assertNotEquals + } } /** -- GitLab From 6600ad6fcdfc39a969bc9edbecb69e0205945847 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 16 Apr 2021 11:14:24 +0200 Subject: [PATCH 16/60] remove unused import --- .../java/foundation/e/drive/AbstractIT.java | 116 ------------------ .../e/drive/ExampleInstrumentedTest.java | 36 ------ .../services/InitializerServiceTest.java | 19 --- .../services/OperationManagerServiceTest.java | 21 ---- .../e/drive/services/ResetServiceTest.java | 21 ---- .../java/foundation/e/drive/AbstractIT.java | 43 ------- .../e/drive/services/ObserverServiceTest.java | 9 -- 7 files changed, 265 deletions(-) delete mode 100644 app/src/androidTest/java/foundation/e/drive/AbstractIT.java delete mode 100644 app/src/androidTest/java/foundation/e/drive/ExampleInstrumentedTest.java delete mode 100644 app/src/androidTest/java/foundation/e/drive/services/InitializerServiceTest.java delete mode 100644 app/src/androidTest/java/foundation/e/drive/services/OperationManagerServiceTest.java delete mode 100644 app/src/androidTest/java/foundation/e/drive/services/ResetServiceTest.java delete mode 100644 app/src/test/java/foundation/e/drive/AbstractIT.java diff --git a/app/src/androidTest/java/foundation/e/drive/AbstractIT.java b/app/src/androidTest/java/foundation/e/drive/AbstractIT.java deleted file mode 100644 index 8b4cf2dd..00000000 --- a/app/src/androidTest/java/foundation/e/drive/AbstractIT.java +++ /dev/null @@ -1,116 +0,0 @@ -package foundation.e.drive; - - -import android.accounts.Account; -import android.accounts.AccountManager; -import android.app.Service; -import android.content.Context; -import android.support.test.InstrumentationRegistry; -import android.support.test.rule.GrantPermissionRule; -import android.Manifest; -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.resources.files.FileUtils; - -import org.junit.BeforeClass; -import org.junit.Rule; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; - -import static android.support.test.InstrumentationRegistry.getInstrumentation; -import static junit.framework.TestCase.assertTrue; - -/** - * Common base for all integration tests - * Inspired by NC's android application's test - */ -public class AbstractIT { - @Rule - public final GrantPermissionRule permissionRule = GrantPermissionRule.grant( - Manifest.permission.WRITE_EXTERNAL_STORAGE); - - protected static OwnCloudClient client; - protected static Account account; - protected static Context targetContext; - - - protected Service currentService; - - @BeforeClass - public static void beforeAll() { - - } - - protected Account[] getAllAccounts() { - return AccountManager.get(targetContext).getAccounts(); - } - - protected static void createDummyFiles() throws IOException { - File tempPath = new File(FileStorageUtils.getTemporalPath(account.name)); - if (!tempPath.exists()) { - assertTrue(tempPath.mkdirs()); - } - - assertTrue(tempPath.exists()); - - createFile("empty.txt", 0); - createFile("nonEmpty.txt", 100); - createFile("chunkedFile.txt", 500000); - } - - public static File createFile(String name, int iteration) throws IOException { - File file = new File(FileStorageUtils.getTemporalPath(account.name) + File.separator + name); - if (!file.getParentFile().exists()) { - assertTrue(file.getParentFile().mkdirs()); - } - - file.createNewFile(); - - FileWriter writer = new FileWriter(file); - - for (int i = 0; i < iteration; i++) { - writer.write("123123123123123123123123123\n"); - } - writer.flush(); - writer.close(); - - return file; - } - - - - protected File getFile(String filename) throws IOException { - InputStream inputStream = getInstrumentation().getContext().getAssets().open(filename); - File temp = File.createTempFile("file", "file"); - //FileUtils.copyInputStreamToFile(inputStream, temp); - - return temp; - } - - - - protected void waitForIdleSync() { - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); - } - - /** Need to find a wya to make this work for service **/ - protected Service getCurrentService) { - InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { - Collection resumedServices; - /*ServiceLifecycleMonitorRegistry - .getInstance() - .getServices();*/ - //.getActivitiesInStage(Stage.RESUMED); - - if (resumedServices.iterator().hasNext()) { - currentService = resumedServices.iterator().next(); - } - }); - - return currentService; - } -} diff --git a/app/src/androidTest/java/foundation/e/drive/ExampleInstrumentedTest.java b/app/src/androidTest/java/foundation/e/drive/ExampleInstrumentedTest.java deleted file mode 100644 index e6c481cd..00000000 --- a/app/src/androidTest/java/foundation/e/drive/ExampleInstrumentedTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright © Vincent Bourgmayer (/e/ foundation). - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - */ - - -package foundation.e.drive; - -import android.content.Context; -import android.support.test.InstrumentationRegistry; -import android.support.test.runner.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.*; - -/** - * Instrumented test, which will execute on an Android device. - * - * @see Testing documentation - */ -@RunWith(AndroidJUnit4.class) -public class ExampleInstrumentedTest { - @Test - public void useAppContext() throws Exception { - // Context of the app under test. - Context appContext = InstrumentationRegistry.getTargetContext(); - - - assertEquals("foundation.e.drive", appContext.getPackageName()); - } -} diff --git a/app/src/androidTest/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/InitializerServiceTest.java deleted file mode 100644 index b3afefde..00000000 --- a/app/src/androidTest/java/foundation/e/drive/services/InitializerServiceTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package foundation.e.drive.services; -import android.content.Context; -import android.support.test.InstrumentationRegistry; -import android.support.test.runner.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.*; - - -/** - * Instrumented test, which will execute on an Android device. - * - * @see Testing documentation - */ -@RunWith(AndroidJUnit4.class) -public class InitializerServiceTest { -} diff --git a/app/src/androidTest/java/foundation/e/drive/services/OperationManagerServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/OperationManagerServiceTest.java deleted file mode 100644 index b8d2562e..00000000 --- a/app/src/androidTest/java/foundation/e/drive/services/OperationManagerServiceTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package foundation.e.drive.services; -import android.content.Context; -import android.support.test.InstrumentationRegistry; -import android.support.test.runner.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.*; - - - - -/** - * Instrumented test, which will execute on an Android device. - * - * @see Testing documentation - */ -@RunWith(AndroidJUnit4.class) -public class OperationManagerServiceTest { -} diff --git a/app/src/androidTest/java/foundation/e/drive/services/ResetServiceTest.java b/app/src/androidTest/java/foundation/e/drive/services/ResetServiceTest.java deleted file mode 100644 index dd84488f..00000000 --- a/app/src/androidTest/java/foundation/e/drive/services/ResetServiceTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package foundation.e.drive.services; -import android.content.Context; -import android.support.test.InstrumentationRegistry; -import android.support.test.runner.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.*; - - - - -/** - * Instrumented test, which will execute on an Android device. - * - * @see Testing documentation - */ -@RunWith(AndroidJUnit4.class) -public class ResetServiceTest { -} diff --git a/app/src/test/java/foundation/e/drive/AbstractIT.java b/app/src/test/java/foundation/e/drive/AbstractIT.java deleted file mode 100644 index 7cd0cbfd..00000000 --- a/app/src/test/java/foundation/e/drive/AbstractIT.java +++ /dev/null @@ -1,43 +0,0 @@ -package foundation.e.drive; - -import android.accounts.Account; -import android.content.Context; - -//import com.owncloud.android.lib.common.OwnCloudClient; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -import static org.junit.Assert.assertTrue; - -/** - * This class contains common method for integration Test - * This is inspired by Nextcloud's android app's test - */ -public class AbstractIT { - //protected static OwnCloudClient client; - protected static Account account; - protected static Context targetContext; - - - public static File createFile(String name, int iteration) throws IOException { - String folder = "";//@TODO fix this - File file = new File(folder + File.separator + name); - if (!file.getParentFile().exists()) { - assertTrue(file.getParentFile().mkdirs()); - } - - file.createNewFile(); - - FileWriter writer = new FileWriter(file); - - for (int i = 0; i < iteration; i++) { - writer.write("123123123123123123123123123\n"); - } - writer.flush(); - writer.close(); - - return file; - } -} diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index a172ce63..8bbe32fe 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -9,39 +9,30 @@ import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; -import android.net.Network; import android.net.NetworkInfo; import android.support.test.runner.AndroidJUnit4; import com.owncloud.android.lib.common.OwnCloudClient; import junit.framework.Assert; -import static org.junit.Assert.*; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.MockedStatic; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.android.controller.ServiceController; -import org.robolectric.annotation.Config; -import org.robolectric.shadows.ShadowContentResolver; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowNetworkInfo; import java.io.File; import java.util.List; -import foundation.e.drive.BuildConfig; import foundation.e.drive.database.DbHelper; import foundation.e.drive.jobs.ScannerJob; import foundation.e.drive.models.SyncedFolder; import foundation.e.drive.operations.CreateInitialFolderRemoteOperation; import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; -import foundation.e.drive.utils.JobUtils; import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; import static foundation.e.drive.utils.AppConstants.INITIALIZATION_HAS_BEEN_DONE; -- GitLab From aadcd78a79631d23be4045b0b75003229d856b99 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 16 Apr 2021 11:16:02 +0200 Subject: [PATCH 17/60] add test job in CI --- .gitlab-ci.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6ba265a2..efea9d21 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,6 +1,7 @@ image: "registry.gitlab.e.foundation:5000/e/apps/docker-android-apps-cicd:latest" stages: +- test - build before_script: @@ -14,6 +15,18 @@ cache: paths: - .gradle/ + +test: + stage:test + script: + - ./gradlew test + artifacts: + paths: + - result/ # this is logcat + reports: + junit: app/build/reports/tests/testDebugUnitTest/ + + build: stage: build script: -- GitLab From 6f834ce01a5f36332da6da5dc3c37b38b8194d07 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 16 Apr 2021 11:18:29 +0200 Subject: [PATCH 18/60] add test job in CI --- .gitlab-ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index efea9d21..3ce4da2f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -17,14 +17,14 @@ cache: test: - stage:test + stage: test script: - - ./gradlew test + - ./gradlew test artifacts: paths: - result/ # this is logcat reports: - junit: app/build/reports/tests/testDebugUnitTest/ + junit: app/build/reports/tests/testDebugUnitTest/* build: -- GitLab From 39655a2835cb04a3a52c0c3e4082135812827925 Mon Sep 17 00:00:00 2001 From: Vincent Bourgmayer Date: Fri, 16 Apr 2021 09:21:34 +0000 Subject: [PATCH 19/60] Update gradle-wrapper.properties --- gradle/wrapper/gradle-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 54f9e466..46b275d7 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip -- GitLab From 77d7d1cb752b72202e85d620e5768550b4d246d0 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 16 Apr 2021 11:43:40 +0200 Subject: [PATCH 20/60] update nc library --- nextcloud-android-lib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nextcloud-android-lib b/nextcloud-android-lib index 880099c8..3d67ff49 160000 --- a/nextcloud-android-lib +++ b/nextcloud-android-lib @@ -1 +1 @@ -Subproject commit 880099c889253f30969b81c5e07750f070bfb65c +Subproject commit 3d67ff4917d47e1665b21382e0d54d3cae4915ad -- GitLab From bd89a7354efd527d38e4d7623e2ba00f77cd09f1 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 16 Apr 2021 12:11:07 +0200 Subject: [PATCH 21/60] update nc lib --- nextcloud-android-lib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nextcloud-android-lib b/nextcloud-android-lib index 3d67ff49..353568a7 160000 --- a/nextcloud-android-lib +++ b/nextcloud-android-lib @@ -1 +1 @@ -Subproject commit 3d67ff4917d47e1665b21382e0d54d3cae4915ad +Subproject commit 353568a74c0708496b36614b3ff69b9fafe9af0b -- GitLab From 2dea2d7e8d690a1beb84b7f46d7c2599caf1d418 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 19 Apr 2021 09:35:03 +0200 Subject: [PATCH 22/60] remove bad old test and update gitlab-ci --- .gitlab-ci.yml | 5 +- .../e/drive/unitTest/CommonUtilsUnitTest.java | 84 --- .../CrashlogFileFilterTest.java | 48 -- .../FileFilterTest/FileFilterUnitTest.java | 44 -- .../foundation/e/drive/unitTest/MD5Test.java | 85 --- .../unitTest/ObserverServiceUnitTest.java | 69 --- .../drive/unitTest/SyncedFolderUnitTest.java | 52 -- .../foundation/e/drive/unitTest/doTest.java | 4 - .../unitTest/mockObject/mockContext.java | 565 ------------------ .../unitTest/mockObject/mockRemoteFile.java | 7 - .../e/drive/unitTest/mockObject/mockSfs.java | 7 - 11 files changed, 2 insertions(+), 968 deletions(-) delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/CommonUtilsUnitTest.java delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/CrashlogFileFilterTest.java delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/FileFilterUnitTest.java delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/MD5Test.java delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/ObserverServiceUnitTest.java delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/SyncedFolderUnitTest.java delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/doTest.java delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/mockObject/mockContext.java delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/mockObject/mockRemoteFile.java delete mode 100644 app/src/test/java/foundation/e/drive/unitTest/mockObject/mockSfs.java diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 3ce4da2f..6c031797 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -21,10 +21,9 @@ test: script: - ./gradlew test artifacts: - paths: - - result/ # this is logcat + when: always reports: - junit: app/build/reports/tests/testDebugUnitTest/* + junit: app/build/test-results/testReleaseUnitTest/**/TEST-*.xml build: diff --git a/app/src/test/java/foundation/e/drive/unitTest/CommonUtilsUnitTest.java b/app/src/test/java/foundation/e/drive/unitTest/CommonUtilsUnitTest.java deleted file mode 100644 index 47154b43..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/CommonUtilsUnitTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright © Vincent Bourgmayer (/e/ foundation). - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - */ -package foundation.e.drive.unitTest; -import android.accounts.Account; - -import org.junit.Assert; -import org.junit.Test; - -/** - * @author Vincent Bourgmayer - * raw mock will be replace ASAP to use mockito or other similar framework - */ -public class CommonUtilsUnitTest { - - @Test - public void testIsThisSyncAllowed(){ - - boolean isMediaType = true; //sfs is media element - - MockAccount account = new MockAccount("allowed", "allowed"); //Both type sync are allowed - - Assert.assertNotNull("Assert account not null", account); - - Assert.assertTrue(isThisSyncAllowed(account, isMediaType)); - - account = new MockAccount("allowed", "not allowed"); //Only Media sync is enabled - Assert.assertTrue(isThisSyncAllowed(account, isMediaType)); - - account = new MockAccount("not allowed", "allowed"); //Only settings sync is enabled - Assert.assertFalse(isThisSyncAllowed(account, isMediaType)); - - account = new MockAccount("not allowed", "not allowed"); //no sync is enabled - Assert.assertFalse(isThisSyncAllowed(account, isMediaType)); - - isMediaType = false; - Assert.assertFalse(isThisSyncAllowed(account, isMediaType)); - - account = new MockAccount("allowed", "not allowed"); //Only Media sync is enabled - Assert.assertFalse(isThisSyncAllowed(account, isMediaType)); - - account = new MockAccount("not allowed", "allowed"); //Only settings sync is enabled - Assert.assertTrue(isThisSyncAllowed(account, isMediaType)); - - account = new MockAccount("allowed", "allowed"); //no sync is enabled - Assert.assertTrue(isThisSyncAllowed(account, isMediaType)); - - } - - - static boolean isThisSyncAllowed(MockAccount account, boolean syncedFileStateIsMedia){ - return ( syncedFileStateIsMedia && mockedIsMediaSyncEnabled(account) ) - || ( !syncedFileStateIsMedia && mockedIsSettingsSyncEnabled(account) ) ; - } - - //@mock tmp - static boolean mockedIsMediaSyncEnabled(MockAccount account){ - return account.mockName.equals("allowed"); - } - - //@mock tmp - static boolean mockedIsSettingsSyncEnabled(MockAccount account){ - return account.mockType.equals("allowed"); - } - - - /** - * Tmp mock class - */ - public class MockAccount extends Account{ - - String mockName; - String mockType; - MockAccount(String name, String type) { - super(name, type); - this.mockName = name; - this.mockType = type; - } - } -} diff --git a/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/CrashlogFileFilterTest.java b/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/CrashlogFileFilterTest.java deleted file mode 100644 index 31b262ea..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/CrashlogFileFilterTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package foundation.e.drive.unitTest.FileFilterTest; - -import org.junit.Assert; -import org.junit.Test; - -public class CrashlogFileFilterTest { - - private String mockFileName(String target, String prefix, String extension){ - return prefix+target+extension; - } - - private String extractTimestamp(String fileName, String prefix, String extension){ - return fileName.substring(prefix.length(), (fileName.length() - extension.length())); - } - - @Test - public void extractTimeStampFromFileNameTest(){ - String prefix = "edrive-"; - String extension = ".log"; - String target = ""; - //Case 1 Empty Target - String base = mockFileName(target, prefix, extension); - Assert.assertEquals("Base length is incorrect", prefix.length()+extension.length(), base.length()); - - String fileTimestamp = extractTimestamp(base, prefix, extension); - Assert.assertEquals("result is not empty String", "", fileTimestamp); - - //Case 2: Prefix is empty - prefix = ""; - target = "1234"; - base = mockFileName(target, prefix, extension); - Assert.assertEquals("Base length is incorrect", prefix.length()+target.length()+extension.length(), base.length()); - - fileTimestamp = extractTimestamp(base, prefix, extension); - Assert.assertEquals("result is not empty String", target, fileTimestamp); - - //Case 3: extension is empty - - prefix = "edrive-"; - extension = ""; - - base = mockFileName(target, prefix, extension); - Assert.assertEquals("Base length is incorrect", prefix.length()+target.length(), base.length()); - - fileTimestamp = extractTimestamp(base, prefix, extension); - Assert.assertEquals("result is not empty String", target, fileTimestamp); - } -} \ No newline at end of file diff --git a/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/FileFilterUnitTest.java b/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/FileFilterUnitTest.java deleted file mode 100644 index 7607f0c4..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/FileFilterTest/FileFilterUnitTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright © Vincent Bourgmayer (/e/ foundation). - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - */ - - -package foundation.e.drive.unitTest.FileFilterTest; - -import junit.framework.Assert; - -import org.junit.Test; - -import foundation.e.drive.utils.AppConstants; -/** - * @author Vincent Bourgmayer - */ -public class FileFilterUnitTest { - - @Test - public void SettingsFileFilterUnitTest(){ - //Directory situation - Assert.assertFalse(mockSettingFileFilterAcceptMethod("", false)); - Assert.assertFalse(mockSettingFileFilterAcceptMethod("", true)); - Assert.assertFalse(mockSettingFileFilterAcceptMethod("settings_foo.xml", false)); - Assert.assertFalse(mockSettingFileFilterAcceptMethod(AppConstants.APPLICATIONS_LIST_FILE_NAME, false)); - Assert.assertFalse(mockSettingFileFilterAcceptMethod("settings_", true)); - Assert.assertFalse(mockSettingFileFilterAcceptMethod(".xml", true)); - Assert.assertFalse(mockSettingFileFilterAcceptMethod("settings_"+AppConstants.APPLICATIONS_LIST_FILE_NAME, true)); - - - Assert.assertTrue(mockSettingFileFilterAcceptMethod("settings_.xml", true)); - Assert.assertTrue(mockSettingFileFilterAcceptMethod("settings_foo.xml", true)); - Assert.assertTrue(mockSettingFileFilterAcceptMethod(AppConstants.APPLICATIONS_LIST_FILE_NAME, true)); - } - - private boolean mockSettingFileFilterAcceptMethod(String name, boolean isFile){ - return ( isFile && - ( ( name.startsWith("settings_") && name.endsWith(".xml") ) - || name.equals( AppConstants.APPLICATIONS_LIST_FILE_NAME ) ) ); - } -} diff --git a/app/src/test/java/foundation/e/drive/unitTest/MD5Test.java b/app/src/test/java/foundation/e/drive/unitTest/MD5Test.java deleted file mode 100644 index 2698b840..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/MD5Test.java +++ /dev/null @@ -1,85 +0,0 @@ -package foundation.e.drive.unitTest; - - -/* - * Copyright (C) 2012 The CyanogenMod Project - * - * * Licensed under the GNU GPLv2 license - * - * The text of the license can be found in the LICENSE file - * or at https://www.gnu.org/licenses/gpl-2.0.txt - */ - - import android.text.TextUtils; - import android.util.Log; - - import java.io.File; - import java.io.FileInputStream; - import java.io.FileNotFoundException; - import java.io.IOException; - import java.io.InputStream; - import java.math.BigInteger; - import java.security.MessageDigest; - import java.security.NoSuchAlgorithmException; - -public class MD5Test { - private static final String TAG = "MD5"; - - public static boolean checkMD5(String md5, File updateFile) { - if (TextUtils.isEmpty(md5) || updateFile == null) { - Log.e(TAG, "MD5 string empty or updateFile null"); - return false; - } - - String calculatedDigest = calculateMD5(updateFile); - if (calculatedDigest == null) { - Log.e(TAG, "calculatedDigest null"); - return false; - } - - Log.v(TAG, "Calculated digest: " + calculatedDigest); - Log.v(TAG, "Provided digest: " + md5); - - return calculatedDigest.equalsIgnoreCase(md5); - } - - public static String calculateMD5(File updateFile) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - Log.e(TAG, "Exception while getting digest", e); - return null; - } - - InputStream is; - try { - is = new FileInputStream(updateFile); - } catch (FileNotFoundException e) { - Log.e(TAG, "Exception while getting FileInputStream", e); - return null; - } - - byte[] buffer = new byte[8192]; - int read; - try { - while ((read = is.read(buffer)) > 0) { - digest.update(buffer, 0, read); - } - byte[] md5sum = digest.digest(); - BigInteger bigInt = new BigInteger(1, md5sum); - String output = bigInt.toString(16); - // Fill to 32 chars - output = String.format("%32s", output).replace(' ', '0'); - return output; - } catch (IOException e) { - throw new RuntimeException("Unable to process file for MD5", e); - } finally { - try { - is.close(); - } catch (IOException e) { - Log.e(TAG, "Exception on closing MD5 input stream", e); - } - } - } -} \ No newline at end of file diff --git a/app/src/test/java/foundation/e/drive/unitTest/ObserverServiceUnitTest.java b/app/src/test/java/foundation/e/drive/unitTest/ObserverServiceUnitTest.java deleted file mode 100644 index adc97d7b..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/ObserverServiceUnitTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright © Vincent Bourgmayer (/e/ foundation). - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - */ -package foundation.e.drive.unitTest; - -import org.junit.Assert; -import org.junit.Test; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - - -/** - * @author Vincent Bourgmayer - */ - -public class ObserverServiceUnitTest { - - public File[] mockCachedFile(){ - File[] mockFile= new File[5]; - for(int i = 0; i < 5; ++i){ - mockFile[i] = new File("/emulated/storage/0/android/data/toto"+i+".jpg"); - } - return mockFile; - } - - public List mockUsedFilePath (){ - List stringList = new ArrayList<>(); - System.out.println("Stringset:"+( (stringList == null)? false: true) ); - boolean a1 = stringList.add( new String("/emulated/storage/0/DCIM/Camera/toto1.jpg") ); - boolean a2 = stringList.add( new String("/emulated/storage/0/DCIM/Camera/toto2.jpg") ); - //boolean a3 = stringSet.add( new String("/emulated/storage/0/DCIM/Camera/toto4.jpg") ); - Assert.assertNotNull(stringList); - return stringList; - } - - @Test - public void handleCachedFile(){ - //Load subfiles into external cache file - //Mock this - File[] fileArray = mockCachedFile(); - - Assert.assertNotNull(fileArray); - //Mock this; - List usedFilePath = mockUsedFilePath(); - - Assert.assertNotNull(usedFilePath); - boolean toRemove = true; - for(int i =0; i < fileArray.length; ++i){ - toRemove = true; - //System.out.println( fileArray[i] ); - for(String filePath : usedFilePath){ - - if(filePath.endsWith(fileArray[i].getName())){ - System.out.println("TRUE"); - toRemove = false; - }else - System.out.println("FALSE"); - } - if(toRemove){ - System.out.println("Deletion of file: "+fileArray[i].getName() ); - } - } - } -} diff --git a/app/src/test/java/foundation/e/drive/unitTest/SyncedFolderUnitTest.java b/app/src/test/java/foundation/e/drive/unitTest/SyncedFolderUnitTest.java deleted file mode 100644 index baecb8f4..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/SyncedFolderUnitTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright © Vincent Bourgmayer (/e/ foundation). - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - */ -package foundation.e.drive.unitTest; - -import junit.framework.Assert; - -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -import foundation.e.drive.models.SyncedFolder; - -import static foundation.e.drive.utils.AppConstants.MEDIA_SYNCABLE_CATEGORIES; - -/** - * @author Vincent Bourgmayer - */ - -public class SyncedFolderUnitTest { - - @Test - public void childCreationTest(){ - SyncedFolder parent = new SyncedFolder("dummy", "/storage/emulated/0/dummy/", "/dummy/", true, true, true, true); - Assert.assertNotNull(parent); - parent.setId(6); - parent.setLastModified(123456789); - - Assert.assertEquals("dummy", parent.getLibelle() ); - - SyncedFolder child = new SyncedFolder(parent, "sub_dummy/", 234678965, ""); - Assert.assertNotNull("child is null", child); - Assert.assertEquals("LocalPath isn't valid", "/storage/emulated/0/dummy/sub_dummy/", child.getLocalFolder()); - Assert.assertEquals("remotePath isn't valid", "/dummy/sub_dummy/", child.getRemoteFolder() ); - Assert.assertTrue("lastModified aren't different", child.getLastModified() != parent.getLastModified() ); - Assert.assertEquals("child libelle isn't valid", parent.getLibelle(), child.getLibelle() ); - Assert.assertTrue("Id are the same", parent.getId() != child.getId() ); - } - - @Test - public void testArrayToList(){ - List arrays = Arrays.asList(MEDIA_SYNCABLE_CATEGORIES); - - Assert.assertEquals(MEDIA_SYNCABLE_CATEGORIES.length, arrays.size()); - - } -} diff --git a/app/src/test/java/foundation/e/drive/unitTest/doTest.java b/app/src/test/java/foundation/e/drive/unitTest/doTest.java deleted file mode 100644 index cd8bfd27..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/doTest.java +++ /dev/null @@ -1,4 +0,0 @@ -package foundation.e.drive.unitTest; - -public class doTest { -} diff --git a/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockContext.java b/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockContext.java deleted file mode 100644 index 1125e35e..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockContext.java +++ /dev/null @@ -1,565 +0,0 @@ -package foundation.e.drive.unitTest.mockObject; - -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.ContentResolver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.IntentSender; -import android.content.ServiceConnection; -import android.content.SharedPreferences; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.res.AssetManager; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.database.DatabaseErrorHandler; -import android.database.sqlite.SQLiteDatabase; -import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.os.UserHandle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.view.Display; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -public class mockContext extends Context{ - - public mockContext(){ - - } - @Override - public AssetManager getAssets() { - return null; - } - - @Override - public Resources getResources() { - return null; - } - - @Override - public PackageManager getPackageManager() { - return null; - } - - @Override - public ContentResolver getContentResolver() { - return null; - } - - @Override - public Looper getMainLooper() { - return null; - } - - @Override - public Context getApplicationContext() { - return null; - } - - @Override - public void setTheme(int resid) { - - } - - @Override - public Resources.Theme getTheme() { - return null; - } - - @Override - public ClassLoader getClassLoader() { - return null; - } - - @Override - public String getPackageName() { - return null; - } - - @Override - public ApplicationInfo getApplicationInfo() { - return null; - } - - @Override - public String getPackageResourcePath() { - return null; - } - - @Override - public String getPackageCodePath() { - return null; - } - - @Override - public SharedPreferences getSharedPreferences(String name, int mode) { - return null; - } - - @Override - public boolean moveSharedPreferencesFrom(Context sourceContext, String name) { - return false; - } - - @Override - public boolean deleteSharedPreferences(String name) { - return false; - } - - @Override - public FileInputStream openFileInput(String name) throws FileNotFoundException { - return null; - } - - @Override - public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException { - return null; - } - - @Override - public boolean deleteFile(String name) { - return false; - } - - @Override - public File getFileStreamPath(String name) { - return null; - } - - @Override - public File getDataDir() { - return null; - } - - @Override - public File getFilesDir() { - return null; - } - - @Override - public File getNoBackupFilesDir() { - return null; - } - - @Nullable - @Override - public File getExternalFilesDir(@Nullable String type) { - return null; - } - - @Override - public File[] getExternalFilesDirs(String type) { - return new File[0]; - } - - @Override - public File getObbDir() { - return null; - } - - @Override - public File[] getObbDirs() { - return new File[0]; - } - - @Override - public File getCacheDir() { - return null; - } - - @Override - public File getCodeCacheDir() { - return null; - } - - @Nullable - @Override - public File getExternalCacheDir() { - return null; - } - - @Override - public File[] getExternalCacheDirs() { - return new File[0]; - } - - @Override - public File[] getExternalMediaDirs() { - return new File[0]; - } - - @Override - public String[] fileList() { - return new String[0]; - } - - @Override - public File getDir(String name, int mode) { - return null; - } - - @Override - public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) { - return null; - } - - @Override - public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, @Nullable DatabaseErrorHandler errorHandler) { - return null; - } - - @Override - public boolean moveDatabaseFrom(Context sourceContext, String name) { - return false; - } - - @Override - public boolean deleteDatabase(String name) { - return false; - } - - @Override - public File getDatabasePath(String name) { - return null; - } - - @Override - public String[] databaseList() { - return new String[0]; - } - - @Override - public Drawable getWallpaper() { - return null; - } - - @Override - public Drawable peekWallpaper() { - return null; - } - - @Override - public int getWallpaperDesiredMinimumWidth() { - return 0; - } - - @Override - public int getWallpaperDesiredMinimumHeight() { - return 0; - } - - @Override - public void setWallpaper(Bitmap bitmap) throws IOException { - - } - - @Override - public void setWallpaper(InputStream data) throws IOException { - - } - - @Override - public void clearWallpaper() throws IOException { - - } - - @Override - public void startActivity(Intent intent) { - - } - - @Override - public void startActivity(Intent intent, @Nullable Bundle options) { - - } - - @Override - public void startActivities(Intent[] intents) { - - } - - @Override - public void startActivities(Intent[] intents, Bundle options) { - - } - - @Override - public void startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException { - - } - - @Override - public void startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options) throws IntentSender.SendIntentException { - - } - - @Override - public void sendBroadcast(Intent intent) { - - } - - @Override - public void sendBroadcast(Intent intent, @Nullable String receiverPermission) { - - } - - @Override - public void sendOrderedBroadcast(Intent intent, @Nullable String receiverPermission) { - - } - - @Override - public void sendOrderedBroadcast(@NonNull Intent intent, @Nullable String receiverPermission, @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras) { } - @Override - public void sendBroadcastAsUser(Intent intent, UserHandle user) { - - } - - @Override - public void sendBroadcastAsUser(Intent intent, UserHandle user, @Nullable String receiverPermission) { - - } - - @Override - public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, @Nullable String receiverPermission, BroadcastReceiver - resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras) { - - } - - @Override - public void sendStickyBroadcast(Intent intent) { - - } - - @Override - public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras) { - - } - - @Override - public void removeStickyBroadcast(Intent intent) { - - } - - @Override - public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) { - - } - - @Override - public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, @Nullable String initialData, @Nullable Bundle initialExtras) { - - } - - @Override - public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) { - - } - - @Nullable - @Override - public Intent registerReceiver(@Nullable BroadcastReceiver receiver, IntentFilter filter) { - return null; - } - - @Nullable - @Override - public Intent registerReceiver(@Nullable BroadcastReceiver receiver, IntentFilter filter, int flags) { - return null; - } - - @Nullable - @Override - public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, @Nullable String broadcastPermission, @Nullable Handler scheduler) { - return null; - } - - @Nullable - @Override - public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, @Nullable String broadcastPermission, @Nullable Handler scheduler, int flags) { - return null; - } - - @Override - public void unregisterReceiver(BroadcastReceiver receiver) { - - } - - @Nullable - @Override - public ComponentName startService(Intent service) { - return null; - } - - @Nullable - @Override - public ComponentName startForegroundService(Intent service) { - return null; - } - - @Override - public boolean stopService(Intent service) { - return false; - } - - @Override - public boolean bindService(Intent service, @NonNull ServiceConnection conn, int flags) { - return false; - } - - @Override - public void unbindService(@NonNull ServiceConnection conn) { - - } - - @Override - public boolean startInstrumentation(@NonNull ComponentName className, @Nullable String profileFile, @Nullable Bundle arguments) { - return false; - } - - @Nullable - @Override - public Object getSystemService(@NonNull String name) { - return null; - } - - @Nullable - @Override - public String getSystemServiceName(@NonNull Class serviceClass) { - return null; - } - - @Override - public int checkPermission(@NonNull String permission, int pid, int uid) { - return 0; - } - - @Override - public int checkCallingPermission(@NonNull String permission) { - return 0; - } - - @Override - public int checkCallingOrSelfPermission(@NonNull String permission) { - return 0; - } - - @Override - public int checkSelfPermission(@NonNull String permission) { - return 0; - } - - @Override - public void enforcePermission(@NonNull String permission, int pid, int uid, @Nullable String message) { - - } - - @Override - public void enforceCallingPermission(@NonNull String permission, @Nullable String message) { - - } - - @Override - public void enforceCallingOrSelfPermission(@NonNull String permission, @Nullable String message) { - - } - - @Override - public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { - - } - - @Override - public void revokeUriPermission(Uri uri, int modeFlags) { - - } - - @Override - public void revokeUriPermission(String toPackage, Uri uri, int modeFlags) { - - } - - @Override - public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { - return 0; - } - - @Override - public int checkCallingUriPermission(Uri uri, int modeFlags) { - return 0; - } - - @Override - public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { - return 0; - } - - @Override - public int checkUriPermission(@Nullable Uri uri, @Nullable String readPermission, @Nullable String writePermission, int pid, int uid, int modeFlags) { - return 0; - } - - @Override - public void enforceUriPermission(Uri uri, int pid, int uid, int modeFlags, String message) { - - } - - @Override - public void enforceCallingUriPermission(Uri uri, int modeFlags, String message) { - - } - - @Override - public void enforceCallingOrSelfUriPermission(Uri uri, int modeFlags, String message) { - - } - - @Override - public void enforceUriPermission(@Nullable Uri uri, @Nullable String readPermission, @Nullable String writePermission, int pid, int uid, int modeFlags, @Nullable String message) { - - } - - @Override - public Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException { - return null; - } - - @Override - public Context createContextForSplit(String splitName) throws PackageManager.NameNotFoundException { - return null; - } - - @Override - public Context createConfigurationContext(@NonNull Configuration overrideConfiguration) { - return null; - } - - @Override - public Context createDisplayContext(@NonNull Display display) { - return null; - } - - @Override - public Context createDeviceProtectedStorageContext() { - return null; - } - - @Override - public boolean isDeviceProtectedStorage() { - return false; - } - } - diff --git a/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockRemoteFile.java b/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockRemoteFile.java deleted file mode 100644 index 94df626d..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockRemoteFile.java +++ /dev/null @@ -1,7 +0,0 @@ -package foundation.e.drive.unitTest.mockObject; - -import com.owncloud.android.lib.resources.files.model.RemoteFile; - -public class mockRemoteFile extends RemoteFile { - public mockRemoteFile(){}; -} diff --git a/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockSfs.java b/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockSfs.java deleted file mode 100644 index 5e58d68c..00000000 --- a/app/src/test/java/foundation/e/drive/unitTest/mockObject/mockSfs.java +++ /dev/null @@ -1,7 +0,0 @@ -package foundation.e.drive.unitTest.mockObject; - -import foundation.e.drive.models.SyncedFileState; - -public class mockSfs extends SyncedFileState { - public mockSfs(){} -} -- GitLab From 836ace8f998e6e1bdde1e0ccd362d4d47a47e69b Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 19 Apr 2021 09:38:53 +0200 Subject: [PATCH 23/60] fix path for test result in CI test job --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6c031797..e61c2f22 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -23,7 +23,7 @@ test: artifacts: when: always reports: - junit: app/build/test-results/testReleaseUnitTest/**/TEST-*.xml + junit: app/build/test-results/testReleaseUnitTest/TEST-*.xml build: -- GitLab From 4426f1595d026adb181dfdfb9db4357783246273 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 19 Apr 2021 11:18:08 +0200 Subject: [PATCH 24/60] fix CI test jobs to get result as expected --- .gitlab-ci.yml | 2 +- app/build.gradle | 10 ++++++---- .../e/drive/services/ObserverServiceTest.java | 9 ++++++++- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e61c2f22..76dcd095 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -23,7 +23,7 @@ test: artifacts: when: always reports: - junit: app/build/test-results/testReleaseUnitTest/TEST-*.xml + junit: app/build/test-results/testDebugUnitTest/TEST-*.xml build: diff --git a/app/build.gradle b/app/build.gradle index d84d464a..840ca816 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -9,7 +9,6 @@ def buildTime() { return df.format(new Date()) } - android { compileSdkVersion 26 defaultConfig { @@ -36,8 +35,12 @@ android { testOptions { - unitTests.returnDefaultValues = true + unitTests { + returnDefaultValues = true + //includeAndroidResources = true + } } + } @@ -59,8 +62,7 @@ dependencies { testImplementation 'com.android.support.test:rules:1.0.2' testImplementation 'junit:junit:4.12' //testImplementation 'org.robolectric:robolectric:4.4' //need AndroidX - testCompile "org.robolectric:robolectric:3.8" - //testImplementation "org.mockito:mockito-core:2.19.0" + testImplementation "org.robolectric:robolectric:3.8" testImplementation('org.mockito:mockito-inline:3.4.0') //testImplementation Libs.AndroidX.Test.archCoreTesting //TODO: replace by not android X version diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index 8bbe32fe..0ec3f3e2 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -10,6 +10,7 @@ import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; +import android.os.Build; import android.support.test.runner.AndroidJUnit4; import com.owncloud.android.lib.common.OwnCloudClient; @@ -21,12 +22,14 @@ import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.android.controller.ServiceController; +import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowNetworkInfo; import java.io.File; import java.util.List; +import foundation.e.drive.BuildConfig; import foundation.e.drive.database.DbHelper; import foundation.e.drive.jobs.ScannerJob; import foundation.e.drive.models.SyncedFolder; @@ -42,9 +45,13 @@ import static foundation.e.drive.utils.AppConstants.SETTINGSYNC_PROVIDER_AUTHORI import static foundation.e.drive.utils.JobUtils.ScannerJobId; import static org.robolectric.Shadows.shadowOf; +import org.robolectric.RobolectricTestRunner; -@RunWith(AndroidJUnit4.class) +//@RunWith(AndroidJUnit4.class) +@RunWith(RobolectricTestRunner.class) +@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.O, manifest = Config.NONE) public class ObserverServiceTest { + private static final String TEST_SERVER_URI ="https://eeo.one"; private final static String TEST_ACCOUNT_TYPE ="eelo"; private final static String TEST_ACCOUNT_NAME="edrivetesting1"; -- GitLab From cde759f1c3ffe298b146c4bfe5fa69de468df11b Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 19 Apr 2021 11:24:58 +0200 Subject: [PATCH 25/60] fix path to test result --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 76dcd095..e61c2f22 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -23,7 +23,7 @@ test: artifacts: when: always reports: - junit: app/build/test-results/testDebugUnitTest/TEST-*.xml + junit: app/build/test-results/testReleaseUnitTest/TEST-*.xml build: -- GitLab From e423846d2c441e062e4f80458e9d414edd8ddd58 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 19 Apr 2021 15:13:34 +0200 Subject: [PATCH 26/60] add allow-failure for test job in CI --- .gitlab-ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e61c2f22..0a4901ad 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -17,6 +17,7 @@ cache: test: + allow_failure: true stage: test script: - ./gradlew test -- GitLab From 89e12c1ad1b8c2f83f56bfe282ebbbe7c667c57c Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Tue, 20 Apr 2021 16:31:23 +0200 Subject: [PATCH 27/60] refactor test class, add a common abstract class for service test and start to implement basic test for OperationManagerService --- .../e/drive/services/AbstractServiceIT.java | 167 ++++++++++++++++++ .../services/InitializerServiceTest.java | 38 ++++ .../services/InitializerServiceUnitTest.java | 35 ---- .../e/drive/services/ObserverServiceTest.java | 144 ++++++--------- .../services/OperationManagerServiceTest.java | 109 ++++++++++++ 5 files changed, 364 insertions(+), 129 deletions(-) create mode 100644 app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java create mode 100644 app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java delete mode 100644 app/src/test/java/foundation/e/drive/services/InitializerServiceUnitTest.java create mode 100644 app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java diff --git a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java new file mode 100644 index 00000000..c2cdd2ce --- /dev/null +++ b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java @@ -0,0 +1,167 @@ +package foundation.e.drive.services; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.app.Service; +import android.app.job.JobScheduler; +import android.content.ContentResolver; +import android.content.Context; +import android.content.SharedPreferences; +import android.net.ConnectivityManager; +import android.os.Build; + +import com.owncloud.android.lib.common.OwnCloudClient; +import com.owncloud.android.lib.common.network.CertificateCombinedException; +import com.owncloud.android.lib.common.network.NetworkUtils; +import com.owncloud.android.lib.common.operations.RemoteOperationResult; +import com.owncloud.android.lib.common.utils.Log_OC; +import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation; + +import org.junit.BeforeClass; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.android.controller.ServiceController; +import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowLog; + +import java.io.IOException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import foundation.e.drive.BuildConfig; +import foundation.e.drive.database.DbHelper; + +import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; +import static foundation.e.drive.utils.AppConstants.MEDIASYNC_PROVIDER_AUTHORITY; +import static foundation.e.drive.utils.AppConstants.SETTINGSYNC_PROVIDER_AUTHORITY; +import static org.robolectric.Shadows.shadowOf; + + +@RunWith(RobolectricTestRunner.class) +@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.O, manifest = Config.NONE) +public abstract class AbstractServiceIT { + protected final static String TEST_SERVER_URI ="https://eeo.one"; + protected final static String TEST_ACCOUNT_TYPE ="eelo"; + protected final static String TEST_ACCOUNT_NAME="edrivetesting1@eeo.one"; + + /** + * By making the below field static it is done once + * for all test class that extends this instead of + * one time by class. + */ + protected static Context context; + protected static Account validAccount; + + protected T mService; + protected ServiceController mServiceController; + + protected AccountManager accountManager; + protected ContentResolver contentResolver; + protected SharedPreferences sharedPreferences; + protected ConnectivityManager connectivityManager; + protected JobScheduler jobScheduler; + protected DbHelper dbHelper; + + protected int initial_folder_number=0; + protected long last_sync_time=0l; + protected boolean init_done = true; + protected boolean oms_running=false; + + @BeforeClass + public static void beforeAll(){ + ShadowLog.stream = System.out; //give access to log + } + + + /** + * Test the connexion to the server + * Add the certificate to the knownServerCertificateStore if required + * @throws KeyStoreException + * @throws CertificateException + * @throws NoSuchAlgorithmException + * @throws IOException + * @throws InterruptedException + */ + protected static void testConnection(OwnCloudClient client) throws KeyStoreException, + CertificateException, + NoSuchAlgorithmException, + IOException, + InterruptedException{ + + GetRemoteStatusOperation getStatus = new GetRemoteStatusOperation(context); + + RemoteOperationResult result = getStatus.execute(client); + + if (result.isSuccess()) { + Log_OC.d("AbstractIT", "Connection to server successful"); + } else { + if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(result.getCode())) { + Log_OC.d("AbstractIT", "Accepting certificate"); + + CertificateCombinedException exception = (CertificateCombinedException) result.getException(); + X509Certificate certificate = exception.getServerCertificate(); + + NetworkUtils.addCertToKnownServersStore(certificate, context); + Thread.sleep(1000); + + // retry + getStatus = new GetRemoteStatusOperation(context); + result = getStatus.execute(client); + + if (!result.isSuccess()) { + throw new RuntimeException("No connection to server possible, even with accepted cert"); + } + + } else { + throw new RuntimeException("No connection to server possible"); + } + } + } + + + /** + * Create and register one validAccount + */ + protected void prepareValidAccount(){ + validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type + shadowOf(accountManager).addAccount(validAccount); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... + shadowOf(accountManager).setPassword(validAccount, "iY8kKhJufPxTr2F"); + //shadowOf(accountManager).setPassword(validAccount, "REPLACEATRUNTIMR"); + //shadowOf(accountManager).setAuthToken(validAccount, "dontknowWhatToDo", "REPLACEATRUNTIMR"); //This is to add the token of the account + shadowOf(accountManager).setUserData(validAccount, KEY_OC_BASE_URL, TEST_SERVER_URI); + } + + /** + * enable Media & settings sync + */ + protected void enableMediaAndSettingsSync(){ //replace this by robolectric the contentResolver + contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); + contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, true); + } + + /** + * disable Media & enable settings sync + */ + protected void disableMediaSync(){ //replace this by robolectric the contentResolver + contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, false); + contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, true); + } + + /** + * enable Media and disable settings sync + */ + protected void disableSettingsSync(){ //replace this by robolectric the contentResolver + contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); + contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, false); + } + + /** + * disable Media & settings sync + */ + protected void disableMediaAndSettingsSync(){ //replace this by robolectric the contentResolver + contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, false); + contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, false); + } +} diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java new file mode 100644 index 00000000..10a7f238 --- /dev/null +++ b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java @@ -0,0 +1,38 @@ +package foundation.e.drive.services; + + +import android.accounts.AccountManager; +import android.app.job.JobScheduler; +import android.content.Context; +import android.net.ConnectivityManager; + +import junit.framework.Assert; + +import org.junit.Test; +import org.robolectric.Robolectric; +import org.robolectric.RuntimeEnvironment; + +import foundation.e.drive.database.DbHelper; +import foundation.e.drive.utils.AppConstants; + +public class InitializerServiceTest extends AbstractServiceIT{ + + public InitializerServiceTest(){ + + mServiceController = Robolectric.buildService(InitializerService.class); + mService = mServiceController.get(); + context = RuntimeEnvironment.application; + accountManager = AccountManager.get(context); + jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); + contentResolver = context.getContentResolver(); + sharedPreferences = context.getSharedPreferences( AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); + connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + dbHelper = new DbHelper(context); + } + + @Test + public void assertFails(){ + Assert.fail(); + } + +} diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceUnitTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceUnitTest.java deleted file mode 100644 index 48dc732c..00000000 --- a/app/src/test/java/foundation/e/drive/services/InitializerServiceUnitTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package foundation.e.drive.services; - -import android.accounts.AccountManager; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; - -import org.junit.Test; -import org.mockito.Mockito; - -import foundation.e.drive.utils.AppConstants; - -public class InitializerServiceUnitTest { - private final static String TEST_ACCOUNT_TYPE =""; - private final static String TEST_ACCOUNT_NAME=""; - - @Test - public void onStartCommand() { - final Intent intent = Mockito.mock(Intent.class); - final SharedPreferences sharedPrefs = Mockito.mock(SharedPreferences.class); - final Context context = Mockito.mock(Context.class); - - - Mockito.when(context.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE)).thenReturn(sharedPrefs); - - Mockito.when(sharedPrefs.getBoolean(AppConstants.INITIALIZATION_HAS_BEEN_DONE, false)).thenReturn(false); - Mockito.when(sharedPrefs.getString(AccountManager.KEY_ACCOUNT_NAME, "" )).thenReturn(TEST_ACCOUNT_NAME); - Mockito.when(sharedPrefs.getString(AccountManager.KEY_ACCOUNT_TYPE, "" )).thenReturn(TEST_ACCOUNT_TYPE); - } - - - @Test - public void onRemoteOperationFinish() { - } -} diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index 0ec3f3e2..abc056ae 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -1,35 +1,27 @@ package foundation.e.drive.services; -import android.accounts.Account; import android.accounts.AccountManager; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; -import android.content.ContentResolver; import android.content.Context; -import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; -import android.os.Build; -import android.support.test.runner.AndroidJUnit4; import com.owncloud.android.lib.common.OwnCloudClient; +import com.owncloud.android.lib.common.operations.RemoteOperationResult; import junit.framework.Assert; -import org.junit.Before; + import org.junit.Test; -import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; -import org.robolectric.android.controller.ServiceController; -import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowNetworkInfo; import java.io.File; import java.util.List; -import foundation.e.drive.BuildConfig; import foundation.e.drive.database.DbHelper; import foundation.e.drive.jobs.ScannerJob; import foundation.e.drive.models.SyncedFolder; @@ -37,60 +29,30 @@ import foundation.e.drive.operations.CreateInitialFolderRemoteOperation; import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; -import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; import static foundation.e.drive.utils.AppConstants.INITIALIZATION_HAS_BEEN_DONE; -import static foundation.e.drive.utils.AppConstants.MEDIASYNC_PROVIDER_AUTHORITY; import static foundation.e.drive.utils.AppConstants.MEDIA_SYNCABLE_CATEGORIES; -import static foundation.e.drive.utils.AppConstants.SETTINGSYNC_PROVIDER_AUTHORITY; import static foundation.e.drive.utils.JobUtils.ScannerJobId; import static org.robolectric.Shadows.shadowOf; -import org.robolectric.RobolectricTestRunner; + //@RunWith(AndroidJUnit4.class) -@RunWith(RobolectricTestRunner.class) -@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.O, manifest = Config.NONE) -public class ObserverServiceTest { - - private static final String TEST_SERVER_URI ="https://eeo.one"; - private final static String TEST_ACCOUNT_TYPE ="eelo"; - private final static String TEST_ACCOUNT_NAME="edrivetesting1"; - //private final static String PROD_ACCOUNT_NAME="vincent.bourgmayer@e.email"; - private int initial_folder_number=0; - private long last_sync_time=0l; - private boolean init_done = true; - private boolean oms_running=false; - - private ObserverService myService; - private ServiceController mServiceController; - //Stuff Below could be defined in a abstractClass which would be extends by other test class - private JobScheduler jobScheduler; - private AccountManager accountManager; - private Account validAccount; - private ConnectivityManager connectivityManager; - private ContentResolver contentResolver; - private SharedPreferences sharedPreferences; - - //private Handler handler; //Trial for SSL issue with remote folder creation - - @Before - public void setUp(){ - //Note: May be the SharedPrefs part could be created with robolectric instead of mockito.. - ShadowLog.stream = System.out; //give access to log - - accountManager = AccountManager.get(RuntimeEnvironment.application); - connectivityManager = (ConnectivityManager) RuntimeEnvironment.application .getSystemService(Context.CONNECTIVITY_SERVICE); - jobScheduler = (JobScheduler) RuntimeEnvironment.application.getSystemService(Context.JOB_SCHEDULER_SERVICE); - contentResolver = RuntimeEnvironment.application.getContentResolver(); - sharedPreferences = RuntimeEnvironment.application.getSharedPreferences( - AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); - DbHelper helper = new DbHelper(RuntimeEnvironment.application); +public class ObserverServiceTest extends AbstractServiceIT { + public ObserverServiceTest(){ mServiceController = Robolectric.buildService(ObserverService.class); - myService = mServiceController.get(); + mService = mServiceController.get(); + context = RuntimeEnvironment.application; + accountManager = AccountManager.get(context); + jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); + contentResolver = context.getContentResolver(); + sharedPreferences = context.getSharedPreferences( AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); + connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + dbHelper = new DbHelper(context); } + /** * Register all the preferences in SharedPref object */ @@ -104,25 +66,13 @@ public class ObserverServiceTest { .commit(); } - /** - * Create and register one validAccount - */ - private void prepareValidAccount(){ - validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type - shadowOf(accountManager).addAccount(validAccount); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... - shadowOf(accountManager).setPassword(validAccount, "REPLACEATRUNTIMR"); - //shadowOf(accountManager).setAuthToken(validAccount, "dontknowWhatToDo", "REPLACEATRUNTIMR"); - shadowOf(accountManager).setUserData(validAccount, KEY_OC_BASE_URL, TEST_SERVER_URI); - } /** * Schedule a ScannerJob instance in JobScheduler */ private void registerScannerJobInJobScheduler(){ - ComponentName jobService = new ComponentName( RuntimeEnvironment.application, ScannerJob.class ); - - + ComponentName jobService = new ComponentName( context, ScannerJob.class ); Assert.assertNotNull(jobService); //Creating the job like in ScannerJob class isn't possible because Robolectric doesn't @@ -157,36 +107,28 @@ public class ObserverServiceTest { shadowOf(connectivityManager).setActiveNetworkInfo(netInfo); } + /** + * Create a network status where no connection is available + */ private void setUnavailableWifiNetworkStatus(){ - //Try to remove the two default Network available that are "MOBILE" and "CONNECTED" - //But doesn't work... - - //shadowOf(connectivityManager).clearAllNetworks(); + //shadowOf(connectivityManager).clearAllNetworks(); // doesn't work... /*for(Network network : shadowOf (connectivityManager).getAllNetworks()){ - shadowOf(connectivityManager).removeNetwork(network); + shadowOf(connectivityManager).removeNetwork(network); // doesn't work... }*/ NetworkInfo netInfo = ShadowNetworkInfo.newInstance(null, ConnectivityManager.TYPE_WIFI, 0, true, NetworkInfo.State.DISCONNECTED); Assert.assertEquals("NetworkInfo type is invalid",ConnectivityManager.TYPE_WIFI,netInfo.getType()); - shadowOf(connectivityManager).setActiveNetworkInfo(netInfo); } - /** - * enable Media & settings sync + * Create a single 'SyncedFolder' instance for 'eDrive-test' folder + * @return */ - private void enableMediaAndSettingsSync(){ //replace this by robolectric the contentResolver - contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); - contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, true); - } - - private SyncedFolder createSingleTestSyncedFolder(){ - //handler = new Handler(); final String watchedFolderLocalPath = "/tmp/eDrive/test/"; final String watchedFolderRemotePath="/eDrive-test/"; final File folder = new File(watchedFolderLocalPath); @@ -194,38 +136,54 @@ public class ObserverServiceTest { final SyncedFolder sFolder = new SyncedFolder(MEDIA_SYNCABLE_CATEGORIES[0], watchedFolderLocalPath, watchedFolderRemotePath, true); return sFolder; - } - private void createRemoteSyncedFolder(SyncedFolder folder){ - OwnCloudClient client = CommonUtils.getOwnCloudClient(validAccount, RuntimeEnvironment.application); - CreateInitialFolderRemoteOperation op = new CreateInitialFolderRemoteOperation(folder, true, RuntimeEnvironment.application); - op.execute(client); //Give SSL issue - //op.execute(client, myService, this.handler); - //op.execute(client, true); - //op.execute(validAccount, RuntimeEnvironment.application); + /** + * Send request to server to create the remote folder of the given syncedFolder + * @param folder the local folder metadata to create + */ + private void createRemoteFolder(SyncedFolder folder){ + OwnCloudClient client = CommonUtils.getOwnCloudClient(validAccount, context); + + try { + testConnection(client); + }catch(Exception e){ + System.out.println("Test connection failed :"+e.getMessage()); + } + + CreateInitialFolderRemoteOperation op = new CreateInitialFolderRemoteOperation(folder, true, context); + RemoteOperationResult result = op.execute(client); //Give SSL issue + + Assert.assertTrue("Creation of remote test folder failed",result.isSuccess()); //Assert.assertTrue(folderList.contains(sFolder)); initial_folder_number =1; } + /** + * Run a test which correspond to a non blocking context + */ @Test public void shouldWork() { setWifiNetworkStatus(); prepareValidAccount(); enableMediaAndSettingsSync(); - //createRemoteSyncedFolder(createSingleTestSyncedFolder()); + createRemoteFolder(createSingleTestSyncedFolder()); registerScannerJobInJobScheduler(); registerSharedPref(); //Start the service mServiceController.create().startCommand(0, 0); - //@TODO add assertion! - Assert.fail("NO Assertion here!"); + List logs = ShadowLog.getLogs(); + ShadowLog.LogItem lastLog = logs.get(logs.size()-2); + + Assert.assertEquals("expected: 'Going to scan remote files' but found: '"+lastLog.msg, "Going to scan remote files", lastLog.msg); + //Tear down + mService.deleteDatabase(DbHelper.DATABASE_NAME); //Assert.assertTrue("Database hasn't been removed", myService.deleteDatabase(DbHelper.DATABASE_NAME)); } @@ -336,8 +294,6 @@ public class ObserverServiceTest { Assert.assertFalse("SharedPref doesn't contains the expected value for Initialization_has_been_done key", sharedPreferences.getBoolean(INITIALIZATION_HAS_BEEN_DONE, true)); mServiceController.create().startCommand(0, 0); - - //How to assert this... ? List logs = ShadowLog.getLogs(); @@ -348,6 +304,6 @@ public class ObserverServiceTest { //Assert.assertTrue(logs.contains()); //@TODO how to assert that logs doesn't contain the expecteed message ? //tearDown - Remove DB if it had been created - myService.deleteDatabase(DbHelper.DATABASE_NAME); + mService.deleteDatabase(DbHelper.DATABASE_NAME); } } \ No newline at end of file diff --git a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java new file mode 100644 index 00000000..29cb6385 --- /dev/null +++ b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java @@ -0,0 +1,109 @@ +package foundation.e.drive.services; + +import android.accounts.AccountManager; +import android.app.job.JobScheduler; +import android.content.Context; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.os.Bundle; +import android.os.Parcelable; + +import com.owncloud.android.lib.resources.files.model.RemoteFile; + +import junit.framework.Assert; + +import org.junit.Test; +import org.robolectric.Robolectric; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.shadows.ShadowLog; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import foundation.e.drive.database.DbHelper; +import foundation.e.drive.models.SyncedFileState; +import foundation.e.drive.operations.DownloadFileOperation; +import foundation.e.drive.utils.AppConstants; + + +public class OperationManagerServiceTest extends AbstractServiceIT{ + + public OperationManagerServiceTest(){ + mServiceController = Robolectric.buildService(OperationManagerService.class); + mService = mServiceController.get(); + context = RuntimeEnvironment.application; + accountManager = AccountManager.get(context); + jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); + contentResolver = context.getContentResolver(); + sharedPreferences = context.getSharedPreferences( AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); + connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + dbHelper = new DbHelper(context); + } + + + /** + * Check that the service stop quickly if no intent is provided + */ + @Test + public void noIntent_shouldStop(){ + mServiceController.create(); + mService.onStartCommand(null,0, 0); + + List logs = ShadowLog.getLogs(); + ShadowLog.LogItem lastLog = logs.get(logs.size()-2); + + Assert.assertEquals("Expected last log was: 'intent was null, flags=0 bits=0' but got:"+lastLog, "intent was null, flags=0 bits=0", lastLog.msg); + } + + + /** + * Start the service with an intent that doesn't contains list of extra data + * (meaning no account and no synchronisation to perform) + */ + @Test + public void intentWithoutExtras_shouldStop(){ + mServiceController.create(); + mService.onStartCommand(new Intent(), 0, 0); + + List logs = ShadowLog.getLogs(); + ShadowLog.LogItem lastLog = logs.get(logs.size()-1); + + Assert.assertEquals("Expected last log was: 'Intent's extras is null.' but got:"+lastLog, "Intent's extras is null.", lastLog.msg); + } + + + /** + * Start the OperationmanagerService with File to upload but no account provided + * in the intent. + * Failure is expected + */ + @Test + public void noAccount_shouldFail(){ + prepareValidAccount(); + Intent intent = new Intent("dummyAction"); + + intent.putExtra("0", + new DownloadFileOperation( + new RemoteFile("/eDrive-test/coco.txt"), + new SyncedFileState(3, "coco.txt", "/tmp/eDrive-test/", "/eDrive-test/coco.txt","", -1, 1, true ) + ) + ); + + + intent.putExtra("account", validAccount); + + boolean accountRemoved = accountManager.removeAccountExplicitly(validAccount); + Assert.assertTrue("Account removal should return true but returned false", accountRemoved); + + mServiceController.create(); + mService.onStartCommand(intent, 0,0); + + List logs = ShadowLog.getLogs(); + ShadowLog.LogItem lastLog = logs.get(logs.size()-1); + Assert.assertEquals("Expected last log was: 'No Client, Can't Work!' but got:"+lastLog, "No Client, Can't Work!", lastLog.msg); + + } + + +} -- GitLab From 8ea7ef18366483fcc6c9450224712bea02b95c23 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Tue, 20 Apr 2021 18:48:56 +0200 Subject: [PATCH 28/60] update test for OMS --- .../e/drive/services/OperationManagerServiceTest.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java index 29cb6385..dfa0593e 100644 --- a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java @@ -5,8 +5,6 @@ import android.app.job.JobScheduler; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; -import android.os.Bundle; -import android.os.Parcelable; import com.owncloud.android.lib.resources.files.model.RemoteFile; @@ -17,9 +15,7 @@ import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowLog; -import java.util.HashMap; import java.util.List; -import java.util.Map; import foundation.e.drive.database.DbHelper; import foundation.e.drive.models.SyncedFileState; @@ -53,7 +49,7 @@ public class OperationManagerServiceTest extends AbstractServiceIT logs = ShadowLog.getLogs(); ShadowLog.LogItem lastLog = logs.get(logs.size()-2); - Assert.assertEquals("Expected last log was: 'intent was null, flags=0 bits=0' but got:"+lastLog, "intent was null, flags=0 bits=0", lastLog.msg); + Assert.assertEquals("Expected last log was: 'intent was null, flags=0 bits=0' but got:"+lastLog.msg, "intent was null, flags=0 bits=0", lastLog.msg); } @@ -69,7 +65,7 @@ public class OperationManagerServiceTest extends AbstractServiceIT logs = ShadowLog.getLogs(); ShadowLog.LogItem lastLog = logs.get(logs.size()-1); - Assert.assertEquals("Expected last log was: 'Intent's extras is null.' but got:"+lastLog, "Intent's extras is null.", lastLog.msg); + Assert.assertEquals("Expected last log was: 'Intent's extras is null.' but got:"+lastLog.msg, "Intent's extras is null.", lastLog.msg); } @@ -101,7 +97,7 @@ public class OperationManagerServiceTest extends AbstractServiceIT logs = ShadowLog.getLogs(); ShadowLog.LogItem lastLog = logs.get(logs.size()-1); - Assert.assertEquals("Expected last log was: 'No Client, Can't Work!' but got:"+lastLog, "No Client, Can't Work!", lastLog.msg); + Assert.assertEquals("Expected last log was: 'No Client, Can't Work!' but got:"+lastLog.msg, "No Client, Can't Work!", lastLog.msg); } -- GitLab From 41abc48828d33688bfc6a903dfdbd51a7b4d2b68 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 21 Apr 2021 13:31:40 +0200 Subject: [PATCH 29/60] make ServerCredential dependant of the context --- app/build.gradle | 15 ++++++++++++- .../e/drive/services/AbstractServiceIT.java | 22 ++++++++++++++----- .../e/drive/services/ObserverServiceTest.java | 8 +++---- 3 files changed, 35 insertions(+), 10 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 840ca816..da9aae76 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -9,6 +9,17 @@ def buildTime() { return df.format(new Date()) } +def getTestProp(String propName) { + def result =System.getProperty(propName, ""); + if (result.isEmpty()){ + Properties properties = new Properties() + properties.load(project.rootProject.file('local.properties').newDataInputStream()) + result = properties.getProperty(propName); + } + return result; +} + + android { compileSdkVersion 26 defaultConfig { @@ -20,7 +31,9 @@ android { setProperty("archivesBaseName", "$applicationId.$versionName") testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testBuildType System.getProperty('testBuildType', 'debug') - + buildConfigField "String", "testAccountName", "\""+getTestProp("testAccountName")+"\"" + buildConfigField "String", "testAccountPWd", "\""+getTestProp("testAccountPWd")+"\"" + buildConfigField "String", "testServerUrl", "\""+getTestProp("testServerUrl")+"\"" } buildTypes { release { diff --git a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java index c2cdd2ce..a4b3d9b8 100644 --- a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java +++ b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java @@ -42,10 +42,10 @@ import static org.robolectric.Shadows.shadowOf; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.O, manifest = Config.NONE) public abstract class AbstractServiceIT { - protected final static String TEST_SERVER_URI ="https://eeo.one"; - protected final static String TEST_ACCOUNT_TYPE ="eelo"; - protected final static String TEST_ACCOUNT_NAME="edrivetesting1@eeo.one"; - + protected static String TEST_ACCOUNT_TYPE ="eelo"; + protected static String TEST_SERVER_URI; + protected static String TEST_ACCOUNT_NAME; + protected static String TEST_ACCOUNT_PASSWORD; /** * By making the below field static it is done once * for all test class that extends this instead of @@ -71,10 +71,22 @@ public abstract class AbstractServiceIT { @BeforeClass public static void beforeAll(){ + loadServerCredentials(); ShadowLog.stream = System.out; //give access to log } + private static void loadServerCredentials(){ + TEST_ACCOUNT_PASSWORD = System.getProperty("testPwd", ""); + TEST_ACCOUNT_NAME = System.getProperty("testAccountName",""); + TEST_SERVER_URI = System.getProperty("serverUrl", ""); + + + if(TEST_ACCOUNT_PASSWORD.isEmpty()) TEST_ACCOUNT_PASSWORD = BuildConfig.testAccountPWd; + if(TEST_ACCOUNT_NAME.isEmpty()) TEST_ACCOUNT_NAME = BuildConfig.testAccountName; + if(TEST_SERVER_URI.isEmpty()) TEST_SERVER_URI = BuildConfig.testServerUrl; + } + /** * Test the connexion to the server * Add the certificate to the knownServerCertificateStore if required @@ -127,7 +139,7 @@ public abstract class AbstractServiceIT { protected void prepareValidAccount(){ validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type shadowOf(accountManager).addAccount(validAccount); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... - shadowOf(accountManager).setPassword(validAccount, "iY8kKhJufPxTr2F"); + shadowOf(accountManager).setPassword(validAccount, "aFcHm-3msyc-eqCCi-5fW9x-XksPL"); //shadowOf(accountManager).setPassword(validAccount, "REPLACEATRUNTIMR"); //shadowOf(accountManager).setAuthToken(validAccount, "dontknowWhatToDo", "REPLACEATRUNTIMR"); //This is to add the token of the account shadowOf(accountManager).setUserData(validAccount, KEY_OC_BASE_URL, TEST_SERVER_URI); diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index abc056ae..46800d8d 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -34,9 +34,9 @@ import static foundation.e.drive.utils.AppConstants.MEDIA_SYNCABLE_CATEGORIES; import static foundation.e.drive.utils.JobUtils.ScannerJobId; import static org.robolectric.Shadows.shadowOf; - - -//@RunWith(AndroidJUnit4.class) +/** + * The RunWith & Config annotation are done in the AbstractServiceIT + */ public class ObserverServiceTest extends AbstractServiceIT { public ObserverServiceTest(){ @@ -178,7 +178,7 @@ public class ObserverServiceTest extends AbstractServiceIT { mServiceController.create().startCommand(0, 0); List logs = ShadowLog.getLogs(); - ShadowLog.LogItem lastLog = logs.get(logs.size()-2); + ShadowLog.LogItem lastLog = logs.get(logs.size()-3); Assert.assertEquals("expected: 'Going to scan remote files' but found: '"+lastLog.msg, "Going to scan remote files", lastLog.msg); -- GitLab From e1dae4b015d69c770826311859828de9e50350dd Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 21 Apr 2021 14:01:18 +0200 Subject: [PATCH 30/60] fix Gradle build and gradle test --- app/build.gradle | 2 +- .../e/drive/services/AbstractServiceIT.java | 3 +++ .../e/drive/services/ObserverServiceTest.java | 12 ++++++------ 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index da9aae76..1d227ecf 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -10,7 +10,7 @@ def buildTime() { } def getTestProp(String propName) { - def result =System.getProperty(propName, ""); + def result =System.getenv(propName, ""); if (result.isEmpty()){ Properties properties = new Properties() properties.load(project.rootProject.file('local.properties').newDataInputStream()) diff --git a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java index a4b3d9b8..2c804e41 100644 --- a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java +++ b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java @@ -46,6 +46,9 @@ public abstract class AbstractServiceIT { protected static String TEST_SERVER_URI; protected static String TEST_ACCOUNT_NAME; protected static String TEST_ACCOUNT_PASSWORD; + + protected static final String TEST_LOCAL_ROOT_FOLDER_PATH = "/tmp/eDrive/test/"; //THis is where test file and folder for synchronisatio will be stored + protected static final String TEST_REMOTE_ROOT_FOLDER_PATH ="/eDrive-test/"; /** * By making the below field static it is done once * for all test class that extends this instead of diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index 46800d8d..37b78d17 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -40,7 +40,6 @@ import static org.robolectric.Shadows.shadowOf; public class ObserverServiceTest extends AbstractServiceIT { public ObserverServiceTest(){ - mServiceController = Robolectric.buildService(ObserverService.class); mService = mServiceController.get(); context = RuntimeEnvironment.application; @@ -129,11 +128,9 @@ public class ObserverServiceTest extends AbstractServiceIT { * @return */ private SyncedFolder createSingleTestSyncedFolder(){ - final String watchedFolderLocalPath = "/tmp/eDrive/test/"; - final String watchedFolderRemotePath="/eDrive-test/"; - final File folder = new File(watchedFolderLocalPath); + final File folder = new File(TEST_LOCAL_ROOT_FOLDER_PATH); folder.mkdirs(); - final SyncedFolder sFolder = new SyncedFolder(MEDIA_SYNCABLE_CATEGORIES[0], watchedFolderLocalPath, watchedFolderRemotePath, true); + final SyncedFolder sFolder = new SyncedFolder(MEDIA_SYNCABLE_CATEGORIES[0], TEST_LOCAL_ROOT_FOLDER_PATH, TEST_REMOTE_ROOT_FOLDER_PATH, true); return sFolder; } @@ -157,7 +154,10 @@ public class ObserverServiceTest extends AbstractServiceIT { Assert.assertTrue("Creation of remote test folder failed",result.isSuccess()); - //Assert.assertTrue(folderList.contains(sFolder)); + final int dbFolderListSize =DbHelper.getAllSyncedFolders(context).size(); + Assert.assertEquals("Expected DB's SyncedFolder table content was 1, but got:"+dbFolderListSize, 1, dbFolderListSize); + + initial_folder_number =1; } -- GitLab From 7d71315647726aae7181e1310406f0ab60438a81 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 21 Apr 2021 14:01:48 +0200 Subject: [PATCH 31/60] update CI to use build and test job with correct parameters --- .gitlab-ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 0a4901ad..9bbec5ca 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -20,7 +20,7 @@ test: allow_failure: true stage: test script: - - ./gradlew test + - ./gradlew test -Pname=$testAccountName -Ppass=$testAccountPWd -Purl=$testServerUrl artifacts: when: always reports: @@ -30,7 +30,7 @@ test: build: stage: build script: - - ./gradlew build + - ./gradlew build -x test artifacts: paths: - app/build/outputs/apk/ -- GitLab From b5c133189c67a78c9604d3720da94a21e7e92d59 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 21 Apr 2021 14:07:35 +0200 Subject: [PATCH 32/60] fix CI job and gradle build --- .gitlab-ci.yml | 4 ++-- app/build.gradle | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 9bbec5ca..3fe298fa 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -20,7 +20,7 @@ test: allow_failure: true stage: test script: - - ./gradlew test -Pname=$testAccountName -Ppass=$testAccountPWd -Purl=$testServerUrl + - ./gradlew test -Pname="$testAccountName" -Ppass="$testAccountPWd" -Purl="$testServerUrl" artifacts: when: always reports: @@ -30,7 +30,7 @@ test: build: stage: build script: - - ./gradlew build -x test + - ./gradlew build -X test artifacts: paths: - app/build/outputs/apk/ diff --git a/app/build.gradle b/app/build.gradle index 1d227ecf..da9aae76 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -10,7 +10,7 @@ def buildTime() { } def getTestProp(String propName) { - def result =System.getenv(propName, ""); + def result =System.getProperty(propName, ""); if (result.isEmpty()){ Properties properties = new Properties() properties.load(project.rootProject.file('local.properties').newDataInputStream()) -- GitLab From e8768947c561d517fa3c59788eab19ccdabd404c Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 21 Apr 2021 15:05:30 +0200 Subject: [PATCH 33/60] fix build.gradle(:app) --- app/build.gradle | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index da9aae76..bb8d1042 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -10,13 +10,16 @@ def buildTime() { } def getTestProp(String propName) { - def result =System.getProperty(propName, ""); - if (result.isEmpty()){ + def result = "" + if(project.hasProperty(propName)){ + result =project.property('key').toString() + } + if(project.rootProject.file('local.properties').exists()){ Properties properties = new Properties() - properties.load(project.rootProject.file('local.properties').newDataInputStream()) - result = properties.getProperty(propName); + properties.load(project.rootProject.file('local.properties').newReader()) + result = properties.getProperty(propName) } - return result; + return result } -- GitLab From b52afc08af18f4f5b29f3d19f1960f6a0ede1e30 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 22 Apr 2021 14:07:05 +0200 Subject: [PATCH 34/60] update gitlab-ci to explore java version --- .gitlab-ci.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 3fe298fa..7472b9c4 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -10,6 +10,7 @@ before_script: - export GRADLE_USER_HOME=$(pwd)/.gradle - chmod +x ./gradlew + cache: key: ${CI_PROJECT_ID} paths: @@ -20,7 +21,9 @@ test: allow_failure: true stage: test script: - - ./gradlew test -Pname="$testAccountName" -Ppass="$testAccountPWd" -Purl="$testServerUrl" + - ls /usr/lib/jvm/ + - echo $JAVA_HOME + - ./gradlew test -Dorg.gradle.java.home=/usr/lib/jvm/java-8-openjdk-amd64D -Pname="${testAccountName}" -Ppass="{$testAccountPWd}" -Purl="${testServerUrl}" artifacts: when: always reports: -- GitLab From bddb642c42d1ec8a2623b0f05900edb80a855b5c Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 22 Apr 2021 14:10:34 +0200 Subject: [PATCH 35/60] update gitlab-ci to fix test execution --- .gitlab-ci.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 7472b9c4..c30c2e62 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -22,8 +22,7 @@ test: stage: test script: - ls /usr/lib/jvm/ - - echo $JAVA_HOME - - ./gradlew test -Dorg.gradle.java.home=/usr/lib/jvm/java-8-openjdk-amd64D -Pname="${testAccountName}" -Ppass="{$testAccountPWd}" -Purl="${testServerUrl}" + - ./gradlew test -Dorg.gradle.java.home=/usr/lib/jvm/java-8-openjdk-amd64 -Pname="${testAccountName}" -Ppass="{$testAccountPWd}" -Purl="${testServerUrl}" artifacts: when: always reports: -- GitLab From 9791bd21d5fa830ea3c2e98cd9cba9639c95aa60 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 22 Apr 2021 14:31:54 +0200 Subject: [PATCH 36/60] fix issue with build and test --- .gitlab-ci.yml | 4 ++-- .../java/foundation/e/drive/services/AbstractServiceIT.java | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c30c2e62..6008778d 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -26,13 +26,13 @@ test: artifacts: when: always reports: - junit: app/build/test-results/testReleaseUnitTest/TEST-*.xml + junit: app/build/test-results/*/TEST-*.xml build: stage: build script: - - ./gradlew build -X test + - ./gradlew build -x test artifacts: paths: - app/build/outputs/apk/ diff --git a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java index 2c804e41..12ce1715 100644 --- a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java +++ b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java @@ -142,8 +142,7 @@ public abstract class AbstractServiceIT { protected void prepareValidAccount(){ validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type shadowOf(accountManager).addAccount(validAccount); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... - shadowOf(accountManager).setPassword(validAccount, "aFcHm-3msyc-eqCCi-5fW9x-XksPL"); - //shadowOf(accountManager).setPassword(validAccount, "REPLACEATRUNTIMR"); + shadowOf(accountManager).setPassword(validAccount, TEST_ACCOUNT_PASSWORD); //shadowOf(accountManager).setAuthToken(validAccount, "dontknowWhatToDo", "REPLACEATRUNTIMR"); //This is to add the token of the account shadowOf(accountManager).setUserData(validAccount, KEY_OC_BASE_URL, TEST_SERVER_URI); } -- GitLab From d6e4c52cfb0f107f41535d04aa66e854b95631ef Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 22 Apr 2021 15:02:56 +0200 Subject: [PATCH 37/60] fix credentials reading from CI --- .gitlab-ci.yml | 2 +- app/build.gradle | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6008778d..6aac946e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -22,7 +22,7 @@ test: stage: test script: - ls /usr/lib/jvm/ - - ./gradlew test -Dorg.gradle.java.home=/usr/lib/jvm/java-8-openjdk-amd64 -Pname="${testAccountName}" -Ppass="{$testAccountPWd}" -Purl="${testServerUrl}" + - ./gradlew test -Dorg.gradle.java.home=/usr/lib/jvm/java-8-openjdk-amd64 -PtestAccountName="${testAccountName}" -PtestAccountPwd="{$testAccountPwd}" -PtestServerUrl="${testServerUrl}" artifacts: when: always reports: diff --git a/app/build.gradle b/app/build.gradle index bb8d1042..8d31ffe8 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -35,7 +35,7 @@ android { testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testBuildType System.getProperty('testBuildType', 'debug') buildConfigField "String", "testAccountName", "\""+getTestProp("testAccountName")+"\"" - buildConfigField "String", "testAccountPWd", "\""+getTestProp("testAccountPWd")+"\"" + buildConfigField "String", "testAccountPWd", "\""+getTestProp("testAccountPwd")+"\"" buildConfigField "String", "testServerUrl", "\""+getTestProp("testServerUrl")+"\"" } buildTypes { -- GitLab From c5cfbbe7ac024f313cf80c23991c7ece7c0149ef Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 22 Apr 2021 15:05:23 +0200 Subject: [PATCH 38/60] fix credentials reading from CI --- app/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/build.gradle b/app/build.gradle index 8d31ffe8..1851e5eb 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,7 +12,7 @@ def buildTime() { def getTestProp(String propName) { def result = "" if(project.hasProperty(propName)){ - result =project.property('key').toString() + result =project.property(propName).toString() } if(project.rootProject.file('local.properties').exists()){ Properties properties = new Properties() -- GitLab From 6dc4b59fdac040670ade11a67832299f9d8a3578 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 22 Apr 2021 16:04:54 +0200 Subject: [PATCH 39/60] add basic test for InitializerService --- .../e/drive/services/AbstractServiceIT.java | 31 +++++++++-- .../services/InitializerServiceTest.java | 54 ++++++++++++++++++- .../e/drive/services/ObserverServiceTest.java | 16 ------ 3 files changed, 80 insertions(+), 21 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java index 12ce1715..acef0631 100644 --- a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java +++ b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java @@ -32,6 +32,7 @@ import java.security.cert.X509Certificate; import foundation.e.drive.BuildConfig; import foundation.e.drive.database.DbHelper; +import foundation.e.drive.utils.AppConstants; import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; import static foundation.e.drive.utils.AppConstants.MEDIASYNC_PROVIDER_AUTHORITY; @@ -67,10 +68,10 @@ public abstract class AbstractServiceIT { protected JobScheduler jobScheduler; protected DbHelper dbHelper; - protected int initial_folder_number=0; - protected long last_sync_time=0l; - protected boolean init_done = true; - protected boolean oms_running=false; + protected int initial_folder_number=0; //number of folders to sync at initialization + protected long last_sync_time=0l; //Timestamp of the end of the last synchronisation + protected boolean init_done = true; //true if InitializerService did its job + protected boolean oms_running=false; //true if OperationManagerService is already running @BeforeClass public static void beforeAll(){ @@ -178,4 +179,26 @@ public abstract class AbstractServiceIT { contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, false); contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, false); } + + /** + * Register sharedPreferences common to all services + * - OMS is working (bool) + * - Account name (String) + * - Account type (String) + * - initial folders number (int) + * - last sync time (long) + * - Initialization has been done (bool) + * + * Use default value of the instance field + * So update the field before to call this to store specific value + */ + protected void registerSharedPref(){ + sharedPreferences.edit().putBoolean( AppConstants.INITIALIZATION_HAS_BEEN_DONE, init_done) + .putBoolean(AppConstants.KEY_OMS_IS_WORKING, oms_running) + .putString(AccountManager.KEY_ACCOUNT_NAME, TEST_ACCOUNT_NAME) + .putString(AccountManager.KEY_ACCOUNT_TYPE, TEST_ACCOUNT_TYPE) + .putInt(AppConstants.INITIALFOLDERS_NUMBER, initial_folder_number) + .putLong(AppConstants.KEY_LAST_SYNC_TIME, last_sync_time) + .commit(); + } } diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java index 10a7f238..043e4c12 100644 --- a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java @@ -11,6 +11,7 @@ import junit.framework.Assert; import org.junit.Test; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; +import org.robolectric.shadows.ShadowLog; import foundation.e.drive.database.DbHelper; import foundation.e.drive.utils.AppConstants; @@ -28,11 +29,62 @@ public class InitializerServiceTest extends AbstractServiceIT { dbHelper = new DbHelper(context); } - - /** - * Register all the preferences in SharedPref object - */ - private void registerSharedPref(){ - sharedPreferences.edit().putBoolean( AppConstants.INITIALIZATION_HAS_BEEN_DONE, init_done) - .putBoolean(AppConstants.KEY_OMS_IS_WORKING, oms_running) - .putString(AccountManager.KEY_ACCOUNT_NAME, TEST_ACCOUNT_NAME) - .putString(AccountManager.KEY_ACCOUNT_TYPE, TEST_ACCOUNT_TYPE) - .putInt(AppConstants.INITIALFOLDERS_NUMBER, initial_folder_number) - .putLong(AppConstants.KEY_LAST_SYNC_TIME, last_sync_time) //Set this value to currentTime to make it fails - .commit(); - } - - - /** * Schedule a ScannerJob instance in JobScheduler */ -- GitLab From 197975747feca411dc084ddf0f825111bef03432 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 23 Apr 2021 14:15:05 +0200 Subject: [PATCH 40/60] update test for initializer service --- .../services/InitializerServiceTest.java | 55 ++++++++++++++++++- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java index 043e4c12..6b7649ea 100644 --- a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java @@ -5,16 +5,33 @@ import android.accounts.AccountManager; import android.app.job.JobScheduler; import android.content.Context; import android.net.ConnectivityManager; +import android.os.Handler; + +import com.owncloud.android.lib.common.OwnCloudClient; +import com.owncloud.android.lib.common.operations.RemoteOperation; +import com.owncloud.android.lib.common.operations.RemoteOperationResult; import junit.framework.Assert; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.jackrabbit.webdav.client.methods.MkColMethod; import org.junit.Test; +import org.mockito.Answers; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowLog; +import org.robolectric.shadows.ShadowLooper; import foundation.e.drive.database.DbHelper; +import foundation.e.drive.operations.CreateInitialFolderRemoteOperation; import foundation.e.drive.utils.AppConstants; +import foundation.e.drive.utils.CommonUtils; + +import static org.robolectric.Shadows.shadowOf; + public class InitializerServiceTest extends AbstractServiceIT{ @@ -69,22 +86,54 @@ public class InitializerServiceTest extends AbstractServiceIT Date: Mon, 26 Apr 2021 17:35:18 +0200 Subject: [PATCH 41/60] start to work on test for file uploading --- .../foundation/e/drive/TestConstants.java | 41 +++++++ .../operations/UploadFileOperationTest.java | 109 ++++++++++++++++++ .../e/drive/services/AbstractServiceIT.java | 37 ++---- .../e/drive/services/ObserverServiceTest.java | 3 + .../services/OperationManagerServiceTest.java | 2 + 5 files changed, 167 insertions(+), 25 deletions(-) create mode 100644 app/src/test/java/foundation/e/drive/TestConstants.java create mode 100644 app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java diff --git a/app/src/test/java/foundation/e/drive/TestConstants.java b/app/src/test/java/foundation/e/drive/TestConstants.java new file mode 100644 index 00000000..7048c68c --- /dev/null +++ b/app/src/test/java/foundation/e/drive/TestConstants.java @@ -0,0 +1,41 @@ +package foundation.e.drive; + +import android.accounts.Account; +import android.accounts.AccountManager; + +import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; +import static org.robolectric.Shadows.shadowOf; + +public abstract class TestConstants { + public static final String TEST_LOCAL_ROOT_FOLDER_PATH = "/tmp/eDrive/test/"; //THis is where test file and folder for synchronisatio will be stored + public static final String TEST_REMOTE_ROOT_FOLDER_PATH ="/eDrive-test/"; + public static String TEST_ACCOUNT_TYPE ="eelo"; + public static String TEST_SERVER_URI; + public static String TEST_ACCOUNT_NAME; + public static String TEST_ACCOUNT_PASSWORD; + public static Account validAccount; + + + public static void loadServerCredentials(){ + TEST_ACCOUNT_PASSWORD = System.getProperty("testPwd", ""); + TEST_ACCOUNT_NAME = System.getProperty("testAccountName",""); + TEST_SERVER_URI = System.getProperty("serverUrl", ""); + + if(TEST_ACCOUNT_PASSWORD.isEmpty()) TEST_ACCOUNT_PASSWORD = BuildConfig.testAccountPWd; + if(TEST_ACCOUNT_NAME.isEmpty()) TEST_ACCOUNT_NAME = BuildConfig.testAccountName; + if(TEST_SERVER_URI.isEmpty()) TEST_SERVER_URI = BuildConfig.testServerUrl; + } + + + + /** + * Create and register one validAccount + */ + public static void prepareValidAccount(AccountManager accountManager){ + validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type + shadowOf(accountManager).addAccount(validAccount); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... + shadowOf(accountManager).setPassword(validAccount, TEST_ACCOUNT_PASSWORD); + //shadowOf(accountManager).setAuthToken(validAccount, "dontknowWhatToDo", "REPLACEATRUNTIMR"); //This is to add the token of the account + shadowOf(accountManager).setUserData(validAccount, KEY_OC_BASE_URL, TEST_SERVER_URI); + } +} diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java new file mode 100644 index 00000000..c35a83d0 --- /dev/null +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -0,0 +1,109 @@ +package foundation.e.drive.operations; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.content.Context; +import android.content.SharedPreferences; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; + +import com.google.android.apps.common.testing.accessibility.framework.proto.FrameworkProtos; +import com.owncloud.android.lib.common.OwnCloudAccount; +import com.owncloud.android.lib.common.OwnCloudClient; +import com.owncloud.android.lib.common.OwnCloudClientFactory; +import com.owncloud.android.lib.common.operations.RemoteOperationResult; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.annotation.Config; + +import java.util.ArrayList; +import java.util.List; + +import foundation.e.drive.BuildConfig; +import foundation.e.drive.database.DbHelper; +import foundation.e.drive.models.SyncedFileState; +import foundation.e.drive.models.SyncedFolder; +import foundation.e.drive.TestConstants; +import foundation.e.drive.utils.AppConstants; +import foundation.e.drive.utils.CommonUtils; + + +@RunWith(RobolectricTestRunner.class) +@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.O, manifest = Config.NONE) +public class UploadFileOperationTest { + + private SharedPreferences sharedPreferences; + private List syncedFileStates= new ArrayList<>(); + private OwnCloudClient client; + private AccountManager accountManager; + + + public UploadFileOperationTest(){ + accountManager = AccountManager.get(RuntimeEnvironment.application); + sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); + } + + @Before + public void setUp(){ + TestConstants.loadServerCredentials(); + //Create DB + Account account = new Account(TestConstants.TEST_ACCOUNT_NAME, TestConstants.TEST_ACCOUNT_TYPE); + accountManager.addAccountExplicitly(account, TestConstants.TEST_ACCOUNT_PASSWORD, new Bundle()); + + prepareDB(); + createLocalFiles(); + + } + + /** + * Prepare content of database for test + */ + private void prepareDB(){ + //Insert three test folder: small, medium, large + + DbHelper.insertSyncedFolder(createSyncedFolder("small"), RuntimeEnvironment.application); + DbHelper.insertSyncedFolder(createSyncedFolder("medium"), RuntimeEnvironment.application); + DbHelper.insertSyncedFolder(createSyncedFolder("large"), RuntimeEnvironment.application); + + //Insert at least one file for each folder + Assert.assertEquals("There isn't three folder in DB as expected", 3, DbHelper.getSyncedFolderList(RuntimeEnvironment.application, true).size()); + } + + private SyncedFolder createSyncedFolder(String name){ + return new SyncedFolder(name, TestConstants.TEST_LOCAL_ROOT_FOLDER_PATH+name+"/", TestConstants.TEST_LOCAL_ROOT_FOLDER_PATH+name+"/", true, true, true, true); + } + + /** + * Create local file to use for upload test + */ + private void createLocalFiles(){ + syncedFileStates.add(new SyncedFileState(2, "dummy.txt", "", "", "", 0l, 0l, true)); + + } + + + /** + * test upload of a file and check that it's ok + */ + @Test + public void testUploadFile(){ + + OwnCloudClient client = CommonUtils.getOwnCloudClient(CommonUtils.getAccount(TestConstants.TEST_ACCOUNT_NAME, TestConstants.TEST_ACCOUNT_TYPE, accountManager), RuntimeEnvironment.application); + Assert.assertNotNull("Client is null. unexpected!", client); + client.setBaseUri(Uri.parse(TestConstants.TEST_SERVER_URI)); + + boolean checkEtag = true; + UploadFileOperation testOperation = new UploadFileOperation(syncedFileStates.get(0), checkEtag); + + RemoteOperationResult result = testOperation.execute(client); + Assert.assertTrue("The upload failed: "+result.getHttpCode(), result.isSuccess()); + + } +} \ No newline at end of file diff --git a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java index acef0631..a92dc8c6 100644 --- a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java +++ b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java @@ -35,28 +35,26 @@ import foundation.e.drive.database.DbHelper; import foundation.e.drive.utils.AppConstants; import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; +import static foundation.e.drive.TestConstants.TEST_ACCOUNT_NAME; +import static foundation.e.drive.TestConstants.TEST_ACCOUNT_PASSWORD; +import static foundation.e.drive.TestConstants.TEST_ACCOUNT_TYPE; +import static foundation.e.drive.TestConstants.TEST_SERVER_URI; +import static foundation.e.drive.TestConstants.validAccount; import static foundation.e.drive.utils.AppConstants.MEDIASYNC_PROVIDER_AUTHORITY; import static foundation.e.drive.utils.AppConstants.SETTINGSYNC_PROVIDER_AUTHORITY; import static org.robolectric.Shadows.shadowOf; - +import foundation.e.drive.TestConstants; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.O, manifest = Config.NONE) public abstract class AbstractServiceIT { - protected static String TEST_ACCOUNT_TYPE ="eelo"; - protected static String TEST_SERVER_URI; - protected static String TEST_ACCOUNT_NAME; - protected static String TEST_ACCOUNT_PASSWORD; - protected static final String TEST_LOCAL_ROOT_FOLDER_PATH = "/tmp/eDrive/test/"; //THis is where test file and folder for synchronisatio will be stored - protected static final String TEST_REMOTE_ROOT_FOLDER_PATH ="/eDrive-test/"; /** * By making the below field static it is done once * for all test class that extends this instead of * one time by class. */ protected static Context context; - protected static Account validAccount; protected T mService; protected ServiceController mServiceController; @@ -75,22 +73,11 @@ public abstract class AbstractServiceIT { @BeforeClass public static void beforeAll(){ - loadServerCredentials(); + TestConstants.loadServerCredentials(); ShadowLog.stream = System.out; //give access to log } - private static void loadServerCredentials(){ - TEST_ACCOUNT_PASSWORD = System.getProperty("testPwd", ""); - TEST_ACCOUNT_NAME = System.getProperty("testAccountName",""); - TEST_SERVER_URI = System.getProperty("serverUrl", ""); - - - if(TEST_ACCOUNT_PASSWORD.isEmpty()) TEST_ACCOUNT_PASSWORD = BuildConfig.testAccountPWd; - if(TEST_ACCOUNT_NAME.isEmpty()) TEST_ACCOUNT_NAME = BuildConfig.testAccountName; - if(TEST_SERVER_URI.isEmpty()) TEST_SERVER_URI = BuildConfig.testServerUrl; - } - /** * Test the connexion to the server * Add the certificate to the knownServerCertificateStore if required @@ -141,15 +128,12 @@ public abstract class AbstractServiceIT { * Create and register one validAccount */ protected void prepareValidAccount(){ - validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type - shadowOf(accountManager).addAccount(validAccount); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... - shadowOf(accountManager).setPassword(validAccount, TEST_ACCOUNT_PASSWORD); - //shadowOf(accountManager).setAuthToken(validAccount, "dontknowWhatToDo", "REPLACEATRUNTIMR"); //This is to add the token of the account - shadowOf(accountManager).setUserData(validAccount, KEY_OC_BASE_URL, TEST_SERVER_URI); + TestConstants.prepareValidAccount(accountManager); } /** * enable Media & settings sync + * Note: Beware validAccount might be null if not initialized before! */ protected void enableMediaAndSettingsSync(){ //replace this by robolectric the contentResolver contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); @@ -158,6 +142,7 @@ public abstract class AbstractServiceIT { /** * disable Media & enable settings sync + * Note: Beware validAccount might be null if not initialized before! */ protected void disableMediaSync(){ //replace this by robolectric the contentResolver contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, false); @@ -166,6 +151,7 @@ public abstract class AbstractServiceIT { /** * enable Media and disable settings sync + * Note: Beware validAccount might be null if not initialized before! */ protected void disableSettingsSync(){ //replace this by robolectric the contentResolver contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); @@ -174,6 +160,7 @@ public abstract class AbstractServiceIT { /** * disable Media & settings sync + * Note: Beware validAccount might be null if not initialized before! */ protected void disableMediaAndSettingsSync(){ //replace this by robolectric the contentResolver contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, false); diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index d61f4d29..6028ce90 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -29,6 +29,9 @@ import foundation.e.drive.operations.CreateInitialFolderRemoteOperation; import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; +import static foundation.e.drive.TestConstants.TEST_LOCAL_ROOT_FOLDER_PATH; +import static foundation.e.drive.TestConstants.TEST_REMOTE_ROOT_FOLDER_PATH; +import static foundation.e.drive.TestConstants.validAccount; import static foundation.e.drive.utils.AppConstants.INITIALIZATION_HAS_BEEN_DONE; import static foundation.e.drive.utils.AppConstants.MEDIA_SYNCABLE_CATEGORIES; import static foundation.e.drive.utils.JobUtils.ScannerJobId; diff --git a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java index dfa0593e..3ede7019 100644 --- a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java @@ -22,6 +22,8 @@ import foundation.e.drive.models.SyncedFileState; import foundation.e.drive.operations.DownloadFileOperation; import foundation.e.drive.utils.AppConstants; +import static foundation.e.drive.TestConstants.validAccount; + public class OperationManagerServiceTest extends AbstractServiceIT{ -- GitLab From 0510c43ad347ad832dbb0ac5bd9f65ab5c347144 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Mon, 26 Apr 2021 19:41:08 +0200 Subject: [PATCH 42/60] refactor test class and try to fix upload test --- .../foundation/e/drive/TestConstants.java | 36 ++++++++++++++----- .../operations/UploadFileOperationTest.java | 23 ++++++------ .../e/drive/services/AbstractServiceIT.java | 36 +++++++------------ .../services/InitializerServiceTest.java | 7 ++-- .../e/drive/services/ObserverServiceTest.java | 14 ++++---- .../services/OperationManagerServiceTest.java | 12 ++++--- 6 files changed, 70 insertions(+), 58 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/TestConstants.java b/app/src/test/java/foundation/e/drive/TestConstants.java index 7048c68c..fc0a441d 100644 --- a/app/src/test/java/foundation/e/drive/TestConstants.java +++ b/app/src/test/java/foundation/e/drive/TestConstants.java @@ -3,6 +3,8 @@ package foundation.e.drive; import android.accounts.Account; import android.accounts.AccountManager; +import org.junit.BeforeClass; + import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; import static org.robolectric.Shadows.shadowOf; @@ -12,10 +14,14 @@ public abstract class TestConstants { public static String TEST_ACCOUNT_TYPE ="eelo"; public static String TEST_SERVER_URI; public static String TEST_ACCOUNT_NAME; - public static String TEST_ACCOUNT_PASSWORD; - public static Account validAccount; + + private static String TEST_ACCOUNT_PASSWORD; //Shouldn't be accessible from outside + private static Account validAccount; + /** + * This method execute before the class, it assure that credentials are available + */ public static void loadServerCredentials(){ TEST_ACCOUNT_PASSWORD = System.getProperty("testPwd", ""); TEST_ACCOUNT_NAME = System.getProperty("testAccountName",""); @@ -27,15 +33,29 @@ public abstract class TestConstants { } + /** + * Get the valid Account object. Create it if it isn't already instanciated + * @return + */ + public static Account getValidAccount(){ + if(validAccount == null){ + System.out.println("Account name = "+TEST_ACCOUNT_NAME); + validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); + } + return validAccount; + } /** - * Create and register one validAccount + * register in accountManager an account with name, password, type and server url provided at build */ public static void prepareValidAccount(AccountManager accountManager){ - validAccount = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE); //Need to provide /e/ account Type - shadowOf(accountManager).addAccount(validAccount); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... - shadowOf(accountManager).setPassword(validAccount, TEST_ACCOUNT_PASSWORD); - //shadowOf(accountManager).setAuthToken(validAccount, "dontknowWhatToDo", "REPLACEATRUNTIMR"); //This is to add the token of the account - shadowOf(accountManager).setUserData(validAccount, KEY_OC_BASE_URL, TEST_SERVER_URI); + storeAccountInManager(getValidAccount(), TEST_ACCOUNT_PASSWORD, TEST_SERVER_URI, accountManager); + } + + + public static void storeAccountInManager(Account account, String password, String serverUrl, AccountManager manager){ + shadowOf(manager).addAccount(account); // Commenting this make failure due to JobUtils.stopScheduleJob()" method... + shadowOf(manager).setPassword(account, password); + shadowOf(manager).setUserData(account, KEY_OC_BASE_URL, serverUrl); } } diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index c35a83d0..e1623b2d 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -46,20 +46,16 @@ public class UploadFileOperationTest { public UploadFileOperationTest(){ + TestConstants.loadServerCredentials(); accountManager = AccountManager.get(RuntimeEnvironment.application); sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); + TestConstants.prepareValidAccount(accountManager); } @Before public void setUp(){ - TestConstants.loadServerCredentials(); - //Create DB - Account account = new Account(TestConstants.TEST_ACCOUNT_NAME, TestConstants.TEST_ACCOUNT_TYPE); - accountManager.addAccountExplicitly(account, TestConstants.TEST_ACCOUNT_PASSWORD, new Bundle()); - - prepareDB(); + prepareDB(); //Create DB createLocalFiles(); - } /** @@ -77,14 +73,14 @@ public class UploadFileOperationTest { } private SyncedFolder createSyncedFolder(String name){ - return new SyncedFolder(name, TestConstants.TEST_LOCAL_ROOT_FOLDER_PATH+name+"/", TestConstants.TEST_LOCAL_ROOT_FOLDER_PATH+name+"/", true, true, true, true); + return new SyncedFolder(name, TestConstants.TEST_LOCAL_ROOT_FOLDER_PATH+name+"/", TestConstants.TEST_REMOTE_ROOT_FOLDER_PATH+name+"/", true, true, true, true); } /** * Create local file to use for upload test */ private void createLocalFiles(){ - syncedFileStates.add(new SyncedFileState(2, "dummy.txt", "", "", "", 0l, 0l, true)); + syncedFileStates.add(new SyncedFileState(-1, "dummy.txt", TestConstants.TEST_LOCAL_ROOT_FOLDER_PATH+"small/dummy.txt", TestConstants.TEST_REMOTE_ROOT_FOLDER_PATH+"small/dummy.txt", "", 0l, 0, true)); } @@ -93,16 +89,19 @@ public class UploadFileOperationTest { * test upload of a file and check that it's ok */ @Test - public void testUploadFile(){ + public void uploadSmallFile_shouldwork(){ OwnCloudClient client = CommonUtils.getOwnCloudClient(CommonUtils.getAccount(TestConstants.TEST_ACCOUNT_NAME, TestConstants.TEST_ACCOUNT_TYPE, accountManager), RuntimeEnvironment.application); Assert.assertNotNull("Client is null. unexpected!", client); - client.setBaseUri(Uri.parse(TestConstants.TEST_SERVER_URI)); - boolean checkEtag = true; + boolean checkEtag = false; UploadFileOperation testOperation = new UploadFileOperation(syncedFileStates.get(0), checkEtag); RemoteOperationResult result = testOperation.execute(client); + System.out.println(result.getCode()+" is the code result"); + System.out.println("result exception: "+result.getException()); + System.out.println("result: "+result.getLogMessage()); + Assert.assertTrue("The upload failed: "+result.getHttpCode(), result.isSuccess()); } diff --git a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java index a92dc8c6..bc8f954a 100644 --- a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java +++ b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java @@ -31,19 +31,13 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import foundation.e.drive.BuildConfig; +import foundation.e.drive.TestConstants; import foundation.e.drive.database.DbHelper; import foundation.e.drive.utils.AppConstants; - -import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; import static foundation.e.drive.TestConstants.TEST_ACCOUNT_NAME; -import static foundation.e.drive.TestConstants.TEST_ACCOUNT_PASSWORD; import static foundation.e.drive.TestConstants.TEST_ACCOUNT_TYPE; -import static foundation.e.drive.TestConstants.TEST_SERVER_URI; -import static foundation.e.drive.TestConstants.validAccount; import static foundation.e.drive.utils.AppConstants.MEDIASYNC_PROVIDER_AUTHORITY; import static foundation.e.drive.utils.AppConstants.SETTINGSYNC_PROVIDER_AUTHORITY; -import static org.robolectric.Shadows.shadowOf; -import foundation.e.drive.TestConstants; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.O, manifest = Config.NONE) @@ -133,38 +127,34 @@ public abstract class AbstractServiceIT { /** * enable Media & settings sync - * Note: Beware validAccount might be null if not initialized before! */ - protected void enableMediaAndSettingsSync(){ //replace this by robolectric the contentResolver - contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); - contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, true); + protected void enableMediaAndSettingsSync(Account account){ //replace this by robolectric the contentResolver + contentResolver.setSyncAutomatically(account, MEDIASYNC_PROVIDER_AUTHORITY, true); + contentResolver.setSyncAutomatically(account, SETTINGSYNC_PROVIDER_AUTHORITY, true); } /** * disable Media & enable settings sync - * Note: Beware validAccount might be null if not initialized before! */ - protected void disableMediaSync(){ //replace this by robolectric the contentResolver - contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, false); - contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, true); + protected void disableMediaSync(Account account){ //replace this by robolectric the contentResolver + contentResolver.setSyncAutomatically(account, MEDIASYNC_PROVIDER_AUTHORITY, false); + contentResolver.setSyncAutomatically(account, SETTINGSYNC_PROVIDER_AUTHORITY, true); } /** * enable Media and disable settings sync - * Note: Beware validAccount might be null if not initialized before! */ - protected void disableSettingsSync(){ //replace this by robolectric the contentResolver - contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, true); - contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, false); + protected void disableSettingsSync(Account account){ //replace this by robolectric the contentResolver + contentResolver.setSyncAutomatically(account, MEDIASYNC_PROVIDER_AUTHORITY, true); + contentResolver.setSyncAutomatically(account, SETTINGSYNC_PROVIDER_AUTHORITY, false); } /** * disable Media & settings sync - * Note: Beware validAccount might be null if not initialized before! */ - protected void disableMediaAndSettingsSync(){ //replace this by robolectric the contentResolver - contentResolver.setSyncAutomatically(validAccount, MEDIASYNC_PROVIDER_AUTHORITY, false); - contentResolver.setSyncAutomatically(validAccount, SETTINGSYNC_PROVIDER_AUTHORITY, false); + protected void disableMediaAndSettingsSync(Account account){ //replace this by robolectric the contentResolver + contentResolver.setSyncAutomatically(account, MEDIASYNC_PROVIDER_AUTHORITY, false); + contentResolver.setSyncAutomatically(account, SETTINGSYNC_PROVIDER_AUTHORITY, false); } /** diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java index 6b7649ea..547d5819 100644 --- a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java @@ -25,6 +25,7 @@ import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowLooper; +import foundation.e.drive.TestConstants; import foundation.e.drive.database.DbHelper; import foundation.e.drive.operations.CreateInitialFolderRemoteOperation; import foundation.e.drive.utils.AppConstants; @@ -86,7 +87,7 @@ public class InitializerServiceTest extends AbstractServiceIT { * @param folder the local folder metadata to create */ private void createRemoteFolder(SyncedFolder folder){ - OwnCloudClient client = CommonUtils.getOwnCloudClient(validAccount, context); + OwnCloudClient client = CommonUtils.getOwnCloudClient(getValidAccount(), context); try { testConnection(client); @@ -156,7 +156,7 @@ public class ObserverServiceTest extends AbstractServiceIT { public void shouldWork() { setWifiNetworkStatus(); prepareValidAccount(); - enableMediaAndSettingsSync(); + enableMediaAndSettingsSync(getValidAccount()); createRemoteFolder(createSingleTestSyncedFolder()); registerScannerJobInJobScheduler(); registerSharedPref(); @@ -185,7 +185,7 @@ public class ObserverServiceTest extends AbstractServiceIT { //setWifiNetworkStatus(); Make the test to fail as expected //setUnavailableWifiNetworkStatus(); //Doesn't give the expected result at the moment so the test fails! prepareValidAccount(); - enableMediaAndSettingsSync(); + enableMediaAndSettingsSync(getValidAccount()); //createRemoteSyncedFolder(createSingleTestSyncedFolder()); registerScannerJobInJobScheduler(); registerSharedPref(); @@ -211,7 +211,7 @@ public class ObserverServiceTest extends AbstractServiceIT { last_sync_time = System.currentTimeMillis() - 899900; setWifiNetworkStatus(); prepareValidAccount(); - enableMediaAndSettingsSync(); + enableMediaAndSettingsSync(getValidAccount()); //createRemoteSyncedFolder(createSingleTestSyncedFolder()); registerScannerJobInJobScheduler(); registerSharedPref(); @@ -238,7 +238,7 @@ public class ObserverServiceTest extends AbstractServiceIT { last_sync_time = System.currentTimeMillis() - 930000; setWifiNetworkStatus(); prepareValidAccount(); - enableMediaAndSettingsSync(); + enableMediaAndSettingsSync(getValidAccount()); //createRemoteSyncedFolder(createSingleTestSyncedFolder()); registerScannerJobInJobScheduler(); registerSharedPref(); @@ -272,7 +272,7 @@ public class ObserverServiceTest extends AbstractServiceIT { setWifiNetworkStatus(); prepareValidAccount(); - enableMediaAndSettingsSync(); + enableMediaAndSettingsSync(getValidAccount()); //createRemoteSyncedFolder(createSingleTestSyncedFolder()); registerScannerJobInJobScheduler(); registerSharedPref(); diff --git a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java index 3ede7019..2a318d4e 100644 --- a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java @@ -1,5 +1,6 @@ package foundation.e.drive.services; +import android.accounts.Account; import android.accounts.AccountManager; import android.app.job.JobScheduler; import android.content.Context; @@ -17,12 +18,12 @@ import org.robolectric.shadows.ShadowLog; import java.util.List; +import foundation.e.drive.TestConstants; import foundation.e.drive.database.DbHelper; import foundation.e.drive.models.SyncedFileState; import foundation.e.drive.operations.DownloadFileOperation; import foundation.e.drive.utils.AppConstants; - -import static foundation.e.drive.TestConstants.validAccount; +import foundation.e.drive.utils.CommonUtils; public class OperationManagerServiceTest extends AbstractServiceIT{ @@ -79,7 +80,8 @@ public class OperationManagerServiceTest extends AbstractServiceIT Date: Mon, 26 Apr 2021 19:47:37 +0200 Subject: [PATCH 43/60] fix upload file test issue and move a function from AbstractServerIt to TestConstants --- .../foundation/e/drive/TestConstants.java | 59 +++++++++++++++++++ .../operations/UploadFileOperationTest.java | 8 +++ .../e/drive/services/AbstractServiceIT.java | 47 --------------- .../e/drive/services/ObserverServiceTest.java | 3 +- 4 files changed, 69 insertions(+), 48 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/TestConstants.java b/app/src/test/java/foundation/e/drive/TestConstants.java index fc0a441d..92154d82 100644 --- a/app/src/test/java/foundation/e/drive/TestConstants.java +++ b/app/src/test/java/foundation/e/drive/TestConstants.java @@ -2,9 +2,23 @@ package foundation.e.drive; import android.accounts.Account; import android.accounts.AccountManager; +import android.content.Context; + +import com.owncloud.android.lib.common.OwnCloudClient; +import com.owncloud.android.lib.common.network.CertificateCombinedException; +import com.owncloud.android.lib.common.network.NetworkUtils; +import com.owncloud.android.lib.common.operations.RemoteOperationResult; +import com.owncloud.android.lib.common.utils.Log_OC; +import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation; import org.junit.BeforeClass; +import java.io.IOException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; import static org.robolectric.Shadows.shadowOf; @@ -58,4 +72,49 @@ public abstract class TestConstants { shadowOf(manager).setPassword(account, password); shadowOf(manager).setUserData(account, KEY_OC_BASE_URL, serverUrl); } + + /** + * Test the connexion to the server + * Add the certificate to the knownServerCertificateStore if required + * @throws KeyStoreException + * @throws CertificateException + * @throws NoSuchAlgorithmException + * @throws IOException + * @throws InterruptedException + */ + public static void testConnection(OwnCloudClient client, Context context) throws KeyStoreException, + CertificateException, + NoSuchAlgorithmException, + IOException, + InterruptedException{ + + GetRemoteStatusOperation getStatus = new GetRemoteStatusOperation(context); + + RemoteOperationResult result = getStatus.execute(client); + + if (result.isSuccess()) { + Log_OC.d("AbstractIT", "Connection to server successful"); + } else { + if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(result.getCode())) { + Log_OC.d("AbstractIT", "Accepting certificate"); + + CertificateCombinedException exception = (CertificateCombinedException) result.getException(); + X509Certificate certificate = exception.getServerCertificate(); + + NetworkUtils.addCertToKnownServersStore(certificate, context); + Thread.sleep(1000); + + // retry + getStatus = new GetRemoteStatusOperation(context); + result = getStatus.execute(client); + + if (!result.isSuccess()) { + throw new RuntimeException("No connection to server possible, even with accepted cert"); + } + + } else { + throw new RuntimeException("No connection to server possible"); + } + } + } } diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index e1623b2d..a55bb90b 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -22,6 +22,7 @@ import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowLog; import java.util.ArrayList; import java.util.List; @@ -90,10 +91,17 @@ public class UploadFileOperationTest { */ @Test public void uploadSmallFile_shouldwork(){ + ShadowLog.stream = System.out; OwnCloudClient client = CommonUtils.getOwnCloudClient(CommonUtils.getAccount(TestConstants.TEST_ACCOUNT_NAME, TestConstants.TEST_ACCOUNT_TYPE, accountManager), RuntimeEnvironment.application); Assert.assertNotNull("Client is null. unexpected!", client); + + try { + TestConstants.testConnection(client, RuntimeEnvironment.application); + }catch(Exception e){ + Assert.fail(e.getMessage()); + } boolean checkEtag = false; UploadFileOperation testOperation = new UploadFileOperation(syncedFileStates.get(0), checkEtag); diff --git a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java index bc8f954a..17ada5ad 100644 --- a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java +++ b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java @@ -71,53 +71,6 @@ public abstract class AbstractServiceIT { ShadowLog.stream = System.out; //give access to log } - - /** - * Test the connexion to the server - * Add the certificate to the knownServerCertificateStore if required - * @throws KeyStoreException - * @throws CertificateException - * @throws NoSuchAlgorithmException - * @throws IOException - * @throws InterruptedException - */ - protected static void testConnection(OwnCloudClient client) throws KeyStoreException, - CertificateException, - NoSuchAlgorithmException, - IOException, - InterruptedException{ - - GetRemoteStatusOperation getStatus = new GetRemoteStatusOperation(context); - - RemoteOperationResult result = getStatus.execute(client); - - if (result.isSuccess()) { - Log_OC.d("AbstractIT", "Connection to server successful"); - } else { - if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(result.getCode())) { - Log_OC.d("AbstractIT", "Accepting certificate"); - - CertificateCombinedException exception = (CertificateCombinedException) result.getException(); - X509Certificate certificate = exception.getServerCertificate(); - - NetworkUtils.addCertToKnownServersStore(certificate, context); - Thread.sleep(1000); - - // retry - getStatus = new GetRemoteStatusOperation(context); - result = getStatus.execute(client); - - if (!result.isSuccess()) { - throw new RuntimeException("No connection to server possible, even with accepted cert"); - } - - } else { - throw new RuntimeException("No connection to server possible"); - } - } - } - - /** * Create and register one validAccount */ diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index 05ce5cdb..678b750c 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -22,6 +22,7 @@ import org.robolectric.shadows.ShadowNetworkInfo; import java.io.File; import java.util.List; +import foundation.e.drive.TestConstants; import foundation.e.drive.database.DbHelper; import foundation.e.drive.jobs.ScannerJob; import foundation.e.drive.models.SyncedFolder; @@ -131,7 +132,7 @@ public class ObserverServiceTest extends AbstractServiceIT { OwnCloudClient client = CommonUtils.getOwnCloudClient(getValidAccount(), context); try { - testConnection(client); + TestConstants.testConnection(client, context); }catch(Exception e){ System.out.println("Test connection failed :"+e.getMessage()); } -- GitLab From fe09f503d535098f0bc1d7a6f26f53ced77de8b6 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Tue, 27 Apr 2021 15:43:36 +0200 Subject: [PATCH 44/60] rename TestConstants into TestUtils and improve uploadFile test by creating local file on @before and destroying it locally and remotly in @After --- .../{TestConstants.java => TestUtils.java} | 33 ++++++++- .../operations/UploadFileOperationTest.java | 68 +++++++++++++------ .../e/drive/services/AbstractServiceIT.java | 23 ++----- .../services/InitializerServiceTest.java | 22 ++---- .../e/drive/services/ObserverServiceTest.java | 18 +++-- .../services/OperationManagerServiceTest.java | 5 +- 6 files changed, 102 insertions(+), 67 deletions(-) rename app/src/test/java/foundation/e/drive/{TestConstants.java => TestUtils.java} (82%) diff --git a/app/src/test/java/foundation/e/drive/TestConstants.java b/app/src/test/java/foundation/e/drive/TestUtils.java similarity index 82% rename from app/src/test/java/foundation/e/drive/TestConstants.java rename to app/src/test/java/foundation/e/drive/TestUtils.java index 92154d82..ad428599 100644 --- a/app/src/test/java/foundation/e/drive/TestConstants.java +++ b/app/src/test/java/foundation/e/drive/TestUtils.java @@ -13,6 +13,8 @@ import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation; import org.junit.BeforeClass; +import java.io.File; +import java.io.FileWriter; import java.io.IOException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; @@ -20,9 +22,10 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_OC_BASE_URL; +import static org.junit.Assert.assertTrue; import static org.robolectric.Shadows.shadowOf; -public abstract class TestConstants { +public abstract class TestUtils { public static final String TEST_LOCAL_ROOT_FOLDER_PATH = "/tmp/eDrive/test/"; //THis is where test file and folder for synchronisatio will be stored public static final String TEST_REMOTE_ROOT_FOLDER_PATH ="/eDrive-test/"; public static String TEST_ACCOUNT_TYPE ="eelo"; @@ -117,4 +120,32 @@ public abstract class TestConstants { } } } + + + /** + * Method adapted from https://github.com/nextcloud/android/blob/master/src/androidTest/java/com/owncloud/android/AbstractIT.java + * @param filePath path of the file to create + * @param iteration number of time to write dummy content + * @return the File instance + * @throws IOException + * @throws SecurityException + */ + public static File createFile(String filePath, int iteration) throws IOException, SecurityException{ + File file = new File(filePath); + if (!file.getParentFile().exists()) { + assertTrue(file.getParentFile().mkdirs()); + } + + file.createNewFile(); + + FileWriter writer = new FileWriter(file); + + for (int i = 0; i < iteration; i++) { + writer.write("123123123123123123123123123\n"); + } + writer.flush(); + writer.close(); + + return file; + } } diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index a55bb90b..89f5fc94 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -1,21 +1,17 @@ package foundation.e.drive.operations; -import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import android.content.SharedPreferences; -import android.net.Uri; import android.os.Build; -import android.os.Bundle; -import com.google.android.apps.common.testing.accessibility.framework.proto.FrameworkProtos; -import com.owncloud.android.lib.common.OwnCloudAccount; import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.OwnCloudClientFactory; +import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import junit.framework.Assert; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,6 +20,8 @@ import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; +import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -31,7 +29,7 @@ import foundation.e.drive.BuildConfig; import foundation.e.drive.database.DbHelper; import foundation.e.drive.models.SyncedFileState; import foundation.e.drive.models.SyncedFolder; -import foundation.e.drive.TestConstants; +import foundation.e.drive.TestUtils; import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; @@ -47,16 +45,25 @@ public class UploadFileOperationTest { public UploadFileOperationTest(){ - TestConstants.loadServerCredentials(); + TestUtils.loadServerCredentials(); accountManager = AccountManager.get(RuntimeEnvironment.application); sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); - TestConstants.prepareValidAccount(accountManager); + TestUtils.prepareValidAccount(accountManager); } @Before public void setUp(){ prepareDB(); //Create DB - createLocalFiles(); + createSmallFile(); + client = CommonUtils.getOwnCloudClient(CommonUtils.getAccount(TestUtils.TEST_ACCOUNT_NAME, TestUtils.TEST_ACCOUNT_TYPE, accountManager), RuntimeEnvironment.application); + Assert.assertNotNull("Client is null. unexpected!", client); + + + } + + @After + public void tearDown(){ + removeSmallFile(); } /** @@ -73,18 +80,45 @@ public class UploadFileOperationTest { Assert.assertEquals("There isn't three folder in DB as expected", 3, DbHelper.getSyncedFolderList(RuntimeEnvironment.application, true).size()); } + /** + * Create the syncedFolder instance + * @param name the name of the folder + * @return SyncedFolder instance + */ private SyncedFolder createSyncedFolder(String name){ - return new SyncedFolder(name, TestConstants.TEST_LOCAL_ROOT_FOLDER_PATH+name+"/", TestConstants.TEST_REMOTE_ROOT_FOLDER_PATH+name+"/", true, true, true, true); + return new SyncedFolder(name, TestUtils.TEST_LOCAL_ROOT_FOLDER_PATH+name+"/", TestUtils.TEST_REMOTE_ROOT_FOLDER_PATH+name+"/", true, true, true, true); } /** * Create local file to use for upload test */ - private void createLocalFiles(){ - syncedFileStates.add(new SyncedFileState(-1, "dummy.txt", TestConstants.TEST_LOCAL_ROOT_FOLDER_PATH+"small/dummy.txt", TestConstants.TEST_REMOTE_ROOT_FOLDER_PATH+"small/dummy.txt", "", 0l, 0, true)); + private void createSmallFile(){ + final String smallDummyFilePath = TestUtils.TEST_LOCAL_ROOT_FOLDER_PATH+"small/dummy.txt"; + try { + TestUtils.createFile(smallDummyFilePath, 2); + } catch (IOException | SecurityException e ) { + Assert.fail(e.getMessage()); + } + syncedFileStates.add(new SyncedFileState(-1, "dummy.txt", TestUtils.TEST_LOCAL_ROOT_FOLDER_PATH+"small/dummy.txt", TestUtils.TEST_REMOTE_ROOT_FOLDER_PATH+"small/dummy.txt", "", 0l, 0, true)); } + /** + * Remove SmallFile locally and remotly if it exist + * @return true if file deleted or if it doesn't exist + */ + private boolean removeSmallFile(){ + //@TODO organise return to be the sum of the remove remote file and remove local file op + RemoveFileOperation removeRemoteFileOp = new RemoveFileOperation(syncedFileStates.get(0)); + + removeRemoteFileOp.execute(client); + + final String smallDummyFilePath = TestUtils.TEST_LOCAL_ROOT_FOLDER_PATH+"small/dummy.txt"; + File smallFile = new File(smallDummyFilePath); + if(smallFile.exists()){ + return smallFile.delete(); + }else return true; + } /** * test upload of a file and check that it's ok @@ -93,12 +127,9 @@ public class UploadFileOperationTest { public void uploadSmallFile_shouldwork(){ ShadowLog.stream = System.out; - OwnCloudClient client = CommonUtils.getOwnCloudClient(CommonUtils.getAccount(TestConstants.TEST_ACCOUNT_NAME, TestConstants.TEST_ACCOUNT_TYPE, accountManager), RuntimeEnvironment.application); - Assert.assertNotNull("Client is null. unexpected!", client); - try { - TestConstants.testConnection(client, RuntimeEnvironment.application); + TestUtils.testConnection(client, RuntimeEnvironment.application); }catch(Exception e){ Assert.fail(e.getMessage()); } @@ -106,9 +137,6 @@ public class UploadFileOperationTest { UploadFileOperation testOperation = new UploadFileOperation(syncedFileStates.get(0), checkEtag); RemoteOperationResult result = testOperation.execute(client); - System.out.println(result.getCode()+" is the code result"); - System.out.println("result exception: "+result.getException()); - System.out.println("result: "+result.getLogMessage()); Assert.assertTrue("The upload failed: "+result.getHttpCode(), result.isSuccess()); diff --git a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java index 17ada5ad..810a7640 100644 --- a/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java +++ b/app/src/test/java/foundation/e/drive/services/AbstractServiceIT.java @@ -10,13 +10,6 @@ import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.os.Build; -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.network.CertificateCombinedException; -import com.owncloud.android.lib.common.network.NetworkUtils; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.utils.Log_OC; -import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation; - import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @@ -24,18 +17,12 @@ import org.robolectric.android.controller.ServiceController; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; -import java.io.IOException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - import foundation.e.drive.BuildConfig; -import foundation.e.drive.TestConstants; +import foundation.e.drive.TestUtils; import foundation.e.drive.database.DbHelper; import foundation.e.drive.utils.AppConstants; -import static foundation.e.drive.TestConstants.TEST_ACCOUNT_NAME; -import static foundation.e.drive.TestConstants.TEST_ACCOUNT_TYPE; +import static foundation.e.drive.TestUtils.TEST_ACCOUNT_NAME; +import static foundation.e.drive.TestUtils.TEST_ACCOUNT_TYPE; import static foundation.e.drive.utils.AppConstants.MEDIASYNC_PROVIDER_AUTHORITY; import static foundation.e.drive.utils.AppConstants.SETTINGSYNC_PROVIDER_AUTHORITY; @@ -67,7 +54,7 @@ public abstract class AbstractServiceIT { @BeforeClass public static void beforeAll(){ - TestConstants.loadServerCredentials(); + TestUtils.loadServerCredentials(); ShadowLog.stream = System.out; //give access to log } @@ -75,7 +62,7 @@ public abstract class AbstractServiceIT { * Create and register one validAccount */ protected void prepareValidAccount(){ - TestConstants.prepareValidAccount(accountManager); + TestUtils.prepareValidAccount(accountManager); } /** diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java index 547d5819..aaa04aad 100644 --- a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java @@ -5,31 +5,17 @@ import android.accounts.AccountManager; import android.app.job.JobScheduler; import android.content.Context; import android.net.ConnectivityManager; -import android.os.Handler; - -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.operations.RemoteOperation; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; import junit.framework.Assert; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.jackrabbit.webdav.client.methods.MkColMethod; import org.junit.Test; -import org.mockito.Answers; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadows.ShadowLog; -import org.robolectric.shadows.ShadowLooper; -import foundation.e.drive.TestConstants; +import foundation.e.drive.TestUtils; import foundation.e.drive.database.DbHelper; -import foundation.e.drive.operations.CreateInitialFolderRemoteOperation; import foundation.e.drive.utils.AppConstants; -import foundation.e.drive.utils.CommonUtils; import static org.robolectric.Shadows.shadowOf; @@ -87,7 +73,7 @@ public class InitializerServiceTest extends AbstractServiceIT { /** * Create a single 'SyncedFolder' instance for 'eDrive-test' folder - * @return + * @return SyncedFolder instance */ private SyncedFolder createSingleTestSyncedFolder(){ final File folder = new File(TEST_LOCAL_ROOT_FOLDER_PATH); - folder.mkdirs(); + try{ + folder.mkdirs(); + }catch(SecurityException e){ + Assert.fail(e.getMessage()); + } final SyncedFolder sFolder = new SyncedFolder(MEDIA_SYNCABLE_CATEGORIES[0], TEST_LOCAL_ROOT_FOLDER_PATH, TEST_REMOTE_ROOT_FOLDER_PATH, true); return sFolder; @@ -132,7 +136,7 @@ public class ObserverServiceTest extends AbstractServiceIT { OwnCloudClient client = CommonUtils.getOwnCloudClient(getValidAccount(), context); try { - TestConstants.testConnection(client, context); + TestUtils.testConnection(client, context); }catch(Exception e){ System.out.println("Test connection failed :"+e.getMessage()); } diff --git a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java index 2a318d4e..0a2fb8f7 100644 --- a/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/OperationManagerServiceTest.java @@ -18,12 +18,11 @@ import org.robolectric.shadows.ShadowLog; import java.util.List; -import foundation.e.drive.TestConstants; +import foundation.e.drive.TestUtils; import foundation.e.drive.database.DbHelper; import foundation.e.drive.models.SyncedFileState; import foundation.e.drive.operations.DownloadFileOperation; import foundation.e.drive.utils.AppConstants; -import foundation.e.drive.utils.CommonUtils; public class OperationManagerServiceTest extends AbstractServiceIT{ @@ -80,7 +79,7 @@ public class OperationManagerServiceTest extends AbstractServiceIT Date: Tue, 27 Apr 2021 19:19:06 +0200 Subject: [PATCH 45/60] fix db update issue with test to upload file --- .../e/drive/operations/UploadFileOperationTest.java | 4 ++-- .../e/drive/services/InitializerServiceTest.java | 9 --------- .../foundation/e/drive/services/ObserverServiceTest.java | 4 ++-- 3 files changed, 4 insertions(+), 13 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index 89f5fc94..56d1e410 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -72,6 +72,7 @@ public class UploadFileOperationTest { private void prepareDB(){ //Insert three test folder: small, medium, large + DbHelper.insertSyncedFolder(createSyncedFolder("small"), RuntimeEnvironment.application); DbHelper.insertSyncedFolder(createSyncedFolder("medium"), RuntimeEnvironment.application); DbHelper.insertSyncedFolder(createSyncedFolder("large"), RuntimeEnvironment.application); @@ -110,7 +111,6 @@ public class UploadFileOperationTest { private boolean removeSmallFile(){ //@TODO organise return to be the sum of the remove remote file and remove local file op RemoveFileOperation removeRemoteFileOp = new RemoveFileOperation(syncedFileStates.get(0)); - removeRemoteFileOp.execute(client); final String smallDummyFilePath = TestUtils.TEST_LOCAL_ROOT_FOLDER_PATH+"small/dummy.txt"; @@ -135,9 +135,9 @@ public class UploadFileOperationTest { } boolean checkEtag = false; UploadFileOperation testOperation = new UploadFileOperation(syncedFileStates.get(0), checkEtag); + testOperation.setContext(RuntimeEnvironment.application); //Without it, it won't update database RemoteOperationResult result = testOperation.execute(client); - Assert.assertTrue("The upload failed: "+result.getHttpCode(), result.isSuccess()); } diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java index aaa04aad..651a6dcb 100644 --- a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java @@ -37,15 +37,6 @@ public class InitializerServiceTest extends AbstractServiceIT { /** * This assert that ObserverService won't start if it's already running */ - @Test + /*@Test public void syncAlreadyStarted_shouldStop(){ //@TODO need to find how to access the "isRunning" private field inside the ObserverService for this test Assert.fail("Not implemented yet"); } - + */ /** * This test will assert that the ObserverService won't do its job -- GitLab From 48b5fcf3fce79083106eeb2ba345e9de0ce4954a Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 28 Apr 2021 09:44:54 +0200 Subject: [PATCH 46/60] add debug info for gitlab execution of upload file test --- .../e/drive/operations/UploadFileOperationTest.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index 56d1e410..7075ea1f 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -126,8 +126,6 @@ public class UploadFileOperationTest { @Test public void uploadSmallFile_shouldwork(){ ShadowLog.stream = System.out; - - try { TestUtils.testConnection(client, RuntimeEnvironment.application); }catch(Exception e){ @@ -138,7 +136,12 @@ public class UploadFileOperationTest { testOperation.setContext(RuntimeEnvironment.application); //Without it, it won't update database RemoteOperationResult result = testOperation.execute(client); - Assert.assertTrue("The upload failed: "+result.getHttpCode(), result.isSuccess()); + String errorMsg = "The upload failed:\n http code: "+result.getHttpCode() + +"\n, is success ?"+result.isSuccess() + +"\n, log msg: "+result.getLogMessage() + +"\n, exception msg: "+result.getException().getMessage() + +"\n, is server fail ? "+result.isServerFail(); + Assert.assertTrue( errorMsg, result.isSuccess()); } } \ No newline at end of file -- GitLab From 0d7cc7a8a772c5b48ba684c08cfc181264562602 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 28 Apr 2021 09:55:55 +0200 Subject: [PATCH 47/60] update debug info for gitlab execution of upload file test --- .../e/drive/operations/UploadFileOperationTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index 7075ea1f..e89911f2 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -139,8 +139,10 @@ public class UploadFileOperationTest { String errorMsg = "The upload failed:\n http code: "+result.getHttpCode() +"\n, is success ?"+result.isSuccess() +"\n, log msg: "+result.getLogMessage() - +"\n, exception msg: "+result.getException().getMessage() +"\n, is server fail ? "+result.isServerFail(); + if(result.getException() != null){ + errorMsg += "\n, exception msg: "+result.getException().getMessage(); + } Assert.assertTrue( errorMsg, result.isSuccess()); } -- GitLab From c16ae065daae06919ec624f3d358d1770ce76ebf Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 28 Apr 2021 11:12:19 +0200 Subject: [PATCH 48/60] try to add more output for CI's test result --- .gitlab-ci.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6aac946e..c09b6c4c 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -25,6 +25,9 @@ test: - ./gradlew test -Dorg.gradle.java.home=/usr/lib/jvm/java-8-openjdk-amd64 -PtestAccountName="${testAccountName}" -PtestAccountPwd="{$testAccountPwd}" -PtestServerUrl="${testServerUrl}" artifacts: when: always + paths: + - app/build/test-results/*/TEST-*.xml + - app/build/reports/tests/* reports: junit: app/build/test-results/*/TEST-*.xml -- GitLab From 4fb27fad44d1105f512aca9a8587afceb5950380 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 28 Apr 2021 13:52:36 +0200 Subject: [PATCH 49/60] fix issue when loading credentials --- app/build.gradle | 3 +-- app/src/test/java/foundation/e/drive/TestUtils.java | 10 +++------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 1851e5eb..65eeb920 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -13,8 +13,7 @@ def getTestProp(String propName) { def result = "" if(project.hasProperty(propName)){ result =project.property(propName).toString() - } - if(project.rootProject.file('local.properties').exists()){ + }else if(project.rootProject.file('local.properties').exists()){ Properties properties = new Properties() properties.load(project.rootProject.file('local.properties').newReader()) result = properties.getProperty(propName) diff --git a/app/src/test/java/foundation/e/drive/TestUtils.java b/app/src/test/java/foundation/e/drive/TestUtils.java index ad428599..159609da 100644 --- a/app/src/test/java/foundation/e/drive/TestUtils.java +++ b/app/src/test/java/foundation/e/drive/TestUtils.java @@ -40,13 +40,9 @@ public abstract class TestUtils { * This method execute before the class, it assure that credentials are available */ public static void loadServerCredentials(){ - TEST_ACCOUNT_PASSWORD = System.getProperty("testPwd", ""); - TEST_ACCOUNT_NAME = System.getProperty("testAccountName",""); - TEST_SERVER_URI = System.getProperty("serverUrl", ""); - - if(TEST_ACCOUNT_PASSWORD.isEmpty()) TEST_ACCOUNT_PASSWORD = BuildConfig.testAccountPWd; - if(TEST_ACCOUNT_NAME.isEmpty()) TEST_ACCOUNT_NAME = BuildConfig.testAccountName; - if(TEST_SERVER_URI.isEmpty()) TEST_SERVER_URI = BuildConfig.testServerUrl; + TEST_ACCOUNT_PASSWORD = BuildConfig.testAccountPWd; + TEST_ACCOUNT_NAME = BuildConfig.testAccountName; + TEST_SERVER_URI = BuildConfig.testServerUrl; } -- GitLab From cc333690be5c12f4e0423dd6124096c603d176cb Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 28 Apr 2021 14:50:58 +0200 Subject: [PATCH 50/60] try to fix use of secret variable in gitlab-ci.yml --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c09b6c4c..b71b2cbc 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -22,7 +22,7 @@ test: stage: test script: - ls /usr/lib/jvm/ - - ./gradlew test -Dorg.gradle.java.home=/usr/lib/jvm/java-8-openjdk-amd64 -PtestAccountName="${testAccountName}" -PtestAccountPwd="{$testAccountPwd}" -PtestServerUrl="${testServerUrl}" + - ./gradlew test -Dorg.gradle.java.home=/usr/lib/jvm/java-8-openjdk-amd64 -PtestAccountName="$testAccountName" -PtestAccountPwd="$testAccountPwd" -PtestServerUrl="$testServerUrl" artifacts: when: always paths: -- GitLab From 0878b7ccc94dcbe01903edad63ac909d26b81404 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 28 Apr 2021 16:42:04 +0200 Subject: [PATCH 51/60] add Database check into uploadNewSmallFile test --- .../operations/UploadFileOperationTest.java | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index e89911f2..db22dc2d 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -1,12 +1,9 @@ package foundation.e.drive.operations; import android.accounts.AccountManager; -import android.content.Context; -import android.content.SharedPreferences; import android.os.Build; import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import junit.framework.Assert; @@ -30,7 +27,6 @@ import foundation.e.drive.database.DbHelper; import foundation.e.drive.models.SyncedFileState; import foundation.e.drive.models.SyncedFolder; import foundation.e.drive.TestUtils; -import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; @@ -38,7 +34,6 @@ import foundation.e.drive.utils.CommonUtils; @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.O, manifest = Config.NONE) public class UploadFileOperationTest { - private SharedPreferences sharedPreferences; private List syncedFileStates= new ArrayList<>(); private OwnCloudClient client; private AccountManager accountManager; @@ -47,7 +42,6 @@ public class UploadFileOperationTest { public UploadFileOperationTest(){ TestUtils.loadServerCredentials(); accountManager = AccountManager.get(RuntimeEnvironment.application); - sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); TestUtils.prepareValidAccount(accountManager); } @@ -101,7 +95,11 @@ public class UploadFileOperationTest { } catch (IOException | SecurityException e ) { Assert.fail(e.getMessage()); } - syncedFileStates.add(new SyncedFileState(-1, "dummy.txt", TestUtils.TEST_LOCAL_ROOT_FOLDER_PATH+"small/dummy.txt", TestUtils.TEST_REMOTE_ROOT_FOLDER_PATH+"small/dummy.txt", "", 0l, 0, true)); + + final SyncedFileState sfs = new SyncedFileState(-1, "dummy.txt", TestUtils.TEST_LOCAL_ROOT_FOLDER_PATH+"small/dummy.txt", TestUtils.TEST_REMOTE_ROOT_FOLDER_PATH+"small/dummy.txt", "", 0l, 0, true); + sfs.setId(DbHelper.manageSyncedFileStateDB(sfs, "INSERT", RuntimeEnvironment.application)); + + syncedFileStates.add(sfs); } /** @@ -124,13 +122,18 @@ public class UploadFileOperationTest { * test upload of a file and check that it's ok */ @Test - public void uploadSmallFile_shouldwork(){ + public void uploadNewSmallFile_shouldwork(){ ShadowLog.stream = System.out; try { TestUtils.testConnection(client, RuntimeEnvironment.application); }catch(Exception e){ Assert.fail(e.getMessage()); } + + final SyncedFileState sfs_fromDB = DbHelper.loadSyncedFile(RuntimeEnvironment.application, syncedFileStates.get(0).getLocalPath(), true); + Assert.assertTrue("SyncedFileState loaded from DB must have an empty Etag", sfs_fromDB.getLastETAG().isEmpty()); + + boolean checkEtag = false; UploadFileOperation testOperation = new UploadFileOperation(syncedFileStates.get(0), checkEtag); testOperation.setContext(RuntimeEnvironment.application); //Without it, it won't update database @@ -145,5 +148,8 @@ public class UploadFileOperationTest { } Assert.assertTrue( errorMsg, result.isSuccess()); + final SyncedFileState sfs_fromDBAfterUpload = DbHelper.loadSyncedFile(RuntimeEnvironment.application, syncedFileStates.get(0).getLocalPath(), true); + Assert.assertFalse("After upload, the database must store the etag of the syncedFileState. But here it is empty", sfs_fromDBAfterUpload.getLastETAG().isEmpty()); + } } \ No newline at end of file -- GitLab From 8b0b4c02422cb70eedd91f0e8f557796be64c5c7 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 29 Apr 2021 12:01:39 +0200 Subject: [PATCH 52/60] add a new test case for UploadFileOperation --- .../operations/UploadFileOperationTest.java | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index db22dc2d..ce726e55 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -43,12 +43,12 @@ public class UploadFileOperationTest { TestUtils.loadServerCredentials(); accountManager = AccountManager.get(RuntimeEnvironment.application); TestUtils.prepareValidAccount(accountManager); + ShadowLog.stream = System.out; } @Before public void setUp(){ prepareDB(); //Create DB - createSmallFile(); client = CommonUtils.getOwnCloudClient(CommonUtils.getAccount(TestUtils.TEST_ACCOUNT_NAME, TestUtils.TEST_ACCOUNT_TYPE, accountManager), RuntimeEnvironment.application); Assert.assertNotNull("Client is null. unexpected!", client); @@ -57,7 +57,6 @@ public class UploadFileOperationTest { @After public void tearDown(){ - removeSmallFile(); } /** @@ -123,7 +122,8 @@ public class UploadFileOperationTest { */ @Test public void uploadNewSmallFile_shouldwork(){ - ShadowLog.stream = System.out; + createSmallFile(); //preparation + try { TestUtils.testConnection(client, RuntimeEnvironment.application); }catch(Exception e){ @@ -151,5 +151,22 @@ public class UploadFileOperationTest { final SyncedFileState sfs_fromDBAfterUpload = DbHelper.loadSyncedFile(RuntimeEnvironment.application, syncedFileStates.get(0).getLocalPath(), true); Assert.assertFalse("After upload, the database must store the etag of the syncedFileState. But here it is empty", sfs_fromDBAfterUpload.getLastETAG().isEmpty()); + //tearDown + removeSmallFile(); + } + + + /** + * Try to upload a file with a null SyncedFileState instance + * Must return a "Forbidden" result code + */ + @Test + public void nullSyncedFileState_shouldFail(){ + UploadFileOperation testOperation = new UploadFileOperation(null, false); + testOperation.setContext(RuntimeEnvironment.application); + + + RemoteOperationResult result = testOperation.execute(client); + Assert.assertEquals("Expected result code was FORBIDDEN but got: "+result.getCode().name(), RemoteOperationResult.ResultCode.FORBIDDEN, result.getCode()); } } \ No newline at end of file -- GitLab From 8591d2978c404a3722d6fa5fc2941db2df9a999d Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 29 Apr 2021 16:27:56 +0200 Subject: [PATCH 53/60] add @ignore annotation to some test. Add another test for UploadOperation to check that operation fails if file has been removed before execution --- .../operations/UploadFileOperationTest.java | 44 ++++++++++++++++--- .../e/drive/services/ObserverServiceTest.java | 10 +++-- 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index ce726e55..0ecd344e 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -10,6 +10,7 @@ import junit.framework.Assert; import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @@ -103,12 +104,18 @@ public class UploadFileOperationTest { /** * Remove SmallFile locally and remotly if it exist + * This method has just been made to make basic test to work + * It should be refactored for next state, and test improvement * @return true if file deleted or if it doesn't exist */ private boolean removeSmallFile(){ - //@TODO organise return to be the sum of the remove remote file and remove local file op - RemoveFileOperation removeRemoteFileOp = new RemoveFileOperation(syncedFileStates.get(0)); - removeRemoteFileOp.execute(client); + if(!syncedFileStates.isEmpty()) { + final SyncedFileState sfs = syncedFileStates.get(0); + if (sfs != null) { + RemoveFileOperation removeRemoteFileOp = new RemoveFileOperation(sfs); + removeRemoteFileOp.execute(client); + } + } final String smallDummyFilePath = TestUtils.TEST_LOCAL_ROOT_FOLDER_PATH+"small/dummy.txt"; File smallFile = new File(smallDummyFilePath); @@ -122,6 +129,8 @@ public class UploadFileOperationTest { */ @Test public void uploadNewSmallFile_shouldwork(){ + //tearDown + removeSmallFile(); //clean the environnement createSmallFile(); //preparation try { @@ -150,9 +159,6 @@ public class UploadFileOperationTest { final SyncedFileState sfs_fromDBAfterUpload = DbHelper.loadSyncedFile(RuntimeEnvironment.application, syncedFileStates.get(0).getLocalPath(), true); Assert.assertFalse("After upload, the database must store the etag of the syncedFileState. But here it is empty", sfs_fromDBAfterUpload.getLastETAG().isEmpty()); - - //tearDown - removeSmallFile(); } @@ -160,11 +166,37 @@ public class UploadFileOperationTest { * Try to upload a file with a null SyncedFileState instance * Must return a "Forbidden" result code */ + @Ignore("Ignored until UploadFileOperation has fixed the NPE") @Test public void nullSyncedFileState_shouldFail(){ + + //Test fails at the moment because of UploadFileOperation's constructor not checking for syncedFileState is null) + // check https://gitlab.e.foundation/e/apps/eDrive/-/issues/120 UploadFileOperation testOperation = new UploadFileOperation(null, false); testOperation.setContext(RuntimeEnvironment.application); + RemoteOperationResult result = testOperation.execute(client); + Assert.assertEquals("Expected result code was FORBIDDEN but got: "+result.getCode().name(), RemoteOperationResult.ResultCode.FORBIDDEN, result.getCode()); + } + + + /** + * Try to upload local file that has been removed between uploadOperation's creation and + * ploadOperation execution + */ + @Test + public void localFileRemovedBeforeUpload_shouldFail(){ + removeSmallFile(); //clean the environnement + createSmallFile(); //preparation + + final SyncedFileState sfs_fromDB = DbHelper.loadSyncedFile(RuntimeEnvironment.application, syncedFileStates.get(0).getLocalPath(), true); + Assert.assertTrue("SyncedFileState loaded from DB must have an empty Etag", sfs_fromDB.getLastETAG().isEmpty()); + + boolean checkEtag = false; + UploadFileOperation testOperation = new UploadFileOperation(syncedFileStates.get(0), checkEtag); + + File smallFile = new File(sfs_fromDB.getLocalPath()); + Assert.assertTrue("Local file deletion return false instead of true", smallFile.delete()); RemoteOperationResult result = testOperation.execute(client); Assert.assertEquals("Expected result code was FORBIDDEN but got: "+result.getCode().name(), RemoteOperationResult.ResultCode.FORBIDDEN, result.getCode()); diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index f9cece74..d6369132 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -13,6 +13,7 @@ import com.owncloud.android.lib.common.operations.RemoteOperationResult; import junit.framework.Assert; +import org.junit.Ignore; import org.junit.Test; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; @@ -157,6 +158,7 @@ public class ObserverServiceTest extends AbstractServiceIT { /** * Run a test which correspond to a non blocking context */ + @Ignore("Ignore until a correct assertion has been found") @Test public void shouldWork() { setWifiNetworkStatus(); @@ -185,6 +187,7 @@ public class ObserverServiceTest extends AbstractServiceIT { /** * This assert that ObserverService doesn't start scanning remote or local if there is no network */ + @Ignore("Ignore until a way to prepare unavailable Network has been founded") @Test public void noNetwork_shouldStop(){ //setWifiNetworkStatus(); Make the test to fail as expected @@ -260,12 +263,13 @@ public class ObserverServiceTest extends AbstractServiceIT { /** * This assert that ObserverService won't start if it's already running */ - /*@Test + @Ignore("Not yet implemented") + @Test public void syncAlreadyStarted_shouldStop(){ //@TODO need to find how to access the "isRunning" private field inside the ObserverService for this test - Assert.fail("Not implemented yet"); + Assert.fail("Not yet implemented "); } - */ + /** * This test will assert that the ObserverService won't do its job -- GitLab From a39035345f4dc74b2ba5c8b656e6ca01fd704abd Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 5 May 2021 11:10:49 +0200 Subject: [PATCH 54/60] add 'noAccount_shouldStop' test for ObserverServiceTest --- .../e/drive/services/ObserverServiceTest.java | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index d6369132..fb282453 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -30,6 +30,7 @@ import foundation.e.drive.models.SyncedFolder; import foundation.e.drive.operations.CreateInitialFolderRemoteOperation; import foundation.e.drive.utils.AppConstants; import foundation.e.drive.utils.CommonUtils; +import foundation.e.drive.utils.JobUtils; import static foundation.e.drive.TestUtils.TEST_LOCAL_ROOT_FOLDER_PATH; import static foundation.e.drive.TestUtils.TEST_REMOTE_ROOT_FOLDER_PATH; @@ -60,28 +61,12 @@ public class ObserverServiceTest extends AbstractServiceIT { * Schedule a ScannerJob instance in JobScheduler */ private void registerScannerJobInJobScheduler(){ - ComponentName jobService = new ComponentName( context, ScannerJob.class ); - Assert.assertNotNull(jobService); + Assert.assertTrue("jobScheduler expected to be have no pending job",jobScheduler.getAllPendingJobs().isEmpty()); - //Creating the job like in ScannerJob class isn't possible because Robolectric doesn't - // support chaining of function with JobInfo.Builder... - JobInfo.Builder jobBuilder = new JobInfo.Builder(ScannerJobId, jobService ); - Assert.assertNotNull(jobBuilder); + JobUtils.scheduleScannerJob(context); + int scheduledJobListSize = jobScheduler.getAllPendingJobs().size(); + Assert.assertEquals("PendingJob size expected to be 1 but was:"+scheduledJobListSize,1, scheduledJobListSize ); - jobBuilder.setPeriodic(1860000, 30000); - jobBuilder.setPersisted(true); - jobBuilder.setRequiredNetworkType( JobInfo.NETWORK_TYPE_ANY ); - - //JobInfo job = jobBuilder.build(); - //System.out.println("is Job null ??"); - //Assert.assertNotNull(job); //Can't find why it fails: NPE, job is null... - - - //Assert.assertTrue(jobScheduler.getAllPendingJobs().isEmpty()); //Get NPE too...why ? - - //shadowOf(jobScheduler).schedule(job); - - //Mockito.when(JobUtils.scheduleScannerJob(RuntimeEnvironment.application)).then(); } @@ -271,6 +256,22 @@ public class ObserverServiceTest extends AbstractServiceIT { } + /** + * Check that service stop if no account provided + */ + @Test + public void noAccount_shouldStop(){ + registerScannerJobInJobScheduler(); //Assert that the ScheduledJob is present + + mServiceController.create().startCommand(0, 0); + + List logs = ShadowLog.getLogs(); + ShadowLog.LogItem lastLog = logs.get(logs.size()-1); + + Assert.assertEquals("Last expected log wasn't: 'No account registered' but "+lastLog.msg, "No account registered",lastLog.msg ); + Assert.assertTrue("jobScheduler expected to be have no pending job",jobScheduler.getAllPendingJobs().isEmpty()); + } + /** * This test will assert that the ObserverService won't do its job * if Initialization hasn't been done -- GitLab From b602bcf983d85e9ae50f5912dede667545e0477c Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 5 May 2021 11:12:14 +0200 Subject: [PATCH 55/60] remove useless element in build.gradle --- app/build.gradle | 2 -- 1 file changed, 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 65eeb920..c93eb509 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -31,8 +31,6 @@ android { //versionName "1.0" versionName "beta-${versionMajor}-build-o-${buildTime()}" setProperty("archivesBaseName", "$applicationId.$versionName") - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - testBuildType System.getProperty('testBuildType', 'debug') buildConfigField "String", "testAccountName", "\""+getTestProp("testAccountName")+"\"" buildConfigField "String", "testAccountPWd", "\""+getTestProp("testAccountPwd")+"\"" buildConfigField "String", "testServerUrl", "\""+getTestProp("testServerUrl")+"\"" -- GitLab From 352f206af50a32ee048fbf32ea3eb27f31dd7681 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Wed, 5 May 2021 15:51:17 +0200 Subject: [PATCH 56/60] add assertion about intent on ObserverServiceTest.InitializationNotDone_shouldStop --- .../e/drive/services/ObserverServiceTest.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java index fb282453..a01a141e 100644 --- a/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/ObserverServiceTest.java @@ -1,10 +1,9 @@ package foundation.e.drive.services; import android.accounts.AccountManager; -import android.app.job.JobInfo; import android.app.job.JobScheduler; -import android.content.ComponentName; import android.content.Context; +import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; @@ -25,7 +24,6 @@ import java.util.List; import foundation.e.drive.TestUtils; import foundation.e.drive.database.DbHelper; -import foundation.e.drive.jobs.ScannerJob; import foundation.e.drive.models.SyncedFolder; import foundation.e.drive.operations.CreateInitialFolderRemoteOperation; import foundation.e.drive.utils.AppConstants; @@ -37,7 +35,6 @@ import static foundation.e.drive.TestUtils.TEST_REMOTE_ROOT_FOLDER_PATH; import static foundation.e.drive.TestUtils.getValidAccount; import static foundation.e.drive.utils.AppConstants.INITIALIZATION_HAS_BEEN_DONE; import static foundation.e.drive.utils.AppConstants.MEDIA_SYNCABLE_CATEGORIES; -import static foundation.e.drive.utils.JobUtils.ScannerJobId; import static org.robolectric.Shadows.shadowOf; /** @@ -293,6 +290,11 @@ public class ObserverServiceTest extends AbstractServiceIT { mServiceController.create().startCommand(0, 0); //How to assert this... ? + Intent expectedIntent = new Intent(mService, InitializerService.class); + Intent actualIntent = shadowOf(RuntimeEnvironment.application).getNextStartedService(); + + Assert.assertEquals("Checked intent not the expected one", expectedIntent.getComponent(), actualIntent.getComponent()); + List logs = ShadowLog.getLogs(); ShadowLog.LogItem lastLog = logs.get(logs.size()-1); -- GitLab From 2bb86c0b1643e1464d7999ec3ddb2d6fa4264d24 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 6 May 2021 11:33:44 +0200 Subject: [PATCH 57/60] start to write test to assert quota checking when uploading file --- .../drive/operations/UploadFileOperation.java | 4 ++- .../operations/UploadFileOperationTest.java | 30 +++++++++++++++++-- .../services/InitializerServiceTest.java | 4 ++- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/foundation/e/drive/operations/UploadFileOperation.java b/app/src/main/java/foundation/e/drive/operations/UploadFileOperation.java index 88276a6b..515ce35f 100644 --- a/app/src/main/java/foundation/e/drive/operations/UploadFileOperation.java +++ b/app/src/main/java/foundation/e/drive/operations/UploadFileOperation.java @@ -11,6 +11,7 @@ package foundation.e.drive.operations; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; +import android.support.annotation.VisibleForTesting; import android.util.Log; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.UserInfo; @@ -217,7 +218,8 @@ public class UploadFileOperation extends RemoteOperation implements ComparableOp * @param client OwnCloudClient * @return RemoteOperationResult */ - private RemoteOperationResult checkAvailableSpace(OwnCloudClient client, long fileSize){ + @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) + public RemoteOperationResult checkAvailableSpace(OwnCloudClient client, long fileSize){ GetRemoteUserInfoOperation getRemoteUserInfoOperation = new GetRemoteUserInfoOperation(); RemoteOperationResult ocsResult = getRemoteUserInfoOperation.execute(client); if(ocsResult.isSuccess() && ocsResult.getData() != null){ diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index 0ecd344e..34d786d9 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -4,7 +4,9 @@ import android.accounts.AccountManager; import android.os.Build; import com.owncloud.android.lib.common.OwnCloudClient; +import com.owncloud.android.lib.common.UserInfo; import com.owncloud.android.lib.common.operations.RemoteOperationResult; +import com.owncloud.android.lib.resources.users.GetRemoteUserInfoOperation; import junit.framework.Assert; @@ -52,8 +54,6 @@ public class UploadFileOperationTest { prepareDB(); //Create DB client = CommonUtils.getOwnCloudClient(CommonUtils.getAccount(TestUtils.TEST_ACCOUNT_NAME, TestUtils.TEST_ACCOUNT_TYPE, accountManager), RuntimeEnvironment.application); Assert.assertNotNull("Client is null. unexpected!", client); - - } @After @@ -201,4 +201,30 @@ public class UploadFileOperationTest { RemoteOperationResult result = testOperation.execute(client); Assert.assertEquals("Expected result code was FORBIDDEN but got: "+result.getCode().name(), RemoteOperationResult.ResultCode.FORBIDDEN, result.getCode()); } + + + /** + * Assert that uploading a file that is bigger than quotas isn't allowed + */ + @Test + public void fileBiggerThanQuota_shouldFail(){ + //read quotas of the account + GetRemoteUserInfoOperation getRemoteUserInfoOperation = new GetRemoteUserInfoOperation(); + RemoteOperationResult ocsResult = getRemoteUserInfoOperation.execute(client); + if(ocsResult.isSuccess() && ocsResult.getData() != null) { + UserInfo userInfo = (UserInfo) ocsResult.getData().get(0); + System.out.println("User free Quotas: "+userInfo.getQuota().getFree()); + System.out.println("User Quota: "+userInfo.getQuota().getQuota()); + System.out.println("User used Quotas: "+userInfo.getQuota().getUsed()); + System.out.println("User Total Quotas: "+userInfo.getQuota().getTotal()); + }else{ + Assert.fail("Checking userInfo.getQuota() as preparation failed"); + } + + + RemoteOperationResult expectedResult =new RemoteOperationResult(RemoteOperationResult.ResultCode.QUOTA_EXCEEDED); + + RemoteOperationResult actualResult = null; + Assert.assertEquals("Quota check shoul return Quota_EXCEEDED but got "+actualResult.getCode().name(), expectedResult, actualResult); + } } \ No newline at end of file diff --git a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java index 651a6dcb..0de9195b 100644 --- a/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java +++ b/app/src/test/java/foundation/e/drive/services/InitializerServiceTest.java @@ -81,8 +81,10 @@ public class InitializerServiceTest extends AbstractServiceIT Date: Thu, 6 May 2021 14:55:00 +0200 Subject: [PATCH 58/60] make test for quota checking --- .../operations/UploadFileOperationTest.java | 64 +++++++++++++++++-- 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index 34d786d9..0ed7e6ba 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -15,6 +15,7 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; @@ -204,27 +205,76 @@ public class UploadFileOperationTest { /** - * Assert that uploading a file that is bigger than quotas isn't allowed + * Assert that uploading a file that is bigger than free quotas isn't allowed */ @Test - public void fileBiggerThanQuota_shouldFail(){ + public void fileSizeBiggerThanFreeQuota_shouldnotBeAllowed(){ //read quotas of the account GetRemoteUserInfoOperation getRemoteUserInfoOperation = new GetRemoteUserInfoOperation(); RemoteOperationResult ocsResult = getRemoteUserInfoOperation.execute(client); if(ocsResult.isSuccess() && ocsResult.getData() != null) { UserInfo userInfo = (UserInfo) ocsResult.getData().get(0); + System.out.println("User free Quotas: "+userInfo.getQuota().getFree()); - System.out.println("User Quota: "+userInfo.getQuota().getQuota()); - System.out.println("User used Quotas: "+userInfo.getQuota().getUsed()); System.out.println("User Total Quotas: "+userInfo.getQuota().getTotal()); + + //We don't care of parameter of UploadFileOperation's constructor + RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false).checkAvailableSpace(client, (userInfo.getQuota().getFree()+1)); + Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), RemoteOperationResult.ResultCode.QUOTA_EXCEEDED, actualResult.getCode()); + }else{ Assert.fail("Checking userInfo.getQuota() as preparation failed"); } + } + /** + * Assert that uploading a file which size is exactly the amount of free quota isn't allowed + * + */ + @Test + public void fileSizeEqualToFreeQuota_shouldnotBeAllowed(){ + //read quotas of the account + GetRemoteUserInfoOperation getRemoteUserInfoOperation = new GetRemoteUserInfoOperation(); + RemoteOperationResult ocsResult = getRemoteUserInfoOperation.execute(client); + if(ocsResult.isSuccess() && ocsResult.getData() != null) { + UserInfo userInfo = (UserInfo) ocsResult.getData().get(0); + + System.out.println("User free Quotas: "+userInfo.getQuota().getFree()); + System.out.println("User Total Quotas: "+userInfo.getQuota().getTotal()); - RemoteOperationResult expectedResult =new RemoteOperationResult(RemoteOperationResult.ResultCode.QUOTA_EXCEEDED); + long fileSize = userInfo.getQuota().getFree(); + System.out.println("FileSize: "+fileSize); - RemoteOperationResult actualResult = null; - Assert.assertEquals("Quota check shoul return Quota_EXCEEDED but got "+actualResult.getCode().name(), expectedResult, actualResult); + //We don't care of parameter of UploadFileOperation's constructor + RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false).checkAvailableSpace(client, fileSize); + Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), RemoteOperationResult.ResultCode.QUOTA_EXCEEDED, actualResult.getCode()); + + }else{ + Assert.fail("Checking userInfo.getQuota() as preparation failed"); + } + } + + /** + * Assert that uploading a file which size is lower than the amount of free quota is allowed + * + */ + @Test + public void fileSizeEqualToFreeQuota_shouldBeAllowed(){ + //read quotas of the account + GetRemoteUserInfoOperation getRemoteUserInfoOperation = new GetRemoteUserInfoOperation(); + RemoteOperationResult ocsResult = getRemoteUserInfoOperation.execute(client); + if(ocsResult.isSuccess() && ocsResult.getData() != null) { + UserInfo userInfo = (UserInfo) ocsResult.getData().get(0); + + System.out.println("User free Quotas: "+userInfo.getQuota().getFree()); + System.out.println("User Total Quotas: "+userInfo.getQuota().getTotal()); + + //We don't care of parameter of UploadFileOperation's constructor + RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false).checkAvailableSpace(client, (userInfo.getQuota().getFree()-1)); + Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), RemoteOperationResult.ResultCode.OK, actualResult.getCode()); + + }else{ + Assert.fail("Checking userInfo.getQuota() as preparation failed"); + } } } \ No newline at end of file -- GitLab From d185a14c60caccefd9ebcef039c9be1aac53a596 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Thu, 6 May 2021 16:38:05 +0200 Subject: [PATCH 59/60] try to fix quota checking test --- .../operations/UploadFileOperationTest.java | 90 +++++++++---------- 1 file changed, 40 insertions(+), 50 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index 0ed7e6ba..dee3be47 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -125,6 +125,20 @@ public class UploadFileOperationTest { }else return true; } + private long getUserRemoteFreeQuota(){ + GetRemoteUserInfoOperation getRemoteUserInfoOperation = new GetRemoteUserInfoOperation(); + RemoteOperationResult ocsResult = getRemoteUserInfoOperation.execute(client); + + if(ocsResult.isSuccess() && ocsResult.getData() != null) { + UserInfo userInfo = (UserInfo) ocsResult.getData().get(0); + System.out.println("User free Quotas: "+userInfo.getQuota().getFree()); + System.out.println("User Total Quotas: "+userInfo.getQuota().getTotal()); + + return userInfo.getQuota().getFree(); + } + return -1; + } + /** * test upload of a file and check that it's ok */ @@ -163,6 +177,8 @@ public class UploadFileOperationTest { } + + /** * Try to upload a file with a null SyncedFileState instance * Must return a "Forbidden" result code @@ -209,22 +225,12 @@ public class UploadFileOperationTest { */ @Test public void fileSizeBiggerThanFreeQuota_shouldnotBeAllowed(){ - //read quotas of the account - GetRemoteUserInfoOperation getRemoteUserInfoOperation = new GetRemoteUserInfoOperation(); - RemoteOperationResult ocsResult = getRemoteUserInfoOperation.execute(client); - if(ocsResult.isSuccess() && ocsResult.getData() != null) { - UserInfo userInfo = (UserInfo) ocsResult.getData().get(0); - - System.out.println("User free Quotas: "+userInfo.getQuota().getFree()); - System.out.println("User Total Quotas: "+userInfo.getQuota().getTotal()); - - //We don't care of parameter of UploadFileOperation's constructor - RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false).checkAvailableSpace(client, (userInfo.getQuota().getFree()+1)); - Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), RemoteOperationResult.ResultCode.QUOTA_EXCEEDED, actualResult.getCode()); - - }else{ - Assert.fail("Checking userInfo.getQuota() as preparation failed"); - } + long freeQuota = getUserRemoteFreeQuota(); + Assert.assertFalse("Reading remote free quota fails"+freeQuota, -1 == freeQuota); + //We don't care of parameter of UploadFileOperation's constructor + RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false) + .checkAvailableSpace(client, (freeQuota+1)); + Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), RemoteOperationResult.ResultCode.QUOTA_EXCEEDED, actualResult.getCode()); } /** @@ -233,48 +239,32 @@ public class UploadFileOperationTest { */ @Test public void fileSizeEqualToFreeQuota_shouldnotBeAllowed(){ - //read quotas of the account - GetRemoteUserInfoOperation getRemoteUserInfoOperation = new GetRemoteUserInfoOperation(); - RemoteOperationResult ocsResult = getRemoteUserInfoOperation.execute(client); - if(ocsResult.isSuccess() && ocsResult.getData() != null) { - UserInfo userInfo = (UserInfo) ocsResult.getData().get(0); - - System.out.println("User free Quotas: "+userInfo.getQuota().getFree()); - System.out.println("User Total Quotas: "+userInfo.getQuota().getTotal()); - - long fileSize = userInfo.getQuota().getFree(); - System.out.println("FileSize: "+fileSize); - - //We don't care of parameter of UploadFileOperation's constructor - RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false).checkAvailableSpace(client, fileSize); - Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), RemoteOperationResult.ResultCode.QUOTA_EXCEEDED, actualResult.getCode()); - - }else{ - Assert.fail("Checking userInfo.getQuota() as preparation failed"); - } + //I don't know why but it always fail for this test. + long freeQuota = getUserRemoteFreeQuota(); + Assert.assertFalse("Reading remote free quota fails"+freeQuota, -1 == freeQuota); + + RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false) + .checkAvailableSpace(client, freeQuota); + Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), + RemoteOperationResult.ResultCode.QUOTA_EXCEEDED, + actualResult.getCode()); } + /** * Assert that uploading a file which size is lower than the amount of free quota is allowed * */ @Test - public void fileSizeEqualToFreeQuota_shouldBeAllowed(){ - //read quotas of the account - GetRemoteUserInfoOperation getRemoteUserInfoOperation = new GetRemoteUserInfoOperation(); - RemoteOperationResult ocsResult = getRemoteUserInfoOperation.execute(client); - if(ocsResult.isSuccess() && ocsResult.getData() != null) { - UserInfo userInfo = (UserInfo) ocsResult.getData().get(0); + public void fileSizeSmallerThanFreeQuota_shouldBeAllowed(){ + long freeQuota = getUserRemoteFreeQuota(); + Assert.assertFalse("Reading remote free quota fails "+freeQuota, -1 == freeQuota); - System.out.println("User free Quotas: "+userInfo.getQuota().getFree()); - System.out.println("User Total Quotas: "+userInfo.getQuota().getTotal()); + RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false) + .checkAvailableSpace(client, (freeQuota-1)); + Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), + RemoteOperationResult.ResultCode.OK, + actualResult.getCode()); - //We don't care of parameter of UploadFileOperation's constructor - RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false).checkAvailableSpace(client, (userInfo.getQuota().getFree()-1)); - Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), RemoteOperationResult.ResultCode.OK, actualResult.getCode()); - - }else{ - Assert.fail("Checking userInfo.getQuota() as preparation failed"); - } } } \ No newline at end of file -- GitLab From 58d579b136b21c143436e32c847c1c80f80ff015 Mon Sep 17 00:00:00 2001 From: vincent Bourgmayer Date: Fri, 14 May 2021 11:56:34 +0200 Subject: [PATCH 60/60] fix quota check tests --- .../operations/UploadFileOperationTest.java | 40 ++++++++++--------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java index dee3be47..1c01da6f 100644 --- a/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java +++ b/app/src/test/java/foundation/e/drive/operations/UploadFileOperationTest.java @@ -42,18 +42,26 @@ public class UploadFileOperationTest { private OwnCloudClient client; private AccountManager accountManager; + private long userFreeQuota; public UploadFileOperationTest(){ TestUtils.loadServerCredentials(); accountManager = AccountManager.get(RuntimeEnvironment.application); TestUtils.prepareValidAccount(accountManager); ShadowLog.stream = System.out; + client = CommonUtils.getOwnCloudClient(CommonUtils.getAccount(TestUtils.TEST_ACCOUNT_NAME, TestUtils.TEST_ACCOUNT_TYPE, accountManager), RuntimeEnvironment.application); + + try { + TestUtils.testConnection(client, RuntimeEnvironment.application); + }catch(Exception e){ + System.out.println("test connection failed: "+e.getMessage()); + } + userFreeQuota = getUserRemoteFreeQuota(); } @Before public void setUp(){ prepareDB(); //Create DB - client = CommonUtils.getOwnCloudClient(CommonUtils.getAccount(TestUtils.TEST_ACCOUNT_NAME, TestUtils.TEST_ACCOUNT_TYPE, accountManager), RuntimeEnvironment.application); Assert.assertNotNull("Client is null. unexpected!", client); } @@ -148,12 +156,6 @@ public class UploadFileOperationTest { removeSmallFile(); //clean the environnement createSmallFile(); //preparation - try { - TestUtils.testConnection(client, RuntimeEnvironment.application); - }catch(Exception e){ - Assert.fail(e.getMessage()); - } - final SyncedFileState sfs_fromDB = DbHelper.loadSyncedFile(RuntimeEnvironment.application, syncedFileStates.get(0).getLocalPath(), true); Assert.assertTrue("SyncedFileState loaded from DB must have an empty Etag", sfs_fromDB.getLastETAG().isEmpty()); @@ -225,12 +227,12 @@ public class UploadFileOperationTest { */ @Test public void fileSizeBiggerThanFreeQuota_shouldnotBeAllowed(){ - long freeQuota = getUserRemoteFreeQuota(); - Assert.assertFalse("Reading remote free quota fails"+freeQuota, -1 == freeQuota); + //long freeQuota = getUserRemoteFreeQuota(); + Assert.assertFalse("Reading remote free quota fails"+userFreeQuota, -1 == userFreeQuota); //We don't care of parameter of UploadFileOperation's constructor RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false) - .checkAvailableSpace(client, (freeQuota+1)); - Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), RemoteOperationResult.ResultCode.QUOTA_EXCEEDED, actualResult.getCode()); + .checkAvailableSpace(client, (userFreeQuota+1)); + Assert.assertEquals("Quota check ("+ userFreeQuota+"vs"+(userFreeQuota+1)+") failed", RemoteOperationResult.ResultCode.QUOTA_EXCEEDED, actualResult.getCode()); } /** @@ -240,12 +242,12 @@ public class UploadFileOperationTest { @Test public void fileSizeEqualToFreeQuota_shouldnotBeAllowed(){ //I don't know why but it always fail for this test. - long freeQuota = getUserRemoteFreeQuota(); - Assert.assertFalse("Reading remote free quota fails"+freeQuota, -1 == freeQuota); + //long freeQuota = getUserRemoteFreeQuota(); + Assert.assertFalse("Reading remote free quota fails"+userFreeQuota, -1 == userFreeQuota); RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false) - .checkAvailableSpace(client, freeQuota); - Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), + .checkAvailableSpace(client, userFreeQuota); + Assert.assertEquals("Quota check ("+ userFreeQuota+" vs "+userFreeQuota+") failed", RemoteOperationResult.ResultCode.QUOTA_EXCEEDED, actualResult.getCode()); } @@ -257,12 +259,12 @@ public class UploadFileOperationTest { */ @Test public void fileSizeSmallerThanFreeQuota_shouldBeAllowed(){ - long freeQuota = getUserRemoteFreeQuota(); - Assert.assertFalse("Reading remote free quota fails "+freeQuota, -1 == freeQuota); + //long freeQuota = getUserRemoteFreeQuota(); + Assert.assertFalse("Reading remote free quota fails "+userFreeQuota, -1 == userFreeQuota); RemoteOperationResult actualResult = new UploadFileOperation(Mockito.mock(SyncedFileState.class), false) - .checkAvailableSpace(client, (freeQuota-1)); - Assert.assertEquals("Quota check should return QUOTA_EXCEEDED but got "+actualResult.getCode().name(), + .checkAvailableSpace(client, (userFreeQuota-1)); + Assert.assertEquals("Quota check ("+ userFreeQuota+" vs "+(userFreeQuota-1)+") failed", RemoteOperationResult.ResultCode.OK, actualResult.getCode()); -- GitLab