AbstractIT.java 17 KB

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