/
RecyclerViewActions.java
488 lines (437 loc) · 19.5 KB
/
RecyclerViewActions.java
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.test.espresso.contrib;
import static android.support.test.espresso.contrib.Checks.checkArgument;
import static android.support.test.espresso.contrib.Checks.checkNotNull;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static org.hamcrest.Matchers.allOf;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.PerformException;
import android.support.test.espresso.UiController;
import android.support.test.espresso.ViewAction;
import android.support.test.espresso.util.HumanReadables;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.util.SparseArray;
import android.view.View;
import android.widget.AdapterView;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.util.ArrayList;
import java.util.List;
/**
* {@link ViewAction}s to interact {@link RecyclerView}. RecyclerView works differently than
* {@link AdapterView}. In fact, RecyclerView is not an AdapterView anymore, hence it can't be used
* in combination with {@link Espresso#onData(Matcher)}.
*
* <p>
* To use {@link ViewAction}s in this class use {@link Espresso#onView(Matcher)} with a
* <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matcher.html">
* <code>Matcher</code></a> that matches your {@link RecyclerView}, then perform a
* {@link ViewAction} from this class.
* </p>
**/
public final class RecyclerViewActions {
private static final int NO_POSITION = -1;
private RecyclerViewActions() {
// no instance
}
/**
* Most RecyclerViewActions are given a matcher to select a particular view / viewholder within
* the RecyclerView. In this case the default behaviour is to expect that the matcher matches 1
* and only one item within the RecyclerView.
*
* <p>This interface gives users the ability to override that type of behaviour and explicitly
* select an item in the RecyclerView at a given position. This is similar to on the
* onData(...).atPosition() api for AdapterViews.
*/
public interface PositionableRecyclerViewAction extends ViewAction {
/**
* Returns a new ViewAction which will cause the ViewAction to operate upon the position-th
* element which the matcher has selected.
*
* @param position a 0-based index into the list of matching elements within the RecyclerView.
* @return PositionableRecyclerViewAction a new ViewAction focused on a particular position.
* @throws IllegalArgumentException if position < 0.
*/
public PositionableRecyclerViewAction atPosition(int position);
}
/**
* Returns a {@link ViewAction} which scrolls {@link RecyclerView} to the view matched by
* viewHolderMatcher.
*
* <p>
* This approach uses {@link ViewHolder}s to find the target view. It will create one ViewHolder
* per item type and bind adapter data to the ViewHolder. If the itemViewMatcher matches a
* ViewHolder the current position of the View is used to perform a
* {@link RecyclerView#scrollToPosition(int)}. Note: scrollTo method is not overloaded, method
* overloading with generic parameters is not possible.
* </p>
*
* @param viewHolderMatcher a
* <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matcher.html">
* <code>Matcher</code></a> that matches an item view holder in {@link RecyclerView}
* @throws PerformException if there are more than one items matching given viewHolderMatcher.
*/
public static <VH extends ViewHolder> PositionableRecyclerViewAction scrollToHolder(
final Matcher<VH> viewHolderMatcher) {
return new ScrollToViewAction<VH>(viewHolderMatcher);
}
/**
* Returns a {@link ViewAction} which scrolls {@link RecyclerView} to the view matched by
* itemViewMatcher.
*
* <p>
* This approach uses {@link ViewHolder}s to find the target view. It will create one ViewHolder
* per item type and bind adapter data to the ViewHolder. If the itemViewMatcher matches a
* ViewHolder the current position of the View is used to perform a
* {@link RecyclerView#scrollToPosition(int)}.
* </p>
*
* @param itemViewMatcher a
* <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matcher.html">
* <code>Matcher</code></a> that matches an item view in {@link RecyclerView}
* @throws PerformException if there are more than one items matching given viewHolderMatcher.
*/
public static <VH extends ViewHolder> PositionableRecyclerViewAction scrollTo(
final Matcher<View> itemViewMatcher) {
Matcher<VH> viewHolderMatcher = viewHolderMatcher(itemViewMatcher);
return new ScrollToViewAction<VH>(viewHolderMatcher);
}
/**
* Returns a {@link ViewAction} which scrolls {@link RecyclerView} to a position.
*
* @param position the position of the view to scroll to
*/
public static <VH extends ViewHolder> ViewAction scrollToPosition(final int position) {
return new ScrollToPositionViewAction(position);
}
/**
* Performs a {@link ViewAction} on a view matched by viewHolderMatcher.
*
* <ol>
* <li>Scroll Recycler View to the view matched by itemViewMatcher</li>
* <li>Perform an action on the matched view</li>
* </ol>
*
* @param itemViewMatcher a
* <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matcher.html">
* <code>Matcher</code></a> that matches an item view in {@link RecyclerView}
* @param viewAction the action that is performed on the view matched by viewHolderMatcher
* @throws PerformException if there are more than one items matching given viewHolderMatcher.
*/
public static <VH extends ViewHolder> PositionableRecyclerViewAction actionOnItem(
final Matcher<View> itemViewMatcher, final ViewAction viewAction) {
Matcher<VH> viewHolderMatcher = viewHolderMatcher(itemViewMatcher);
return new ActionOnItemViewAction<VH>(viewHolderMatcher, viewAction);
}
/**
* Performs a {@link ViewAction} on a view matched by viewHolderMatcher.
*
* <ol>
* <li>Scroll Recycler View to the view matched by itemViewMatcher</li>
* <li>Perform an action on the matched view</li>
* </ol>
* Note: actionOnItem method is not overloaded, method overloading with
* generic parameters is not possible.
*
* @param viewHolderMatcher a
* <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matcher.html">
* <code>Matcher</code></a> that matchesan item view holder in {@link RecyclerView}
* @param viewAction the action that is performed on the view matched by viewHolderMatcher
* @throws PerformException if there are more than one items matching given viewHolderMatcher.
*/
public static <VH extends ViewHolder> PositionableRecyclerViewAction actionOnHolderItem(
final Matcher<VH> viewHolderMatcher, final ViewAction viewAction) {
return new ActionOnItemViewAction<VH>(viewHolderMatcher, viewAction);
}
private static final class ActionOnItemViewAction<VH extends ViewHolder> implements
PositionableRecyclerViewAction {
private final Matcher<VH> viewHolderMatcher;
private final ViewAction viewAction;
private final int atPosition;
private final ScrollToViewAction<VH> scroller;
private ActionOnItemViewAction(Matcher<VH> viewHolderMatcher, ViewAction viewAction) {
this(viewHolderMatcher, viewAction, NO_POSITION);
}
private ActionOnItemViewAction(Matcher<VH> viewHolderMatcher, ViewAction viewAction,
int atPosition) {
this.viewHolderMatcher = checkNotNull(viewHolderMatcher);
this.viewAction = checkNotNull(viewAction);
this.atPosition = atPosition;
this.scroller = new ScrollToViewAction<VH>(viewHolderMatcher, atPosition);
}
@SuppressWarnings("unchecked")
@Override
public Matcher<View> getConstraints() {
return allOf(isAssignableFrom(RecyclerView.class), isDisplayed());
}
@Override
public PositionableRecyclerViewAction atPosition(int position) {
checkArgument(position >= 0, "%d is used as an index - must be >= 0", position);
return new ActionOnItemViewAction<VH>(viewHolderMatcher, viewAction, position);
}
@Override
public String getDescription() {
if (atPosition == NO_POSITION) {
return String.format("performing ViewAction: %s on item matching: %s",
viewAction.getDescription(), viewHolderMatcher);
} else {
return String.format("performing ViewAction: %s on %d-th item matching: %s",
viewAction.getDescription(), atPosition, viewHolderMatcher);
}
}
@Override
public void perform(UiController uiController, View root) {
RecyclerView recyclerView = (RecyclerView) root;
try {
scroller.perform(uiController, root);
uiController.loopMainThreadUntilIdle();
// the above scroller has checked bounds, dupes (maybe) and brought the element into screen.
int max = atPosition == NO_POSITION ? 2 : atPosition + 1;
int selectIndex = atPosition == NO_POSITION ? 0 : atPosition;
List<MatchedItem> matchedItems = itemsMatching(recyclerView, viewHolderMatcher, max);
actionOnItemAtPosition(matchedItems.get(selectIndex).position, viewAction).perform(
uiController, root);
uiController.loopMainThreadUntilIdle();
} catch (RuntimeException e) {
throw new PerformException.Builder().withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(root)).withCause(e).build();
}
}
}
/**
* Performs a {@link ViewAction} on a view at position.
*
* <ol>
* <li>Scroll Recycler View to position</li>
* <li>Perform an action on the view at position</li>
* </ol>
*
* @param position position of a view in {@link RecyclerView}
* @param viewAction the action that is performed on the view matched by itemViewMatcher
*/
public static <VH extends ViewHolder> ViewAction actionOnItemAtPosition(final int position,
final ViewAction viewAction) {
return new ActionOnItemAtPositionViewAction<VH>(position, viewAction);
}
private static final class ActionOnItemAtPositionViewAction<VH extends ViewHolder> implements
ViewAction {
private final int position;
private final ViewAction viewAction;
private ActionOnItemAtPositionViewAction(int position, ViewAction viewAction) {
this.position = position;
this.viewAction = viewAction;
}
@SuppressWarnings("unchecked")
@Override
public Matcher<View> getConstraints() {
return allOf(isAssignableFrom(RecyclerView.class), isDisplayed());
}
@Override
public String getDescription() {
return "actionOnItemAtPosition performing ViewAction: " + viewAction.getDescription()
+ " on item at position: " + position;
}
@Override
public void perform(UiController uiController, View view) {
RecyclerView recyclerView = (RecyclerView) view;
new ScrollToPositionViewAction(position).perform(uiController, view);
uiController.loopMainThreadUntilIdle();
@SuppressWarnings("unchecked")
VH viewHolderForPosition = (VH) recyclerView.findViewHolderForPosition(position);
if (null == viewHolderForPosition) {
throw new PerformException.Builder().withActionDescription(this.toString())
.withViewDescription(HumanReadables.describe(view))
.withCause(new IllegalStateException("No view holder at position: " + position))
.build();
}
View viewAtPosition = viewHolderForPosition.itemView;
if (null == viewAtPosition) {
throw new PerformException.Builder().withActionDescription(this.toString())
.withViewDescription(HumanReadables.describe(viewAtPosition))
.withCause(new IllegalStateException("No view at position: " + position)).build();
}
viewAction.perform(uiController, viewAtPosition);
}
}
/**
* {@link ViewAction} which scrolls {@link RecyclerView} to the view matched by itemViewMatcher.
* See {@link RecyclerViewActions#scrollTo(Matcher)} for more details.
*/
private static final class ScrollToViewAction<VH extends ViewHolder> implements
PositionableRecyclerViewAction {
private final Matcher<VH> viewHolderMatcher;
private final int atPosition;
private ScrollToViewAction(Matcher<VH> viewHolderMatcher) {
this(viewHolderMatcher, NO_POSITION);
}
private ScrollToViewAction(Matcher<VH> viewHolderMatcher, int atPosition) {
this.viewHolderMatcher = viewHolderMatcher;
this.atPosition = atPosition;
}
@Override
public PositionableRecyclerViewAction atPosition(int position) {
checkArgument(position >= 0, "%d is used as an index - must be >= 0", position);
return new ScrollToViewAction<VH>(viewHolderMatcher, position);
}
@SuppressWarnings("unchecked")
@Override
public Matcher<View> getConstraints() {
return allOf(isAssignableFrom(RecyclerView.class), isDisplayed());
}
@Override
public String getDescription() {
if (atPosition == NO_POSITION) {
return "scroll RecyclerView to: " + viewHolderMatcher;
} else {
return String.format("scroll RecyclerView to the: %dth matching %s.", atPosition,
viewHolderMatcher);
}
}
@SuppressWarnings("unchecked")
@Override
public void perform(UiController uiController, View view) {
RecyclerView recyclerView = (RecyclerView) view;
try {
int maxMatches = atPosition == NO_POSITION ? 2 : atPosition + 1;
int selectIndex = atPosition == NO_POSITION ? 0 : atPosition;
List<MatchedItem> matchedItems = itemsMatching(recyclerView, viewHolderMatcher, maxMatches);
if (selectIndex >= matchedItems.size()) {
throw new RuntimeException(String.format(
"Found %d items matching %s, but position %d was requested.", matchedItems.size(),
viewHolderMatcher.toString(), atPosition));
}
if (atPosition == NO_POSITION && matchedItems.size() == 2) {
StringBuilder ambiguousViewError = new StringBuilder();
ambiguousViewError.append(
String.format("Found more than one sub-view matching %s", viewHolderMatcher));
for (MatchedItem item : matchedItems) {
ambiguousViewError.append(item + "\n");
}
throw new RuntimeException(ambiguousViewError.toString());
}
recyclerView.scrollToPosition(matchedItems.get(selectIndex).position);
uiController.loopMainThreadUntilIdle();
} catch (RuntimeException e) {
throw new PerformException.Builder().withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view)).withCause(e).build();
}
}
}
/**
* {@link ViewAction} which scrolls {@link RecyclerView} to a given position. See
* {@link RecyclerViewActions#scrollToPosition(int)} for more details.
*/
private static final class ScrollToPositionViewAction implements ViewAction {
private final int position;
private ScrollToPositionViewAction(int position) {
this.position = position;
}
@SuppressWarnings("unchecked")
@Override
public Matcher<View> getConstraints() {
return allOf(isAssignableFrom(RecyclerView.class), isDisplayed());
}
@Override
public String getDescription() {
return "scroll RecyclerView to position: " + position;
}
@Override
public void perform(UiController uiController, View view) {
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.scrollToPosition(position);
}
}
/**
* Finds positions of items in {@link RecyclerView} which is matching given viewHolderMatcher.
* This is similar to positionMatching(RecyclerView, Matcher<VH>), except that it returns list of
* multiple positions if there are, rather than throwing Ambiguous view error exception.
*
* @param recyclerView recycler view which is hosting items.
* @param viewHolderMatcher a
* <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matcher.html">
* <code>Matcher</code></a> that matches an item view in {@link RecyclerView}
* @return list of MatchedItem which contains position and description of items in recyclerView.
* @throws RuntimeException if more than one item or item could not be found.
*/
@SuppressWarnings("unchecked")
private static <T extends VH, VH extends ViewHolder> List<MatchedItem> itemsMatching(
final RecyclerView recyclerView, final Matcher<VH> viewHolderMatcher, int max) {
final Adapter<T> adapter = recyclerView.getAdapter();
SparseArray<VH> viewHolderCache = new SparseArray<VH>();
List<MatchedItem> matchedItems = new ArrayList<MatchedItem>();
for (int position = 0; position < adapter.getItemCount(); position++) {
int itemType = adapter.getItemViewType(position);
VH cachedViewHolder = viewHolderCache.get(itemType);
// Create a view holder per type if not exists
if (null == cachedViewHolder) {
cachedViewHolder = adapter.createViewHolder(recyclerView, itemType);
viewHolderCache.put(itemType, cachedViewHolder);
}
// Bind data to ViewHolder and apply matcher to view descendants.
adapter.bindViewHolder((T) cachedViewHolder, position);
if (viewHolderMatcher.matches(cachedViewHolder)) {
matchedItems.add(new MatchedItem(position, HumanReadables.getViewHierarchyErrorMessage(
cachedViewHolder.itemView, null,
"\n\n*** Matched ViewHolder item at position: " + position + " ***", null)));
if (matchedItems.size() == max) {
break;
}
}
}
return matchedItems;
}
/**
* Wrapper for matched items in recycler view which contains position and description of matched
* view.
*/
private static class MatchedItem {
public final int position;
public final String description;
private MatchedItem(int position, String description) {
this.position = position;
this.description = description;
}
@Override
public String toString() {
return description;
}
}
/**
* Creates matcher for view holder with given item view matcher.
*
* @param itemViewMatcher a item view matcher which is used to match item.
* @return a matcher which matches a view holder containing item matching itemViewMatcher.
*/
private static <VH extends ViewHolder> Matcher<VH> viewHolderMatcher(
final Matcher<View> itemViewMatcher) {
return new TypeSafeMatcher<VH>() {
@Override
public boolean matchesSafely(RecyclerView.ViewHolder viewHolder) {
return itemViewMatcher.matches(viewHolder.itemView);
}
@Override
public void describeTo(Description description) {
description.appendText("holder with view: ");
itemViewMatcher.describeTo(description);
}
};
}
}