summaryrefslogtreecommitdiffstats
path: root/tests/fragment/src/android/fragment/cts/FragmentLifecycleTest.java
blob: 0662d2d5bd9c26ca9adb2bbcb8d94f4561646101 (plain)
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
/*
 * Copyright (C) 2016 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.fragment.cts;

import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.fail;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertNotSame;
import static junit.framework.TestCase.assertNull;
import static junit.framework.TestCase.assertSame;
import static junit.framework.TestCase.assertTrue;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentController;
import android.app.FragmentHostCallback;
import android.app.FragmentManager;
import android.app.FragmentManager.FragmentLifecycleCallbacks;
import android.app.FragmentManagerNonConfig;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.MediumTest;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.FileDescriptor;
import java.io.PrintWriter;

@MediumTest
@RunWith(AndroidJUnit4.class)
public class FragmentLifecycleTest {

    @Rule
    public ActivityTestRule<FragmentTestActivity> mActivityRule =
            new ActivityTestRule<FragmentTestActivity>(FragmentTestActivity.class);

    @Test
    public void basicLifecycle() throws Throwable {
        final FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
        final StrictFragment strictFragment = new StrictFragment();

        // Add fragment; StrictFragment will throw if it detects any violation
        // in standard lifecycle method ordering or expected preconditions.
        fm.beginTransaction().add(strictFragment, "EmptyHeadless").commit();
        executePendingTransactions(fm);

        assertTrue("fragment is not added", strictFragment.isAdded());
        assertFalse("fragment is detached", strictFragment.isDetached());
        assertTrue("fragment is not resumed", strictFragment.isResumed());

        // Test removal as well; StrictFragment will throw here too.
        fm.beginTransaction().remove(strictFragment).commit();
        executePendingTransactions(fm);

        assertFalse("fragment is added", strictFragment.isAdded());
        assertFalse("fragment is resumed", strictFragment.isResumed());

        // This one is perhaps counterintuitive; "detached" means specifically detached
        // but still managed by a FragmentManager. The .remove call above
        // should not enter this state.
        assertFalse("fragment is detached", strictFragment.isDetached());
    }

    @Test
    public void detachment() throws Throwable {
        final FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
        final StrictFragment f1 = new StrictFragment();
        final StrictFragment f2 = new StrictFragment();

        fm.beginTransaction().add(f1, "1").add(f2, "2").commit();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not added", f1.isAdded());
        assertTrue("fragment 2 is not added", f2.isAdded());

        // Test detaching fragments using StrictFragment to throw on errors.
        fm.beginTransaction().detach(f1).detach(f2).commit();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not detached", f1.isDetached());
        assertTrue("fragment 2 is not detached", f2.isDetached());
        assertFalse("fragment 1 is added", f1.isAdded());
        assertFalse("fragment 2 is added", f2.isAdded());

        // Only reattach f1; leave v2 detached.
        fm.beginTransaction().attach(f1).commit();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not added", f1.isAdded());
        assertFalse("fragment 1 is detached", f1.isDetached());
        assertTrue("fragment 2 is not detached", f2.isDetached());

        // Remove both from the FragmentManager.
        fm.beginTransaction().remove(f1).remove(f2).commit();
        executePendingTransactions(fm);

        assertFalse("fragment 1 is added", f1.isAdded());
        assertFalse("fragment 2 is added", f2.isAdded());
        assertFalse("fragment 1 is detached", f1.isDetached());
        assertFalse("fragment 2 is detached", f2.isDetached());
    }

    @Test
    public void basicBackStack() throws Throwable {
        final FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
        final StrictFragment f1 = new StrictFragment();
        final StrictFragment f2 = new StrictFragment();

        // Add a fragment normally to set up
        fm.beginTransaction().add(f1, "1").commit();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not added", f1.isAdded());

        // Remove the first one and add a second. We're not using replace() here since
        // these fragments are headless and as of this test writing, replace() only works
        // for fragments with views and a container view id.
        // Add it to the back stack so we can pop it afterwards.
        fm.beginTransaction().remove(f1).add(f2, "2").addToBackStack("stack1").commit();
        executePendingTransactions(fm);

        assertFalse("fragment 1 is added", f1.isAdded());
        assertTrue("fragment 2 is not added", f2.isAdded());

        // Test popping the stack
        fm.popBackStack();
        executePendingTransactions(fm);

        assertFalse("fragment 2 is added", f2.isAdded());
        assertTrue("fragment 1 is not added", f1.isAdded());
    }

    @Test
    public void attachBackStack() throws Throwable {
        final FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
        final StrictFragment f1 = new StrictFragment();
        final StrictFragment f2 = new StrictFragment();

        // Add a fragment normally to set up
        fm.beginTransaction().add(f1, "1").commit();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not added", f1.isAdded());

        fm.beginTransaction().detach(f1).add(f2, "2").addToBackStack("stack1").commit();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not detached", f1.isDetached());
        assertFalse("fragment 2 is detached", f2.isDetached());
        assertFalse("fragment 1 is added", f1.isAdded());
        assertTrue("fragment 2 is not added", f2.isAdded());
    }

    @Test
    public void viewLifecycle() throws Throwable {
        // Test basic lifecycle when the fragment creates a view

        final FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
        final StrictViewFragment f1 = new StrictViewFragment();

        fm.beginTransaction().add(android.R.id.content, f1).commit();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not added", f1.isAdded());
        final View view = f1.getView();
        assertNotNull("fragment 1 returned null from getView", view);
        assertTrue("fragment 1's view is not attached to a window", view.isAttachedToWindow());

        fm.beginTransaction().remove(f1).commit();
        executePendingTransactions(fm);

        assertFalse("fragment 1 is added", f1.isAdded());
        assertNull("fragment 1 returned non-null from getView after removal", f1.getView());
        assertFalse("fragment 1's previous view is still attached to a window",
                view.isAttachedToWindow());
    }

    @Test
    public void viewReplace() throws Throwable {
        // Replace one view with another, then reverse it with the back stack

        final FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
        final StrictViewFragment f1 = new StrictViewFragment();
        final StrictViewFragment f2 = new StrictViewFragment();

        fm.beginTransaction().add(android.R.id.content, f1).commit();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not added", f1.isAdded());

        View origView1 = f1.getView();
        assertNotNull("fragment 1 returned null view", origView1);
        assertTrue("fragment 1's view not attached", origView1.isAttachedToWindow());

        fm.beginTransaction().replace(android.R.id.content, f2).addToBackStack("stack1").commit();
        executePendingTransactions(fm);

        assertFalse("fragment 1 is added", f1.isAdded());
        assertTrue("fragment 2 is added", f2.isAdded());
        assertNull("fragment 1 returned non-null view", f1.getView());
        assertFalse("fragment 1's old view still attached", origView1.isAttachedToWindow());
        View origView2 = f2.getView();
        assertNotNull("fragment 2 returned null view", origView2);
        assertTrue("fragment 2's view not attached", origView2.isAttachedToWindow());

        fm.popBackStack();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not added", f1.isAdded());
        assertFalse("fragment 2 is added", f2.isAdded());
        assertNull("fragment 2 returned non-null view", f2.getView());
        assertFalse("fragment 2's view still attached", origView2.isAttachedToWindow());
        View newView1 = f1.getView();
        assertNotSame("fragment 1 had same view from last attachment", origView1, newView1);
        assertTrue("fragment 1's view not attached", newView1.isAttachedToWindow());
    }

    @Test
    public void viewReplaceMultiple() throws Throwable {
        // Replace several views with one, then reverse it with the back stack

        final FragmentManager fm = mActivityRule.getActivity().getFragmentManager();
        final StrictViewFragment f1 = new StrictViewFragment();
        final StrictViewFragment f2 = new StrictViewFragment();
        final StrictViewFragment f3 = new StrictViewFragment();

        fm.beginTransaction().add(android.R.id.content, f1).commit();
        fm.beginTransaction().add(android.R.id.content, f2).commit();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not added", f1.isAdded());
        assertTrue("fragment 2 is not added", f2.isAdded());

        View origView1 = f1.getView();
        assertNotNull("fragment 1 returned null view", origView1);
        assertTrue("fragment 1's view not attached", origView1.isAttachedToWindow());
        assertSame(origView1, ((ViewGroup)origView1.getParent()).getChildAt(0));

        View origView2 = f2.getView();
        assertNotNull("fragment 2 returned null view", origView2);
        assertTrue("fragment 2's view not attached", origView2.isAttachedToWindow());
        assertSame(origView2, ((ViewGroup)origView1.getParent()).getChildAt(1));

        fm.beginTransaction().replace(android.R.id.content, f3).addToBackStack("stack1").commit();
        executePendingTransactions(fm);

        assertFalse("fragment 1 is added", f1.isAdded());
        assertFalse("fragment 2 is added", f2.isAdded());
        assertTrue("fragment 3 is added", f3.isAdded());
        assertNull("fragment 1 returned non-null view", f1.getView());
        assertNull("fragment 2 returned non-null view", f2.getView());
        assertFalse("fragment 1's old view still attached", origView1.isAttachedToWindow());
        assertFalse("fragment 2's old view still attached", origView2.isAttachedToWindow());
        View origView3 = f3.getView();
        assertNotNull("fragment 3 returned null view", origView3);
        assertTrue("fragment 3's view not attached", origView3.isAttachedToWindow());

        fm.popBackStack();
        executePendingTransactions(fm);

        assertTrue("fragment 1 is not added", f1.isAdded());
        assertTrue("fragment 2 is not added", f2.isAdded());
        assertFalse("fragment 3 is added", f3.isAdded());
        assertNull("fragment 3 returned non-null view", f3.getView());
        assertFalse("fragment 3's view still attached", origView3.isAttachedToWindow());
        View newView1 = f1.getView();
        View newView2 = f2.getView();
        assertNotSame("fragment 1 had same view from last attachment", origView1, newView1);
        assertNotSame("fragment 2 had same view from last attachment", origView2, newView1);
        assertTrue("fragment 1's view not attached", newView1.isAttachedToWindow());
        assertTrue("fragment 2's view not attached", newView2.isAttachedToWindow());
        assertSame(newView1, ((ViewGroup)newView1.getParent()).getChildAt(0));
        assertSame(newView2, ((ViewGroup)newView1.getParent()).getChildAt(1));
    }

    /**
     * This tests that fragments call onDestroy when the activity finishes.
     */
    @Test
    public void fragmentDestroyedOnFinish() throws Throwable {
        final FragmentController fc = FragmentTestUtil.createController(mActivityRule);
        FragmentTestUtil.resume(mActivityRule, fc, null);
        final StrictViewFragment fragmentA = StrictViewFragment.create(R.layout.text_a);
        final StrictViewFragment fragmentB = StrictViewFragment.create(R.layout.text_b);
        mActivityRule.runOnUiThread(() -> {
            FragmentManager fm = fc.getFragmentManager();

            fm.beginTransaction()
                    .add(android.R.id.content, fragmentA)
                    .commit();
            fm.executePendingTransactions();
            fm.beginTransaction()
                    .replace(android.R.id.content, fragmentB)
                    .addToBackStack(null)
                    .commit();
            fm.executePendingTransactions();
        });
        FragmentTestUtil.destroy(mActivityRule, fc);
        assertTrue(fragmentB.mCalledOnDestroy);
        assertTrue(fragmentA.mCalledOnDestroy);
    }

    /**
     * This test confirms that as long as a parent fragment has called super.onCreate,
     * any child fragments added, committed and with transactions executed will be brought
     * to at least the CREATED state by the time the parent fragment receives onCreateView.
     * This means the child fragment will have received onAttach/onCreate.
     */
    @Test
    @MediumTest
    public void childFragmentManagerAttach() throws Throwable {
        mActivityRule.runOnUiThread(new Runnable() {
            public void run() {
                FragmentController fc = FragmentController.createController(
                        new HostCallbacks(mActivityRule.getActivity()));
                fc.attachHost(null);
                fc.dispatchCreate();

                FragmentLifecycleCallbacks mockLc = mock(FragmentLifecycleCallbacks.class);
                FragmentLifecycleCallbacks mockRecursiveLc = mock(FragmentLifecycleCallbacks.class);

                FragmentManager fm = fc.getFragmentManager();
                fm.registerFragmentLifecycleCallbacks(mockLc, false);
                fm.registerFragmentLifecycleCallbacks(mockRecursiveLc, true);

                ChildFragmentManagerFragment fragment = new ChildFragmentManagerFragment();
                fm.beginTransaction()
                        .add(android.R.id.content, fragment)
                        .commitNow();

                verify(mockLc, times(1)).onFragmentCreated(fm, fragment, null);

                fc.dispatchActivityCreated();

                Fragment childFragment = fragment.getChildFragment();

                verify(mockLc, times(1)).onFragmentActivityCreated(fm, fragment, null);
                verify(mockRecursiveLc, times(1)).onFragmentActivityCreated(fm, fragment, null);
                verify(mockRecursiveLc, times(1)).onFragmentActivityCreated(fm, childFragment, null);

                fc.dispatchStart();

                verify(mockLc, times(1)).onFragmentStarted(fm, fragment);
                verify(mockRecursiveLc, times(1)).onFragmentStarted(fm, fragment);
                verify(mockRecursiveLc, times(1)).onFragmentStarted(fm, childFragment);

                fc.dispatchResume();

                verify(mockLc, times(1)).onFragmentResumed(fm, fragment);
                verify(mockRecursiveLc, times(1)).onFragmentResumed(fm, fragment);
                verify(mockRecursiveLc, times(1)).onFragmentResumed(fm, childFragment);

                // Confirm that the parent fragment received onAttachFragment
                assertTrue("parent fragment did not receive onAttachFragment",
                        fragment.mCalledOnAttachFragment);

                fc.dispatchStop();

                verify(mockLc, times(1)).onFragmentStopped(fm, fragment);
                verify(mockRecursiveLc, times(1)).onFragmentStopped(fm, fragment);
                verify(mockRecursiveLc, times(1)).onFragmentStopped(fm, childFragment);

                fc.dispatchDestroy();

                verify(mockLc, times(1)).onFragmentDestroyed(fm, fragment);
                verify(mockRecursiveLc, times(1)).onFragmentDestroyed(fm, fragment);
                verify(mockRecursiveLc, times(1)).onFragmentDestroyed(fm, childFragment);
            }
        });
    }

    /**
     * Test to ensure that when dispatch* is called that the fragment manager
     * doesn't cause the contained fragment states to change even if no state changes.
     */
    @Test
    public void noPrematureStateChange() throws Throwable {
        final FragmentController fc = FragmentTestUtil.createController(mActivityRule);
        FragmentTestUtil.resume(mActivityRule, fc, null);

        mActivityRule.runOnUiThread(() -> {
            fc.getFragmentManager().beginTransaction()
                    .add(new StrictFragment(), "1")
                    .commitNow();
        });

        Pair<Parcelable, FragmentManagerNonConfig> savedState =
                FragmentTestUtil.destroy(mActivityRule, fc);

        final FragmentController fragmentController = FragmentTestUtil.createController(mActivityRule);

        mActivityRule.runOnUiThread(() -> {
            fragmentController.attachHost(null);
            fragmentController.dispatchCreate();
            fragmentController.dispatchActivityCreated();
            fragmentController.noteStateNotSaved();
            fragmentController.execPendingActions();
            fragmentController.dispatchStart();
            fragmentController.reportLoaderStart();
            fragmentController.dispatchResume();
            fragmentController.restoreAllState(savedState.first, savedState.second);
            fragmentController.dispatchResume();
        });

        FragmentManager fm = fragmentController.getFragmentManager();

        StrictFragment fragment1 = (StrictFragment) fm.findFragmentByTag("1");

        assertNotNull(fragment1);
        assertFalse(fragment1.mCalledOnResume);
    }

    @Test
    public void testIsStateSaved() throws Throwable {
        FragmentController fc = FragmentTestUtil.createController(mActivityRule);
        FragmentTestUtil.resume(mActivityRule, fc, null);
        FragmentManager fm = fc.getFragmentManager();

        mActivityRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Fragment f = new StrictFragment();
                fm.beginTransaction()
                        .add(f, "1")
                        .commitNow();

                assertFalse("fragment reported state saved while resumed",
                        f.isStateSaved());

                fc.dispatchPause();
                fc.saveAllState();

                assertTrue("fragment reported state not saved after saveAllState",
                        f.isStateSaved());

                fc.dispatchStop();

                assertTrue("fragment reported state not saved after stop",
                        f.isStateSaved());

                fc.dispatchDestroy();

                assertFalse("fragment reported state saved after destroy",
                        f.isStateSaved());
            }
        });
    }

    @Test
    public void testSetArgumentsLifecycle() throws Throwable {
        FragmentController fc = FragmentTestUtil.createController(mActivityRule);
        FragmentTestUtil.resume(mActivityRule, fc, null);
        FragmentManager fm = fc.getFragmentManager();

        mActivityRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Fragment f = new StrictFragment();
                f.setArguments(new Bundle());

                fm.beginTransaction()
                        .add(f, "1")
                        .commitNow();

                f.setArguments(new Bundle());

                fc.dispatchPause();
                fc.saveAllState();

                boolean threw = false;
                try {
                    f.setArguments(new Bundle());
                } catch (IllegalStateException ise) {
                    threw = true;
                }
                assertTrue("fragment allowed setArguments after state save", threw);

                fc.dispatchStop();

                threw = false;
                try {
                    f.setArguments(new Bundle());
                } catch (IllegalStateException ise) {
                    threw = true;
                }
                assertTrue("fragment allowed setArguments after stop", threw);

                fc.dispatchDestroy();

                // Fully destroyed, so fragments have been removed.
                f.setArguments(new Bundle());
            }
        });

    }

    /*
     * Test that target fragments are in a useful state when we restore them, even if they're
     * on the back stack.
     */

    @Test
    public void targetFragmentRestoreLifecycleStateBackStack() throws Throwable {
        mActivityRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final FragmentController fc1 = FragmentController.createController(
                        new HostCallbacks(mActivityRule.getActivity()));

                final FragmentManager fm1 = fc1.getFragmentManager();

                fc1.attachHost(null);
                fc1.dispatchCreate();

                final Fragment target = new TargetFragment();
                fm1.beginTransaction().add(target, "target").commitNow();

                final Fragment referrer = new ReferrerFragment();
                referrer.setTargetFragment(target, 0);

                fm1.beginTransaction()
                        .remove(target)
                        .add(referrer, "referrer")
                        .addToBackStack(null)
                        .commit();

                fc1.dispatchActivityCreated();
                fc1.noteStateNotSaved();
                fc1.execPendingActions();
                fc1.doLoaderStart();
                fc1.dispatchStart();
                fc1.reportLoaderStart();
                fc1.dispatchResume();
                fc1.execPendingActions();

                // Bring the state back down to destroyed, simulating an activity restart
                fc1.dispatchPause();
                final Parcelable savedState = fc1.saveAllState();
                final FragmentManagerNonConfig nonconf = fc1.retainNestedNonConfig();
                fc1.dispatchStop();
                fc1.dispatchDestroy();

                final FragmentController fc2 = FragmentController.createController(
                        new HostCallbacks(mActivityRule.getActivity()));

                fc2.attachHost(null);
                fc2.restoreAllState(savedState, nonconf);
                fc2.dispatchCreate();

                fc2.dispatchActivityCreated();
                fc2.noteStateNotSaved();
                fc2.execPendingActions();
                fc2.doLoaderStart();
                fc2.dispatchStart();
                fc2.reportLoaderStart();
                fc2.dispatchResume();
                fc2.execPendingActions();

                // Bring the state back down to destroyed before we finish the test
                fc2.dispatchPause();
                fc2.saveAllState();
                fc2.dispatchStop();
                fc2.dispatchDestroy();
            }
        });
    }

    @Test
    public void targetFragmentRestoreLifecycleStateManagerOrder() throws Throwable {
        mActivityRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final FragmentController fc1 = FragmentController.createController(
                        new HostCallbacks(mActivityRule.getActivity()));

                final FragmentManager fm1 = fc1.getFragmentManager();

                fc1.attachHost(null);
                fc1.dispatchCreate();

                final Fragment target1 = new TargetFragment();
                final Fragment referrer1 = new ReferrerFragment();
                referrer1.setTargetFragment(target1, 0);

                fm1.beginTransaction().add(target1, "target1").add(referrer1, "referrer1").commitNow();

                final Fragment target2 = new TargetFragment();
                final Fragment referrer2 = new ReferrerFragment();
                referrer2.setTargetFragment(target2, 0);

                // Order shouldn't matter.
                fm1.beginTransaction().add(referrer2, "referrer2").add(target2, "target2").commitNow();

                fc1.dispatchActivityCreated();
                fc1.noteStateNotSaved();
                fc1.execPendingActions();
                fc1.doLoaderStart();
                fc1.dispatchStart();
                fc1.reportLoaderStart();
                fc1.dispatchResume();
                fc1.execPendingActions();

                // Bring the state back down to destroyed, simulating an activity restart
                fc1.dispatchPause();
                final Parcelable savedState = fc1.saveAllState();
                final FragmentManagerNonConfig nonconf = fc1.retainNestedNonConfig();
                fc1.dispatchStop();
                fc1.dispatchDestroy();

                final FragmentController fc2 = FragmentController.createController(
                        new HostCallbacks(mActivityRule.getActivity()));

                fc2.attachHost(null);
                fc2.restoreAllState(savedState, nonconf);
                fc2.dispatchCreate();

                fc2.dispatchActivityCreated();
                fc2.noteStateNotSaved();
                fc2.execPendingActions();
                fc2.doLoaderStart();
                fc2.dispatchStart();
                fc2.reportLoaderStart();
                fc2.dispatchResume();
                fc2.execPendingActions();

                // Bring the state back down to destroyed before we finish the test
                fc2.dispatchPause();
                fc2.saveAllState();
                fc2.dispatchStop();
                fc2.dispatchDestroy();
            }
        });
    }

    // Make sure that executing transactions during activity lifecycle events
    // is properly prevented.
    @Test
    public void preventReentrantCalls() throws Throwable {
        testLifecycleTransitionFailure(StrictFragment.ATTACHED, StrictFragment.CREATED);
        testLifecycleTransitionFailure(StrictFragment.CREATED, StrictFragment.ACTIVITY_CREATED);
        testLifecycleTransitionFailure(StrictFragment.ACTIVITY_CREATED, StrictFragment.STARTED);
        testLifecycleTransitionFailure(StrictFragment.STARTED, StrictFragment.RESUMED);

        testLifecycleTransitionFailure(StrictFragment.RESUMED, StrictFragment.STARTED);
        testLifecycleTransitionFailure(StrictFragment.STARTED, StrictFragment.CREATED);
        testLifecycleTransitionFailure(StrictFragment.CREATED, StrictFragment.ATTACHED);
        testLifecycleTransitionFailure(StrictFragment.ATTACHED, StrictFragment.DETACHED);
    }

    private void testLifecycleTransitionFailure(int fromState, int toState) throws Throwable {
        mActivityRule.runOnUiThread(() -> {
            final FragmentController fc1 = FragmentController.createController(
                    new HostCallbacks(mActivityRule.getActivity()));
            FragmentTestUtil.resume(mActivityRule, fc1, null);

            final FragmentManager fm1 = fc1.getFragmentManager();

            final Fragment reentrantFragment = ReentrantFragment.create(fromState, toState);

            fm1.beginTransaction()
                    .add(reentrantFragment, "reentrant")
                    .commit();
            try {
                fm1.executePendingTransactions();
            } catch (IllegalStateException e) {
                fail("An exception shouldn't happen when initially adding the fragment");
            }

            // Now shut down the fragment controller. When fromState > toState, this should
            // result in an exception
            Pair<Parcelable, FragmentManagerNonConfig> savedState = null;
            try {
                savedState = FragmentTestUtil.destroy(mActivityRule, fc1);
                if (fromState > toState) {
                    fail("Expected IllegalStateException when moving from "
                            + StrictFragment.stateToString(fromState) + " to "
                            + StrictFragment.stateToString(toState));
                }
            } catch (IllegalStateException e) {
                if (fromState < toState) {
                    fail("Unexpected IllegalStateException when moving from "
                            + StrictFragment.stateToString(fromState) + " to "
                            + StrictFragment.stateToString(toState));
                }
                return; // test passed!
            }

            // now restore from saved state. This will be reached when
            // fromState < toState. We want to catch the fragment while it
            // is being restored as the fragment controller state is being brought up.

            final FragmentController fc2 = FragmentController.createController(
                    new HostCallbacks(mActivityRule.getActivity()));
            try {
                FragmentTestUtil.resume(mActivityRule, fc2, savedState);

                fail("Expected IllegalStateException when moving from "
                        + StrictFragment.stateToString(fromState) + " to "
                        + StrictFragment.stateToString(toState));
            } catch (IllegalStateException e) {
                // expected, so the test passed!
            }
        });
    }

    @Test
    public void targetFragmentNoCycles() throws Throwable {
        final Fragment one = new Fragment();
        final Fragment two = new Fragment();
        final Fragment three = new Fragment();

        try {
            one.setTargetFragment(two, 0);
            two.setTargetFragment(three, 0);
            three.setTargetFragment(one, 0);
            assertTrue("creating a fragment target cycle did not throw IllegalArgumentException",
                    false);
        } catch (IllegalArgumentException e) {
            // Success!
        }
    }

    @Test
    public void targetFragmentSetClear() throws Throwable {
        final Fragment one = new Fragment();
        final Fragment two = new Fragment();

        one.setTargetFragment(two, 0);
        one.setTargetFragment(null, 0);
    }

    /**
     * When a fragment is saved in non-config, it should be restored to the same index.
     */
    @Test
    public void restoreNonConfig() throws Throwable {
        mActivityRule.runOnUiThread(() -> {
            FragmentController fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, null);
            FragmentManager fm = fc.getFragmentManager();

            Fragment fragment1 = new StrictFragment();
            fm.beginTransaction()
                    .add(fragment1, "1")
                    .addToBackStack(null)
                    .commit();
            fm.executePendingTransactions();
            Fragment fragment2 = new StrictFragment();
            fragment2.setRetainInstance(true);
            fragment2.setTargetFragment(fragment1, 0);
            Fragment fragment3 = new StrictFragment();
            fm.beginTransaction()
                    .remove(fragment1)
                    .add(fragment2, "2")
                    .add(fragment3, "3")
                    .addToBackStack(null)
                    .commit();
            fm.executePendingTransactions();

            Pair<Parcelable, FragmentManagerNonConfig> savedState =
                    FragmentTestUtil.destroy(mActivityRule, fc);

            fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, savedState);
            boolean foundFragment2 = false;
            for (Fragment fragment : fc.getFragmentManager().getFragments()) {
                if (fragment == fragment2) {
                    foundFragment2 = true;
                    assertNotNull(fragment.getTargetFragment());
                    assertEquals("1", fragment.getTargetFragment().getTag());
                } else {
                    assertFalse("2".equals(fragment.getTag()));
                }
            }
            assertTrue(foundFragment2);
        });
    }

    /**
     * Check that retained fragments in the backstack correctly restored after two "configChanges"
     */
    @Test
    public void retainedFragmentInBackstack() throws Throwable {
        mActivityRule.runOnUiThread(() -> {
            FragmentController fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, null);
            FragmentManager fm = fc.getFragmentManager();

            Fragment fragment1 = new StrictFragment();
            fm.beginTransaction()
                    .add(fragment1, "1")
                    .addToBackStack(null)
                    .commit();
            fm.executePendingTransactions();

            Fragment child = new StrictFragment();
            child.setRetainInstance(true);
            fragment1.getChildFragmentManager().beginTransaction()
                    .add(child, "child").commit();
            fragment1.getChildFragmentManager().executePendingTransactions();

            Fragment fragment2 = new StrictFragment();
            fm.beginTransaction()
                    .remove(fragment1)
                    .add(fragment2, "2")
                    .addToBackStack(null)
                    .commit();
            fm.executePendingTransactions();

            Pair<Parcelable, FragmentManagerNonConfig> savedState =
                    FragmentTestUtil.destroy(mActivityRule, fc);

            fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, savedState);
            savedState = FragmentTestUtil.destroy(mActivityRule, fc);
            fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, savedState);
            fm = fc.getFragmentManager();
            fm.popBackStackImmediate();
            Fragment retainedChild = fm.findFragmentByTag("1")
                    .getChildFragmentManager().findFragmentByTag("child");
            assertEquals(child, retainedChild);
        });
    }

    /**
     * When a fragment has been optimized out, it state should still be saved during
     * save and restore instance state.
     */
    @Test
    public void saveRemovedFragment() throws Throwable {
        mActivityRule.runOnUiThread(() -> {
            FragmentController fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, null);
            FragmentManager fm = fc.getFragmentManager();

            SaveStateFragment fragment1 = SaveStateFragment.create(1);
            fm.beginTransaction()
                    .add(android.R.id.content, fragment1, "1")
                    .addToBackStack(null)
                    .commit();
            SaveStateFragment fragment2 = SaveStateFragment.create(2);
            fm.beginTransaction()
                    .replace(android.R.id.content, fragment2, "2")
                    .addToBackStack(null)
                    .commit();
            fm.executePendingTransactions();

            Pair<Parcelable, FragmentManagerNonConfig> savedState =
                    FragmentTestUtil.destroy(mActivityRule, fc);

            fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, savedState);
            fm = fc.getFragmentManager();
            fragment2 = (SaveStateFragment) fm.findFragmentByTag("2");
            assertNotNull(fragment2);
            assertEquals(2, fragment2.getValue());
            fm.popBackStackImmediate();
            fragment1 = (SaveStateFragment) fm.findFragmentByTag("1");
            assertNotNull(fragment1);
            assertEquals(1, fragment1.getValue());
        });
    }

    /**
     * When there are no retained instance fragments, the FragmentManagerNonConfig should be
     * null
     */
    @Test
    public void nullNonConfig() throws Throwable {
        mActivityRule.runOnUiThread(() -> {
            FragmentController fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, null);
            FragmentManager fm = fc.getFragmentManager();

            Fragment fragment1 = new StrictFragment();
            fm.beginTransaction()
                    .add(fragment1, "1")
                    .addToBackStack(null)
                    .commit();
            fm.executePendingTransactions();
            Pair<Parcelable, FragmentManagerNonConfig> savedState =
                    FragmentTestUtil.destroy(mActivityRule, fc);
            assertNull(savedState.second);
        });
    }

    /**
     * When the FragmentManager state changes, the pending transactions should execute.
     */
    @Test
    public void runTransactionsOnChange() throws Throwable {
        mActivityRule.runOnUiThread(() -> {
            FragmentController fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, null);
            FragmentManager fm = fc.getFragmentManager();

            RemoveHelloInOnResume fragment1 = new RemoveHelloInOnResume();
            StrictFragment fragment2 = new StrictFragment();
            fm.beginTransaction()
                    .add(fragment1, "1")
                    .setReorderingAllowed(false)
                    .commit();
            fm.beginTransaction()
                    .add(fragment2, "Hello")
                    .setReorderingAllowed(false)
                    .commit();
            fm.executePendingTransactions();

            assertEquals(2, fm.getFragments().size());
            assertTrue(fm.getFragments().contains(fragment1));
            assertTrue(fm.getFragments().contains(fragment2));

            Pair<Parcelable, FragmentManagerNonConfig> savedState =
                    FragmentTestUtil.destroy(mActivityRule, fc);
            fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, savedState);
            fm = fc.getFragmentManager();

            assertEquals(1, fm.getFragments().size());
            for (Fragment fragment : fm.getFragments()) {
                assertTrue(fragment instanceof RemoveHelloInOnResume);
            }
        });
    }

    @Test
    public void optionsMenu() throws Throwable {
        mActivityRule.runOnUiThread(() -> {
            FragmentController fc = FragmentTestUtil.createController(mActivityRule);
            FragmentTestUtil.resume(mActivityRule, fc, null);
            FragmentManager fm = fc.getFragmentManager();

            InvalidateOptionFragment fragment = new InvalidateOptionFragment();
            fm.beginTransaction()
                    .add(android.R.id.content, fragment)
                    .commit();
            fm.executePendingTransactions();

            Menu menu = mock(Menu.class);
            fc.dispatchPrepareOptionsMenu(menu);
            assertTrue(fragment.onPrepareOptionsMenuCalled);
            fragment.onPrepareOptionsMenuCalled = false;
            FragmentTestUtil.destroy(mActivityRule, fc);
            fc.dispatchPrepareOptionsMenu(menu);
            assertFalse(fragment.onPrepareOptionsMenuCalled);
        });
    }

    private void executePendingTransactions(final FragmentManager fm) throws Throwable {
        mActivityRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fm.executePendingTransactions();
            }
        });
    }

    /**
     * This tests a deliberately odd use of a child fragment, added in onCreateView instead
     * of elsewhere. It simulates creating a UI child fragment added to the view hierarchy
     * created by this fragment.
     */
    public static class ChildFragmentManagerFragment extends StrictFragment {
        private FragmentManager mSavedChildFragmentManager;
        private ChildFragmentManagerChildFragment mChildFragment;

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            mSavedChildFragmentManager = getChildFragmentManager();
        }


        @Override
        public View onCreateView(LayoutInflater inflater,  ViewGroup container,
                 Bundle savedInstanceState) {
            assertSame("child FragmentManagers not the same instance", mSavedChildFragmentManager,
                    getChildFragmentManager());
            ChildFragmentManagerChildFragment child =
                    (ChildFragmentManagerChildFragment) mSavedChildFragmentManager
                            .findFragmentByTag("tag");
            if (child == null) {
                child = new ChildFragmentManagerChildFragment("foo");
                mSavedChildFragmentManager.beginTransaction()
                        .add(child, "tag")
                        .commitNow();
                assertEquals("argument strings don't match", "foo", child.getString());
            }
            mChildFragment = child;
            return new TextView(container.getContext());
        }


        public Fragment getChildFragment() {
            return mChildFragment;
        }
    }

    public static class ChildFragmentManagerChildFragment extends StrictFragment {
        private String mString;

        public ChildFragmentManagerChildFragment() {
        }

        public ChildFragmentManagerChildFragment(String arg) {
            final Bundle b = new Bundle();
            b.putString("string", arg);
            setArguments(b);
        }

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            mString = getArguments().getString("string", "NO VALUE");
        }

        public String getString() {
            return mString;
        }
    }

    public static class TargetFragment extends Fragment {
        public boolean calledCreate;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            calledCreate = true;
        }
    }

    public static class ReferrerFragment extends Fragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            Fragment target = getTargetFragment();
            assertNotNull("target fragment was null during referrer onCreate", target);

            if (!(target instanceof TargetFragment)) {
                throw new IllegalStateException("target fragment was not a TargetFragment");
            }

            assertTrue("target fragment has not yet been created",
                    ((TargetFragment) target).calledCreate);
        }
    }

    static class HostCallbacks extends FragmentHostCallback<Activity> {
        private final Activity mActivity;

        public HostCallbacks(Activity activity) {
            super(activity, null, 0);
            mActivity = activity;
        }

        @Override
        public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
        }

        @Override
        public boolean onShouldSaveFragmentState(Fragment fragment) {
            return !mActivity.isFinishing();
        }

        @Override
        public LayoutInflater onGetLayoutInflater() {
            return mActivity.getLayoutInflater().cloneInContext(mActivity);
        }

        @Override
        public Activity onGetHost() {
            return mActivity;
        }

        @Override
        public void onStartActivityFromFragment(
                Fragment fragment, Intent intent, int requestCode,  Bundle options) {
            mActivity.startActivityFromFragment(fragment, intent, requestCode, options);
        }

        @Override
        public void onRequestPermissionsFromFragment( Fragment fragment,
                 String[] permissions, int requestCode) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean onHasWindowAnimations() {
            return mActivity.getWindow() != null;
        }

        @Override
        public int onGetWindowAnimations() {
            final Window w = mActivity.getWindow();
            return (w == null) ? 0 : w.getAttributes().windowAnimations;
        }

        @Override
        public void onAttachFragment(Fragment fragment) {
            mActivity.onAttachFragment(fragment);
        }

        @Override
        public View onFindViewById(int id) {
            return mActivity.findViewById(id);
        }

        @Override
        public boolean onHasView() {
            final Window w = mActivity.getWindow();
            return (w != null && w.peekDecorView() != null);
        }
    }

    public static class SaveStateFragment extends Fragment {
        private static final String VALUE_KEY = "SaveStateFragment.mValue";
        private int mValue;

        public static SaveStateFragment create(int value) {
            SaveStateFragment saveStateFragment = new SaveStateFragment();
            saveStateFragment.mValue = value;
            return saveStateFragment;
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putInt(VALUE_KEY, mValue);
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (savedInstanceState != null) {
                mValue = savedInstanceState.getInt(VALUE_KEY, mValue);
            }
        }

        public int getValue() {
            return mValue;
        }
    }

    public static class RemoveHelloInOnResume extends Fragment {
        @Override
        public void onResume() {
            super.onResume();
            Fragment fragment = getFragmentManager().findFragmentByTag("Hello");
            if (fragment != null) {
                getFragmentManager().beginTransaction().remove(fragment).commit();
            }
        }
    }

    public static class InvalidateOptionFragment extends Fragment {
        public boolean onPrepareOptionsMenuCalled;

        public InvalidateOptionFragment() {
            setHasOptionsMenu(true);
        }

        @Override
        public void onPrepareOptionsMenu(Menu menu) {
            onPrepareOptionsMenuCalled = true;
            assertNotNull(getContext());
            super.onPrepareOptionsMenu(menu);
        }
    }
}