AbstractIT.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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.os.Build;
  10. import android.os.Bundle;
  11. import android.text.TextUtils;
  12. import android.view.View;
  13. import com.facebook.testing.screenshot.Screenshot;
  14. import com.facebook.testing.screenshot.internal.TestNameDetector;
  15. import com.nextcloud.client.GrantStoragePermissionRule;
  16. import com.nextcloud.client.account.User;
  17. import com.nextcloud.client.account.UserAccountManager;
  18. import com.nextcloud.client.account.UserAccountManagerImpl;
  19. import com.nextcloud.client.device.BatteryStatus;
  20. import com.nextcloud.client.device.PowerManagementService;
  21. import com.nextcloud.client.network.Connectivity;
  22. import com.nextcloud.client.network.ConnectivityService;
  23. import com.nextcloud.client.preferences.AppPreferencesImpl;
  24. import com.nextcloud.client.preferences.DarkMode;
  25. import com.nextcloud.java.util.Optional;
  26. import com.owncloud.android.datamodel.FileDataStorageManager;
  27. import com.owncloud.android.datamodel.OCFile;
  28. import com.owncloud.android.datamodel.UploadsStorageManager;
  29. import com.owncloud.android.db.OCUpload;
  30. import com.owncloud.android.files.services.FileUploader;
  31. import com.owncloud.android.files.services.NameCollisionPolicy;
  32. import com.owncloud.android.lib.common.OwnCloudClient;
  33. import com.owncloud.android.lib.common.OwnCloudClientFactory;
  34. import com.owncloud.android.lib.common.accounts.AccountUtils;
  35. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  36. import com.owncloud.android.lib.resources.status.OCCapability;
  37. import com.owncloud.android.operations.CreateFolderOperation;
  38. import com.owncloud.android.operations.UploadFileOperation;
  39. import com.owncloud.android.utils.FileStorageUtils;
  40. import junit.framework.TestCase;
  41. import org.apache.commons.io.FileUtils;
  42. import org.junit.Before;
  43. import org.junit.BeforeClass;
  44. import org.junit.Rule;
  45. import org.junit.rules.TestRule;
  46. import java.io.File;
  47. import java.io.FileWriter;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.util.Collection;
  51. import java.util.Objects;
  52. import androidx.annotation.NonNull;
  53. import androidx.fragment.app.DialogFragment;
  54. import androidx.test.espresso.contrib.DrawerActions;
  55. import androidx.test.espresso.intent.rule.IntentsTestRule;
  56. import androidx.test.platform.app.InstrumentationRegistry;
  57. import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
  58. import androidx.test.runner.lifecycle.Stage;
  59. import static androidx.test.InstrumentationRegistry.getInstrumentation;
  60. import static androidx.test.espresso.Espresso.onView;
  61. import static androidx.test.espresso.matcher.ViewMatchers.withId;
  62. import static com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID;
  63. import static org.junit.Assert.assertTrue;
  64. /**
  65. * Common base for all integration tests
  66. */
  67. public abstract class AbstractIT {
  68. @Rule
  69. public final TestRule permissionRule = GrantStoragePermissionRule.grant();
  70. protected static OwnCloudClient client;
  71. protected static Account account;
  72. protected static User user;
  73. protected static Context targetContext;
  74. protected static String DARK_MODE = "";
  75. protected static String COLOR = "";
  76. protected Activity currentActivity;
  77. protected FileDataStorageManager fileDataStorageManager =
  78. new FileDataStorageManager(user, targetContext.getContentResolver());
  79. @BeforeClass
  80. public static void beforeAll() {
  81. try {
  82. // clean up
  83. targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
  84. AccountManager platformAccountManager = AccountManager.get(targetContext);
  85. for (Account account : platformAccountManager.getAccounts()) {
  86. if (account.type.equalsIgnoreCase("nextcloud")) {
  87. platformAccountManager.removeAccountExplicitly(account);
  88. }
  89. }
  90. Account temp = new Account("test@https://nextcloud.localhost", MainApp.getAccountType(targetContext));
  91. platformAccountManager.addAccountExplicitly(temp, "password", null);
  92. platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL, "https://nextcloud.localhost");
  93. platformAccountManager.setUserData(temp, KEY_USER_ID, "test");
  94. final UserAccountManager userAccountManager = UserAccountManagerImpl.fromContext(targetContext);
  95. account = userAccountManager.getAccountByName("test@https://nextcloud.localhost");
  96. if (account == null) {
  97. throw new ActivityNotFoundException();
  98. }
  99. Optional<User> optionalUser = userAccountManager.getUser(account.name);
  100. user = optionalUser.orElseThrow(IllegalAccessError::new);
  101. client = OwnCloudClientFactory.createOwnCloudClient(account, targetContext);
  102. } catch (OperationCanceledException e) {
  103. e.printStackTrace();
  104. } catch (AuthenticatorException e) {
  105. e.printStackTrace();
  106. } catch (IOException e) {
  107. e.printStackTrace();
  108. } catch (AccountUtils.AccountNotFoundException e) {
  109. e.printStackTrace();
  110. }
  111. Bundle arguments = androidx.test.platform.app.InstrumentationRegistry.getArguments();
  112. // color
  113. String colorParameter = arguments.getString("COLOR");
  114. if (!TextUtils.isEmpty(colorParameter)) {
  115. FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(account,
  116. targetContext.getContentResolver());
  117. String colorHex = null;
  118. COLOR = colorParameter;
  119. switch (colorParameter) {
  120. case "red":
  121. colorHex = "#7c0000";
  122. break;
  123. case "green":
  124. colorHex = "#00ff00";
  125. break;
  126. case "white":
  127. colorHex = "#ffffff";
  128. break;
  129. case "black":
  130. colorHex = "#000000";
  131. break;
  132. case "lightgreen":
  133. colorHex = "#aaff00";
  134. break;
  135. default:
  136. break;
  137. }
  138. if (colorHex != null) {
  139. OCCapability capability = fileDataStorageManager.getCapability(account.name);
  140. capability.setServerColor(colorHex);
  141. fileDataStorageManager.saveCapabilities(capability);
  142. }
  143. }
  144. // dark / light
  145. String darkModeParameter = arguments.getString("DARKMODE");
  146. if (darkModeParameter != null) {
  147. if (darkModeParameter.equalsIgnoreCase("dark")) {
  148. DARK_MODE = "dark";
  149. AppPreferencesImpl.fromContext(targetContext).setDarkThemeMode(DarkMode.DARK);
  150. MainApp.setAppTheme(DarkMode.DARK);
  151. } else {
  152. DARK_MODE = "light";
  153. }
  154. }
  155. if (DARK_MODE.equalsIgnoreCase("light") && COLOR.equalsIgnoreCase("blue")) {
  156. // use already existing names
  157. DARK_MODE = "";
  158. COLOR = "";
  159. }
  160. }
  161. @Before
  162. public void enableAccessibilityChecks() {
  163. androidx.test.espresso.accessibility.AccessibilityChecks.enable().setRunChecksFromRootView(true);
  164. }
  165. protected FileDataStorageManager getStorageManager() {
  166. return fileDataStorageManager;
  167. }
  168. protected Account[] getAllAccounts() {
  169. return AccountManager.get(targetContext).getAccounts();
  170. }
  171. protected static void createDummyFiles() throws IOException {
  172. File tempPath = new File(FileStorageUtils.getTemporalPath(account.name));
  173. if (!tempPath.exists()) {
  174. assertTrue(tempPath.mkdirs());
  175. }
  176. assertTrue(tempPath.exists());
  177. createFile("empty.txt", 0);
  178. createFile("nonEmpty.txt", 100);
  179. createFile("chunkedFile.txt", 500000);
  180. }
  181. protected static File getDummyFile(String name) throws IOException {
  182. File file = new File(FileStorageUtils.getInternalTemporalPath(account.name, targetContext) + File.separator + name);
  183. if (file.exists()) {
  184. return file;
  185. } else if (name.endsWith("/")) {
  186. file.mkdirs();
  187. return file;
  188. } else {
  189. switch (name) {
  190. case "empty.txt":
  191. return createFile("empty.txt", 0);
  192. case "nonEmpty.txt":
  193. return createFile("nonEmpty.txt", 100);
  194. case "chunkedFile.txt":
  195. return createFile("chunkedFile.txt", 500000);
  196. default:
  197. return createFile(name, 0);
  198. }
  199. }
  200. }
  201. public static File createFile(String name, int iteration) throws IOException {
  202. File file = new File(FileStorageUtils.getTemporalPath(account.name) + File.separator + name);
  203. if (!file.getParentFile().exists()) {
  204. assertTrue(file.getParentFile().mkdirs());
  205. }
  206. file.createNewFile();
  207. FileWriter writer = new FileWriter(file);
  208. for (int i = 0; i < iteration; i++) {
  209. writer.write("123123123123123123123123123\n");
  210. }
  211. writer.flush();
  212. writer.close();
  213. return file;
  214. }
  215. protected File getFile(String filename) throws IOException {
  216. InputStream inputStream = getInstrumentation().getContext().getAssets().open(filename);
  217. File temp = File.createTempFile("file", "file");
  218. FileUtils.copyInputStreamToFile(inputStream, temp);
  219. return temp;
  220. }
  221. protected void waitForIdleSync() {
  222. InstrumentationRegistry.getInstrumentation().waitForIdleSync();
  223. }
  224. protected void openDrawer(IntentsTestRule activityRule) {
  225. Activity sut = activityRule.launchActivity(null);
  226. shortSleep();
  227. onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
  228. waitForIdleSync();
  229. screenshot(sut);
  230. }
  231. protected Activity getCurrentActivity() {
  232. InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
  233. Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry
  234. .getInstance()
  235. .getActivitiesInStage(Stage.RESUMED);
  236. if (resumedActivities.iterator().hasNext()) {
  237. currentActivity = resumedActivities.iterator().next();
  238. }
  239. });
  240. return currentActivity;
  241. }
  242. protected void shortSleep() {
  243. try {
  244. Thread.sleep(2000);
  245. } catch (InterruptedException e) {
  246. e.printStackTrace();
  247. }
  248. }
  249. protected void longSleep() {
  250. try {
  251. Thread.sleep(20000);
  252. } catch (InterruptedException e) {
  253. e.printStackTrace();
  254. }
  255. }
  256. public OCFile createFolder(String remotePath) {
  257. TestCase.assertTrue(new CreateFolderOperation(remotePath, user, targetContext, getStorageManager())
  258. .execute(client)
  259. .isSuccess());
  260. return getStorageManager().getFileByDecryptedRemotePath(remotePath);
  261. }
  262. public void uploadOCUpload(OCUpload ocUpload) {
  263. ConnectivityService connectivityServiceMock = new ConnectivityService() {
  264. @Override
  265. public boolean isInternetWalled() {
  266. return false;
  267. }
  268. @Override
  269. public Connectivity getConnectivity() {
  270. return Connectivity.CONNECTED_WIFI;
  271. }
  272. };
  273. PowerManagementService powerManagementServiceMock = new PowerManagementService() {
  274. @NonNull
  275. @Override
  276. public BatteryStatus getBattery() {
  277. return new BatteryStatus();
  278. }
  279. @Override
  280. public boolean isPowerSavingEnabled() {
  281. return false;
  282. }
  283. @Override
  284. public boolean isPowerSavingExclusionAvailable() {
  285. return false;
  286. }
  287. };
  288. UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
  289. UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(accountManager,
  290. targetContext.getContentResolver());
  291. UploadFileOperation newUpload = new UploadFileOperation(
  292. uploadsStorageManager,
  293. connectivityServiceMock,
  294. powerManagementServiceMock,
  295. user,
  296. null,
  297. ocUpload,
  298. NameCollisionPolicy.DEFAULT,
  299. FileUploader.LOCAL_BEHAVIOUR_COPY,
  300. targetContext,
  301. false,
  302. false,
  303. getStorageManager()
  304. );
  305. newUpload.addRenameUploadListener(() -> {
  306. // dummy
  307. });
  308. newUpload.setRemoteFolderToBeCreated();
  309. RemoteOperationResult result = newUpload.execute(client);
  310. assertTrue(result.getLogMessage(), result.isSuccess());
  311. }
  312. protected void screenshot(View view) {
  313. screenshot(view, "");
  314. }
  315. protected void screenshot(View view, String prefix) {
  316. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
  317. Screenshot.snap(view).setName(createName(prefix)).record();
  318. }
  319. }
  320. protected void screenshot(Activity sut) {
  321. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
  322. Screenshot.snapActivity(sut).setName(createName()).record();
  323. }
  324. }
  325. protected void screenshot(DialogFragment dialogFragment, String prefix) {
  326. screenshot(Objects.requireNonNull(dialogFragment.requireDialog().getWindow()).getDecorView(), prefix);
  327. }
  328. private String createName() {
  329. return createName("");
  330. }
  331. private String createName(String prefix) {
  332. String name = TestNameDetector.getTestClass() + "_" + TestNameDetector.getTestName();
  333. if (!TextUtils.isEmpty(prefix)) {
  334. name = name + "_" + prefix;
  335. }
  336. if (!DARK_MODE.isEmpty()) {
  337. name = name + "_" + DARK_MODE;
  338. }
  339. if (!COLOR.isEmpty()) {
  340. name = name + "_" + COLOR;
  341. }
  342. return name;
  343. }
  344. public static String getUserId(User user) {
  345. return AccountManager.get(targetContext).getUserData(user.toPlatformAccount(), KEY_USER_ID);
  346. }
  347. }