AbstractIT.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. package com.owncloud.android;
  2. import android.accounts.Account;
  3. import android.accounts.AccountManager;
  4. import android.accounts.AuthenticatorException;
  5. import android.accounts.OperationCanceledException;
  6. import android.app.Activity;
  7. import android.content.ActivityNotFoundException;
  8. import android.content.Context;
  9. import android.net.Uri;
  10. import android.os.Bundle;
  11. import com.facebook.testing.screenshot.Screenshot;
  12. import com.nextcloud.client.RetryTestRule;
  13. import com.nextcloud.client.account.UserAccountManager;
  14. import com.nextcloud.client.account.UserAccountManagerImpl;
  15. import com.nextcloud.client.device.BatteryStatus;
  16. import com.nextcloud.client.device.PowerManagementService;
  17. import com.nextcloud.client.network.Connectivity;
  18. import com.nextcloud.client.network.ConnectivityService;
  19. import com.owncloud.android.datamodel.FileDataStorageManager;
  20. import com.owncloud.android.datamodel.OCFile;
  21. import com.owncloud.android.datamodel.UploadsStorageManager;
  22. import com.owncloud.android.db.OCUpload;
  23. import com.owncloud.android.files.services.FileUploader;
  24. import com.owncloud.android.lib.common.OwnCloudClient;
  25. import com.owncloud.android.lib.common.OwnCloudClientFactory;
  26. import com.owncloud.android.lib.common.accounts.AccountUtils;
  27. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  28. import com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation;
  29. import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation;
  30. import com.owncloud.android.lib.resources.files.RemoveFileRemoteOperation;
  31. import com.owncloud.android.lib.resources.files.model.RemoteFile;
  32. import com.owncloud.android.operations.CreateFolderOperation;
  33. import com.owncloud.android.operations.UploadFileOperation;
  34. import com.owncloud.android.utils.FileStorageUtils;
  35. import junit.framework.TestCase;
  36. import org.apache.commons.httpclient.HttpStatus;
  37. import org.apache.commons.httpclient.methods.GetMethod;
  38. import org.apache.commons.io.FileUtils;
  39. import org.jetbrains.annotations.NotNull;
  40. import org.junit.After;
  41. import org.junit.Assert;
  42. import org.junit.BeforeClass;
  43. import org.junit.Rule;
  44. import java.io.File;
  45. import java.io.FileWriter;
  46. import java.io.IOException;
  47. import java.io.InputStream;
  48. import java.util.Collection;
  49. import androidx.test.espresso.contrib.DrawerActions;
  50. import androidx.test.espresso.intent.rule.IntentsTestRule;
  51. import androidx.test.platform.app.InstrumentationRegistry;
  52. import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
  53. import androidx.test.runner.lifecycle.Stage;
  54. import static androidx.test.InstrumentationRegistry.getInstrumentation;
  55. import static androidx.test.espresso.Espresso.onView;
  56. import static androidx.test.espresso.matcher.ViewMatchers.withId;
  57. import static org.junit.Assert.assertTrue;
  58. /**
  59. * Common base for all integration tests
  60. */
  61. public abstract class AbstractIT {
  62. @Rule public RetryTestRule retryTestRule = new RetryTestRule();
  63. protected static OwnCloudClient client;
  64. protected static Account account;
  65. protected static Context targetContext;
  66. private Activity currentActivity;
  67. protected FileDataStorageManager fileDataStorageManager =
  68. new FileDataStorageManager(account, targetContext.getContentResolver());
  69. @BeforeClass
  70. public static void beforeAll() {
  71. try {
  72. targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
  73. Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
  74. Uri baseUrl = Uri.parse(arguments.getString("TEST_SERVER_URL"));
  75. String loginName = arguments.getString("TEST_SERVER_USERNAME");
  76. String password = arguments.getString("TEST_SERVER_PASSWORD");
  77. Account temp = new Account(loginName + "@" + baseUrl, MainApp.getAccountType(targetContext));
  78. UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
  79. if (!accountManager.exists(temp)) {
  80. AccountManager platformAccountManager = AccountManager.get(targetContext);
  81. platformAccountManager.addAccountExplicitly(temp, password, null);
  82. platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
  83. Integer.toString(UserAccountManager.ACCOUNT_VERSION));
  84. platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_VERSION, "14.0.0.0");
  85. platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, baseUrl.toString());
  86. platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_USER_ID, loginName); // same as userId
  87. }
  88. final UserAccountManager userAccountManager = UserAccountManagerImpl.fromContext(targetContext);
  89. account = userAccountManager.getAccountByName(loginName + "@" + baseUrl);
  90. if (account == null) {
  91. throw new ActivityNotFoundException();
  92. }
  93. client = OwnCloudClientFactory.createOwnCloudClient(account, targetContext);
  94. createDummyFiles();
  95. waitForServer(client, baseUrl);
  96. // deleteAllFiles(); // makes sure that no file/folder is in root
  97. } catch (OperationCanceledException e) {
  98. e.printStackTrace();
  99. } catch (AuthenticatorException e) {
  100. e.printStackTrace();
  101. } catch (IOException e) {
  102. e.printStackTrace();
  103. } catch (AccountUtils.AccountNotFoundException e) {
  104. e.printStackTrace();
  105. }
  106. }
  107. @After
  108. public void after() {
  109. deleteAllFiles();
  110. }
  111. public static void deleteAllFiles() {
  112. RemoteOperationResult result = new ReadFolderRemoteOperation("/").execute(client);
  113. assertTrue(result.getLogMessage(), result.isSuccess());
  114. for (Object object : result.getData()) {
  115. RemoteFile remoteFile = (RemoteFile) object;
  116. if (!remoteFile.getRemotePath().equals("/")) {
  117. if (remoteFile.isEncrypted()) {
  118. assertTrue(new ToggleEncryptionRemoteOperation(remoteFile.getLocalId(),
  119. remoteFile.getRemotePath(),
  120. false)
  121. .execute(client)
  122. .isSuccess());
  123. }
  124. assertTrue(new RemoveFileRemoteOperation(remoteFile.getRemotePath())
  125. .execute(client)
  126. .isSuccess()
  127. );
  128. }
  129. }
  130. }
  131. protected FileDataStorageManager getStorageManager() {
  132. return fileDataStorageManager;
  133. }
  134. protected Account[] getAllAccounts() {
  135. return AccountManager.get(targetContext).getAccounts();
  136. }
  137. private static void createDummyFiles() throws IOException {
  138. new File(FileStorageUtils.getSavePath(account.name)).mkdirs();
  139. createFile("empty.txt", 0);
  140. createFile("nonEmpty.txt", 100);
  141. createFile("chunkedFile.txt", 500000);
  142. }
  143. public static void createFile(String name, int iteration) throws IOException {
  144. File file = new File(FileStorageUtils.getSavePath(account.name) + File.separator + name);
  145. file.createNewFile();
  146. FileWriter writer = new FileWriter(file);
  147. for (int i = 0; i < iteration; i++) {
  148. writer.write("123123123123123123123123123\n");
  149. }
  150. writer.flush();
  151. writer.close();
  152. }
  153. private static void waitForServer(OwnCloudClient client, Uri baseUrl) {
  154. GetMethod get = new GetMethod(baseUrl + "/status.php");
  155. try {
  156. int i = 0;
  157. while (client.executeMethod(get) != HttpStatus.SC_OK && i < 3) {
  158. System.out.println("wait…");
  159. Thread.sleep(60 * 1000);
  160. i++;
  161. }
  162. if (i == 3) {
  163. Assert.fail("Server not ready!");
  164. }
  165. } catch (IOException e) {
  166. e.printStackTrace();
  167. } catch (InterruptedException e) {
  168. e.printStackTrace();
  169. }
  170. }
  171. protected File getFile(String filename) throws IOException {
  172. InputStream inputStream = getInstrumentation().getContext().getAssets().open(filename);
  173. File temp = File.createTempFile("file", "file");
  174. FileUtils.copyInputStreamToFile(inputStream, temp);
  175. return temp;
  176. }
  177. protected void waitForIdleSync() {
  178. InstrumentationRegistry.getInstrumentation().waitForIdleSync();
  179. }
  180. protected void openDrawer(IntentsTestRule activityRule) {
  181. Activity sut = activityRule.launchActivity(null);
  182. shortSleep();
  183. onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
  184. waitForIdleSync();
  185. Screenshot.snapActivity(sut).record();
  186. }
  187. protected Activity getCurrentActivity() {
  188. InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
  189. Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry
  190. .getInstance()
  191. .getActivitiesInStage(Stage.RESUMED);
  192. if (resumedActivities.iterator().hasNext()) {
  193. currentActivity = resumedActivities.iterator().next();
  194. }
  195. });
  196. return currentActivity;
  197. }
  198. protected void shortSleep() {
  199. try {
  200. Thread.sleep(2000);
  201. } catch (InterruptedException e) {
  202. e.printStackTrace();
  203. }
  204. }
  205. protected void longSleep() {
  206. try {
  207. Thread.sleep(20000);
  208. } catch (InterruptedException e) {
  209. e.printStackTrace();
  210. }
  211. }
  212. public OCFile createFolder(String remotePath) {
  213. TestCase.assertTrue(new CreateFolderOperation(remotePath, account, targetContext)
  214. .execute(client, getStorageManager())
  215. .isSuccess());
  216. return getStorageManager().getFileByDecryptedRemotePath(remotePath);
  217. }
  218. public void uploadOCUpload(OCUpload ocUpload) {
  219. ConnectivityService connectivityServiceMock = new ConnectivityService() {
  220. @Override
  221. public boolean isInternetWalled() {
  222. return false;
  223. }
  224. @Override
  225. public Connectivity getConnectivity() {
  226. return Connectivity.CONNECTED_WIFI;
  227. }
  228. };
  229. PowerManagementService powerManagementServiceMock = new PowerManagementService() {
  230. @NotNull
  231. @Override
  232. public BatteryStatus getBattery() {
  233. return new BatteryStatus();
  234. }
  235. @Override
  236. public boolean isPowerSavingEnabled() {
  237. return false;
  238. }
  239. @Override
  240. public boolean isPowerSavingExclusionAvailable() {
  241. return false;
  242. }
  243. };
  244. UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
  245. UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(accountManager,
  246. targetContext.getContentResolver());
  247. UploadFileOperation newUpload = new UploadFileOperation(
  248. uploadsStorageManager,
  249. connectivityServiceMock,
  250. powerManagementServiceMock,
  251. account,
  252. null,
  253. ocUpload,
  254. FileUploader.NameCollisionPolicy.DEFAULT,
  255. FileUploader.LOCAL_BEHAVIOUR_COPY,
  256. targetContext,
  257. false,
  258. false
  259. );
  260. newUpload.addRenameUploadListener(() -> {
  261. // dummy
  262. });
  263. newUpload.setRemoteFolderToBeCreated();
  264. RemoteOperationResult result = newUpload.execute(client, getStorageManager());
  265. assertTrue(result.getLogMessage(), result.isSuccess());
  266. }
  267. }