AbstractIT.java 18 KB

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