AbstractIT.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 onIdleSync(Runnable recipient) {
  251. InstrumentationRegistry.getInstrumentation().waitForIdle(recipient);
  252. }
  253. protected void openDrawer(IntentsTestRule activityRule) {
  254. Activity sut = activityRule.launchActivity(null);
  255. shortSleep();
  256. onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
  257. waitForIdleSync();
  258. screenshot(sut);
  259. }
  260. protected Activity getCurrentActivity() {
  261. InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
  262. Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry
  263. .getInstance()
  264. .getActivitiesInStage(Stage.RESUMED);
  265. if (resumedActivities.iterator().hasNext()) {
  266. currentActivity = resumedActivities.iterator().next();
  267. }
  268. });
  269. return currentActivity;
  270. }
  271. protected static void shortSleep() {
  272. try {
  273. Thread.sleep(2000);
  274. } catch (InterruptedException e) {
  275. e.printStackTrace();
  276. }
  277. }
  278. protected void longSleep() {
  279. try {
  280. Thread.sleep(20000);
  281. } catch (InterruptedException e) {
  282. e.printStackTrace();
  283. }
  284. }
  285. protected void sleep(int second) {
  286. try {
  287. Thread.sleep(1000L * second);
  288. } catch (InterruptedException e) {
  289. e.printStackTrace();
  290. }
  291. }
  292. public OCFile createFolder(String remotePath) {
  293. RemoteOperationResult check = new ExistenceCheckRemoteOperation(remotePath, false).execute(client);
  294. if (!check.isSuccess()) {
  295. assertTrue(new CreateFolderOperation(remotePath, user, targetContext, getStorageManager())
  296. .execute(client)
  297. .isSuccess());
  298. }
  299. return getStorageManager().getFileByDecryptedRemotePath(remotePath.endsWith("/") ? remotePath : remotePath + "/");
  300. }
  301. public void uploadFile(File file, String remotePath) {
  302. OCUpload ocUpload = new OCUpload(file.getAbsolutePath(), remotePath, account.name);
  303. uploadOCUpload(ocUpload);
  304. }
  305. public void uploadOCUpload(OCUpload ocUpload) {
  306. ConnectivityService connectivityServiceMock = new ConnectivityService() {
  307. @Override
  308. public boolean isConnected() {
  309. return false;
  310. }
  311. @Override
  312. public boolean isInternetWalled() {
  313. return false;
  314. }
  315. @Override
  316. public Connectivity getConnectivity() {
  317. return Connectivity.CONNECTED_WIFI;
  318. }
  319. };
  320. PowerManagementService powerManagementServiceMock = new PowerManagementService() {
  321. @NonNull
  322. @Override
  323. public BatteryStatus getBattery() {
  324. return new BatteryStatus();
  325. }
  326. @Override
  327. public boolean isPowerSavingEnabled() {
  328. return false;
  329. }
  330. @Override
  331. public boolean isPowerSavingExclusionAvailable() {
  332. return false;
  333. }
  334. };
  335. UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
  336. UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(accountManager,
  337. targetContext.getContentResolver());
  338. UploadFileOperation newUpload = new UploadFileOperation(
  339. uploadsStorageManager,
  340. connectivityServiceMock,
  341. powerManagementServiceMock,
  342. user,
  343. null,
  344. ocUpload,
  345. NameCollisionPolicy.DEFAULT,
  346. FileUploadWorker.LOCAL_BEHAVIOUR_COPY,
  347. targetContext,
  348. false,
  349. false,
  350. getStorageManager()
  351. );
  352. newUpload.addRenameUploadListener(() -> {
  353. // dummy
  354. });
  355. newUpload.setRemoteFolderToBeCreated();
  356. RemoteOperationResult result = newUpload.execute(client);
  357. assertTrue(result.getLogMessage(), result.isSuccess());
  358. }
  359. protected void enableRTL() {
  360. Locale locale = new Locale("ar");
  361. Resources resources = InstrumentationRegistry.getInstrumentation().getTargetContext().getResources();
  362. Configuration config = resources.getConfiguration();
  363. config.setLocale(locale);
  364. resources.updateConfiguration(config, null);
  365. }
  366. protected void resetLocale() {
  367. Locale locale = new Locale("en");
  368. Resources resources = InstrumentationRegistry.getInstrumentation().getTargetContext().getResources();
  369. Configuration config = resources.getConfiguration();
  370. config.setLocale(locale);
  371. resources.updateConfiguration(config, null);
  372. }
  373. protected void screenshot(View view) {
  374. screenshot(view, "");
  375. }
  376. protected void screenshotViaName(Activity activity, String name) {
  377. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
  378. Screenshot.snapActivity(activity).setName(name).record();
  379. }
  380. }
  381. protected void screenshot(View view, String prefix) {
  382. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
  383. Screenshot.snap(view).setName(createName(prefix)).record();
  384. }
  385. }
  386. protected void screenshot(Activity sut) {
  387. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
  388. Screenshot.snapActivity(sut).setName(createName()).record();
  389. }
  390. }
  391. protected void screenshot(DialogFragment dialogFragment, String prefix) {
  392. screenshot(Objects.requireNonNull(dialogFragment.requireDialog().getWindow()).getDecorView(), prefix);
  393. }
  394. private String createName() {
  395. return createName("");
  396. }
  397. private String createName(String prefix) {
  398. String name = TestNameDetector.getTestClass() + "_" + TestNameDetector.getTestName();
  399. if (!TextUtils.isEmpty(prefix)) {
  400. name = name + "_" + prefix;
  401. }
  402. if (!DARK_MODE.isEmpty()) {
  403. name = name + "_" + DARK_MODE;
  404. }
  405. if (!COLOR.isEmpty()) {
  406. name = name + "_" + COLOR;
  407. }
  408. return name;
  409. }
  410. public static String getUserId(User user) {
  411. return AccountManager.get(targetContext).getUserData(user.toPlatformAccount(), KEY_USER_ID);
  412. }
  413. public String getRandomName() {
  414. return getRandomName(5);
  415. }
  416. public String getRandomName(int length) {
  417. return RandomStringGenerator.make(length);
  418. }
  419. protected static User getUser(Account account) {
  420. Optional<User> optionalUser = UserAccountManagerImpl.fromContext(targetContext).getUser(account.name);
  421. return optionalUser.orElseThrow(IllegalAccessError::new);
  422. }
  423. protected static Account createAccount(String name) {
  424. AccountManager platformAccountManager = AccountManager.get(targetContext);
  425. Account temp = new Account(name, MainApp.getAccountType(targetContext));
  426. int atPos = name.lastIndexOf('@');
  427. platformAccountManager.addAccountExplicitly(temp, "password", null);
  428. platformAccountManager.setUserData(temp, AccountUtils.Constants.KEY_OC_BASE_URL,
  429. name.substring(atPos + 1));
  430. platformAccountManager.setUserData(temp, KEY_USER_ID, name.substring(0, atPos));
  431. Account account = UserAccountManagerImpl.fromContext(targetContext).getAccountByName(name);
  432. if (account == null) {
  433. throw new ActivityNotFoundException();
  434. }
  435. return account;
  436. }
  437. protected static boolean removeAccount(Account account) {
  438. return AccountManager.get(targetContext).removeAccountExplicitly(account);
  439. }
  440. }