AbstractIT.java 19 KB

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