-
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathMainActivityTests.java
More file actions
418 lines (352 loc) · 17.4 KB
/
MainActivityTests.java
File metadata and controls
418 lines (352 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package at.tomtasche.reader.test;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.clearText;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.isEnabled;
import static androidx.test.espresso.matcher.ViewMatchers.withClassName;
import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.equalTo;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.SystemClock;
import android.util.ArrayMap;
import android.util.Log;
import androidx.core.content.FileProvider;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.espresso.IdlingResource;
import androidx.test.espresso.intent.Intents;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import at.tomtasche.reader.R;
import at.tomtasche.reader.ui.EditActionModeCallback;
import at.tomtasche.reader.ui.activity.MainActivity;
import at.tomtasche.reader.ui.activity.DocumentFragment;
import at.tomtasche.reader.ui.widget.PageView;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTests {
private IdlingResource m_idlingResource;
private static final Map<String, File> s_testFiles = new ArrayMap<>();
// Yes, this is ActivityTestRule instead of ActivityScenario, because ActivityScenario does not actually work.
// Issue ID may or may not be added later.
// Launch activity manually to ensure complete restart between tests
@Rule
public ActivityTestRule<MainActivity> mainActivityActivityTestRule = new ActivityTestRule<>(MainActivity.class, false, false);
@Before
public void setUp() {
// Launch a fresh activity for each test
MainActivity mainActivity = mainActivityActivityTestRule.launchActivity(null);
m_idlingResource = mainActivity.getOpenFileIdlingResource();
IdlingRegistry.getInstance().register(m_idlingResource);
// Close system dialogs which may cover our Activity.
// Happens frequently on slow emulators.
mainActivity.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
Intents.init();
// Log test setup for debugging
Log.d("MainActivityTests", "setUp() called for test: " + getClass().getName());
}
@After
public void tearDown() {
Log.d("MainActivityTests", "tearDown() called");
Intents.release();
if (null != m_idlingResource) {
IdlingRegistry.getInstance().unregister(m_idlingResource);
}
// Finish and wait for activity to be destroyed
MainActivity activity = mainActivityActivityTestRule.getActivity();
if (activity != null) {
mainActivityActivityTestRule.finishActivity();
// Use Instrumentation to wait until activity is destroyed
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
}
}
private static void copy(InputStream src, File dst) throws IOException {
try (OutputStream out = new FileOutputStream(dst)) {
byte[] buf = new byte[1024];
int len;
while ((len = src.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
@BeforeClass
public static void extractTestFiles() throws IOException {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
Context appContext = instrumentation.getTargetContext();
File appCacheDir = appContext.getCacheDir();
File testDocumentsDir = new File(appCacheDir, "test-documents");
testDocumentsDir.mkdirs();
Assert.assertTrue(testDocumentsDir.exists());
AssetManager testAssetManager = instrumentation.getContext().getAssets();
for (String filename: new String[] {"test.odt", "dummy.pdf", "password-test.odt", "style-various-1.docx"}) {
File targetFile = new File(testDocumentsDir, filename);
try (InputStream inputStream = testAssetManager.open(filename)) {
copy(inputStream, targetFile);
}
s_testFiles.put(filename, targetFile);
}
}
@AfterClass
public static void cleanupTestFiles() {
for (File file: s_testFiles.values()) {
file.delete();
}
}
@Test
public void testODT() {
File testFile = s_testFiles.get("test.odt");
Assert.assertNotNull(testFile);
Context appCtx = InstrumentationRegistry.getInstrumentation().getTargetContext();
Uri testFileUri = FileProvider.getUriForFile(appCtx, appCtx.getPackageName() + ".provider", testFile);
Intents.intending(hasAction(Intent.ACTION_OPEN_DOCUMENT)).respondWith(
new Instrumentation.ActivityResult(Activity.RESULT_OK,
new Intent()
.setData(testFileUri)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
)
);
onView(allOf(withId(R.id.menu_open), withContentDescription("Open document"), isDisplayed()))
.perform(click());
// The menu item could be either Documents or Files.
onView(allOf(withId(android.R.id.text1), anyOf(withText("Documents"), withText("Files")), isDisplayed()))
.perform(click());
// next onView will be blocked until m_idlingResource is idle.
onView(allOf(withId(R.id.menu_edit), withContentDescription("Edit document"), isEnabled()))
.withFailureHandler((error, viewMatcher) -> {
// fails on small screens, try again with overflow menu
onView(allOf(withContentDescription("More options"), isDisplayed())).perform(click());
onView(allOf(withId(R.id.menu_edit), withContentDescription("Edit document"), isDisplayed()))
.perform(click());
});
}
@Test
public void testPDF() {
File testFile = s_testFiles.get("dummy.pdf");
Assert.assertNotNull(testFile);
Context appCtx = InstrumentationRegistry.getInstrumentation().getTargetContext();
Uri testFileUri = FileProvider.getUriForFile(appCtx, appCtx.getPackageName() + ".provider", testFile);
Intents.intending(hasAction(Intent.ACTION_OPEN_DOCUMENT)).respondWith(
new Instrumentation.ActivityResult(Activity.RESULT_OK,
new Intent()
.setData(testFileUri)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
)
);
onView(allOf(withId(R.id.menu_open), withContentDescription("Open document"), isDisplayed()))
.perform(click());
// The menu item could be either Documents or Files.
onView(allOf(withId(android.R.id.text1), anyOf(withText("Documents"), withText("Files")), isDisplayed()))
.perform(click());
// next onView will be blocked until m_idlingResource is idle.
onView(allOf(withId(R.id.menu_edit), withContentDescription("Edit document"), isEnabled()))
.withFailureHandler((error, viewMatcher) -> {
// fails on small screens, try again with overflow menu
onView(allOf(withContentDescription("More options"), isDisplayed())).perform(click());
onView(allOf(withId(R.id.menu_edit), withContentDescription("Edit document"), isDisplayed()))
.perform(click());
});
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Test
public void testPasswordProtectedODT() {
File testFile = s_testFiles.get("password-test.odt");
Assert.assertNotNull(testFile);
// Check if the file exists and is readable
Assert.assertTrue("Password test file does not exist: " + testFile.getAbsolutePath(), testFile.exists());
Assert.assertTrue("Password test file is not readable: " + testFile.getAbsolutePath(), testFile.canRead());
// Log file info for debugging CI issues
Log.d("MainActivityTests", "Password test file path: " + testFile.getAbsolutePath());
Log.d("MainActivityTests", "Password test file size: " + testFile.length());
Log.d("MainActivityTests", "All test files: " + s_testFiles.keySet());
// Double-check we're using the right file
Assert.assertEquals("password-test.odt file size mismatch", 12671L, testFile.length());
Context appCtx = InstrumentationRegistry.getInstrumentation().getTargetContext();
Uri testFileUri = FileProvider.getUriForFile(appCtx, appCtx.getPackageName() + ".provider", testFile);
Intents.intending(hasAction(Intent.ACTION_OPEN_DOCUMENT)).respondWith(
new Instrumentation.ActivityResult(Activity.RESULT_OK,
new Intent()
.setData(testFileUri)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
)
);
onView(allOf(withId(R.id.menu_open), withContentDescription("Open document"), isDisplayed()))
.perform(click());
onView(allOf(withId(android.R.id.text1), anyOf(withText("Documents"), withText("Files")), isDisplayed()))
.perform(click());
// Wait for the password dialog to appear
onView(withText("This document is password-protected"))
.check(matches(isDisplayed()));
// Enter wrong password first
onView(withClassName(equalTo("android.widget.EditText")))
.perform(typeText("wrongpassword"));
onView(withId(android.R.id.button1))
.perform(click());
// Should show password dialog again for wrong password
onView(withText("This document is password-protected"))
.check(matches(isDisplayed()));
// Clear the text field and enter correct password
onView(withClassName(equalTo("android.widget.EditText")))
.perform(clearText(), typeText("passwort"));
onView(withId(android.R.id.button1))
.perform(click());
// Check if edit button becomes available (indicating successful load)
onView(allOf(withId(R.id.menu_edit), withContentDescription("Edit document"), isEnabled()))
.withFailureHandler((error, viewMatcher) -> {
onView(allOf(withContentDescription("More options"), isDisplayed())).perform(click());
onView(allOf(withId(R.id.menu_edit), withContentDescription("Edit document"), isDisplayed()))
.perform(click());
});
}
@Test
public void testODTEditMode() throws InterruptedException {
File testFile = s_testFiles.get("test.odt");
Assert.assertNotNull(testFile);
MainActivity activity = mainActivityActivityTestRule.getActivity();
DocumentFragment documentFragment = loadDocument(activity, testFile);
enterEditMode(activity, documentFragment);
PageView pageView = documentFragment.getPageView();
Assert.assertNotNull(pageView);
Assert.assertTrue(
"ODT should become editable after entering edit mode",
waitForEditableState(pageView, true, 10000)
);
}
@Test
public void testDOCXEditMode() throws InterruptedException {
File testFile = s_testFiles.get("style-various-1.docx");
Assert.assertNotNull(testFile);
MainActivity activity = mainActivityActivityTestRule.getActivity();
DocumentFragment documentFragment = loadDocument(activity, testFile);
enterEditMode(activity, documentFragment);
PageView pageView = documentFragment.getPageView();
Assert.assertNotNull(pageView);
Assert.assertTrue(
"DOCX should become editable after entering edit mode",
waitForEditableState(pageView, true, 10000)
);
}
private DocumentFragment loadDocument(MainActivity activity, File testFile) throws InterruptedException {
Context appCtx = InstrumentationRegistry.getInstrumentation().getTargetContext();
Uri testFileUri = FileProvider.getUriForFile(appCtx, appCtx.getPackageName() + ".provider", testFile);
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> activity.loadUri(testFileUri));
DocumentFragment fragment = waitForDocumentFragment(activity, 10000);
Assert.assertNotNull(fragment);
Assert.assertTrue("Timed out waiting for document to load", waitForLastResult(fragment, 10000));
return fragment;
}
private DocumentFragment waitForDocumentFragment(MainActivity activity, long timeoutMs)
throws InterruptedException {
long startMs = SystemClock.elapsedRealtime();
DocumentFragment fragment;
do {
fragment = (DocumentFragment) activity.getSupportFragmentManager()
.findFragmentByTag("document_fragment");
if (fragment != null) {
return fragment;
}
SystemClock.sleep(100);
} while (SystemClock.elapsedRealtime() - startMs < timeoutMs);
return null;
}
private boolean waitForLastResult(DocumentFragment fragment, long timeoutMs) throws InterruptedException {
long startMs = SystemClock.elapsedRealtime();
while (SystemClock.elapsedRealtime() - startMs < timeoutMs) {
if (fragment.hasLastResult()) {
return true;
}
SystemClock.sleep(100);
}
return false;
}
private void enterEditMode(MainActivity activity, DocumentFragment documentFragment) {
AtomicReference<Boolean> started = new AtomicReference<>(false);
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
started.set(activity.startSupportActionMode(
new EditActionModeCallback(activity, documentFragment)) != null);
});
Assert.assertTrue("Failed to enter edit mode", started.get());
}
private boolean waitForEditableState(PageView pageView, boolean expected, long timeoutMs)
throws InterruptedException {
long startMs = SystemClock.elapsedRealtime();
while (SystemClock.elapsedRealtime() - startMs < timeoutMs) {
if (expected == isEditableDom(pageView)) {
return true;
}
SystemClock.sleep(250);
}
return false;
}
private boolean waitForNonEditableState(PageView pageView, long timeoutMs) throws InterruptedException {
long startMs = SystemClock.elapsedRealtime();
while (SystemClock.elapsedRealtime() - startMs < timeoutMs) {
if (isEditableDom(pageView)) {
return false;
}
SystemClock.sleep(250);
}
return true;
}
private boolean isEditableDom(PageView pageView) throws InterruptedException {
String result = evaluateJavascript(pageView,
"(function(){"
+ "var bodyEditable = document.body && document.body.isContentEditable;"
+ "var editableNode = document.querySelector('[contenteditable=\"true\"], [contenteditable=\"plaintext-only\"]');"
+ "return !!(bodyEditable || editableNode);"
+ "})()");
if (result == null) {
return false;
}
String normalized = result.replace("\"", "");
return "true".equalsIgnoreCase(normalized);
}
private String evaluateJavascript(PageView pageView, String script) throws InterruptedException {
AtomicReference<String> result = new AtomicReference<>();
CountDownLatch latch = new CountDownLatch(1);
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
pageView.evaluateJavascript(script, value -> {
result.set(value);
latch.countDown();
});
});
if (!latch.await(10, TimeUnit.SECONDS)) {
Assert.fail("Timed out waiting for JS evaluation result");
}
return result.get();
}
}