summaryrefslogtreecommitdiff
path: root/profilers/testSrc/com/android/tools/profilers/StudioProfilersTest.java
blob: 86bbfefe26ac1d98f98cf7f8eec48c4a16914f12 (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
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
/*
 * 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 com.android.tools.profilers;

import static com.android.tools.idea.transport.faketransport.FakeTransportService.FAKE_DEVICE;
import static com.android.tools.idea.transport.faketransport.FakeTransportService.FAKE_PROCESS;
import static com.android.tools.profilers.StudioProfilers.AGENT_STATUS_MAX_RETRY_COUNT;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import com.android.sdklib.AndroidVersion;
import com.android.tools.adtui.model.AspectObserver;
import com.android.tools.adtui.model.FakeTimer;
import com.android.tools.adtui.model.StreamingTimeline;
import com.android.tools.idea.transport.faketransport.FakeGrpcServer;
import com.android.tools.idea.transport.faketransport.FakeTransportService;
import com.android.tools.idea.transport.faketransport.commands.BeginSession;
import com.android.tools.profiler.proto.Commands;
import com.android.tools.profiler.proto.Common;
import com.android.tools.profiler.proto.Common.AgentData;
import com.android.tools.profiler.proto.Cpu;
import com.android.tools.profiler.proto.Memory;
import com.android.tools.profilers.cpu.CpuProfilerStage;
import com.android.tools.profilers.customevent.CustomEventProfilerStage;
import com.android.tools.profilers.energy.EnergyProfilerStage;
import com.android.tools.profilers.memory.MainMemoryProfilerStage;
import com.android.tools.profilers.network.NetworkProfilerStage;
import com.google.common.collect.ImmutableList;
import com.google.wireless.android.sdk.stats.AndroidProfilerEvent;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.jetbrains.annotations.NotNull;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public final class StudioProfilersTest {
  @Parameterized.Parameters
  public static Collection<Boolean> useNewEventPipelineParameter() {
    return Arrays.asList(false, true);
  }

  private final FakeTimer myTimer = new FakeTimer();
  private final FakeTransportService myTransportService = new FakeTransportService(myTimer, false);
  private final FakeProfilerService myProfilerService = new FakeProfilerService(myTimer);
  @Rule public FakeGrpcServer myGrpcServer =
    FakeGrpcServer.createFakeGrpcServer("StudioProfilerTestChannel", myTransportService, myProfilerService);
  private final FakeGrpcServer.CpuService myCpuService = myGrpcServer.getCpuService();
  private final FakeIdeProfilerServices myIdeProfilerServices;
  private final boolean myNewEventPipeline;

  private ProfilerClient myProfilerClient;
  private StudioProfilers myProfilers;

  public StudioProfilersTest(boolean useNewEventPipeline) {
    myIdeProfilerServices = new FakeIdeProfilerServices();
    myIdeProfilerServices.enableEventsPipeline(useNewEventPipeline);
    myNewEventPipeline = useNewEventPipeline;
  }

  @Before
  public void setUp() {
    myProfilerClient = new ProfilerClient(myGrpcServer.getChannel());
    myProfilers = new StudioProfilers(myProfilerClient, myIdeProfilerServices, myTimer);
  }

  @Test
  public void testSleepBeforeAppLaunched() {
    //Validate we start in the null stage.
    assertThat(myProfilers.getStageClass()).isSameAs(NullMonitorStage.class);

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    myTransportService.addDevice(device);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up
    myProfilers.setProcess(device, null);
    // Validate that just because we add a device, we still have not left the  null monitor stage.
    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDevice");
    assertThat(myProfilers.getStageClass()).isSameAs(NullMonitorStage.class);

    // Pick a time to set the device to. Note that this value is arbitrary but the bug this tests
    // is exposed if this value is larger than nanoTime.
    long timeOnDevice = System.nanoTime() + 1000;
    myTimer.setCurrentTimeNs(timeOnDevice);

    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);

    // Add a process and validate the stage goes to the monitor stage.
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    // Test that the process was attached correctly
    assertThat(myProfilers.getTimeline().isStreaming()).isTrue();
    // Test that the data range has not been inverted
    assertThat(myProfilers.getTimeline().getDataRange().isEmpty()).isFalse();
  }

  @Test
  public void testProfilerStageChange() {
    //Validate we start in the null stage.
    assertThat(myProfilers.getStageClass()).isSameAs(NullMonitorStage.class);

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    myTransportService.addDevice(device);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up
    myProfilers.setProcess(device, null);
    // Validate that just because we add a device, we still have not left the  null monitor stage.
    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDevice");
    assertThat(myProfilers.getStageClass()).isSameAs(NullMonitorStage.class);

    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);

    // Add a process and validate the stage goes to the monitor stage.
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getStageClass()).isSameAs(StudioMonitorStage.class);
  }

  @Test
  public void testLateConnectionOfPreferredProcess() {
    final String PREFERRED_PROCESS = "Preferred";
    myProfilers.setPreferredProcess(null, PREFERRED_PROCESS, null);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isNull();
    assertThat(myProfilers.getProcess()).isNull();

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up
    myProfilers.setProcess(device, null);
    // We are waiting for the preferred process so the process should not be selected.
    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDevice");
    assertThat(myProfilers.getProcess()).isNull();

    Common.Process preferred = createProcess(device.getDeviceId(), 21, PREFERRED_PROCESS, Common.Process.State.ALIVE);
    myTransportService.addProcess(device, preferred);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up

    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isEqualTo(preferred);
    assertThat(myProfilers.getProcesses()).hasSize(2);
    assertThat(myProfilers.getProcesses()).containsAllIn(ImmutableList.of(process, preferred));
  }

  @Test
  public void testSetPreferredProcessDoesNotProfileEarlierProcess() {
    final String PREFERRED_PROCESS = "Preferred";
    myProfilers.setPreferredProcess(null, PREFERRED_PROCESS, p -> p.getStartTimestampNs() > 5);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isNull();
    assertThat(myProfilers.getProcess()).isNull();

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process earlierProcess = Common.Process.newBuilder()
      .setDeviceId(device.getDeviceId())
      .setPid(20)
      .setName(PREFERRED_PROCESS)
      .setState(Common.Process.State.ALIVE)
      .setStartTimestampNs(5)
      .setExposureLevel(Common.Process.ExposureLevel.DEBUGGABLE)
      .build();
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, earlierProcess);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, null);
    // The process start time is before the time we start looking for preferred process, so profiler should not have started.
    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isNull();

    Common.Process afterProcess = Common.Process.newBuilder()
      .setDeviceId(device.getDeviceId())
      .setPid(21)
      .setName(PREFERRED_PROCESS)
      .setState(Common.Process.State.ALIVE)
      .setStartTimestampNs(10)
      .setExposureLevel(Common.Process.ExposureLevel.DEBUGGABLE)
      .build();
    myTransportService.addProcess(device, afterProcess);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isEqualTo(afterProcess);
    assertThat(myProfilers.getProcesses()).hasSize(2);
    assertThat(myProfilers.getProcesses()).containsAllIn(ImmutableList.of(earlierProcess, afterProcess));
  }

  @Test
  public void testDebuggableProcessNotReportedAsProfileable() {
    Assume.assumeTrue(myNewEventPipeline);
    myIdeProfilerServices.enableProfileable(true);
    myIdeProfilerServices.enableProfileableInQr(true);

    Common.Device device = FAKE_DEVICE;
    myTransportService.addDevice(device);

    Common.Process debuggableEvent = FAKE_PROCESS.toBuilder()
      .setStartTimestampNs(5)
      .setExposureLevel(Common.Process.ExposureLevel.DEBUGGABLE)
      .build();
    myTransportService.addProcess(device, debuggableEvent);

    Common.Process profileableEvent = debuggableEvent.toBuilder()
      .setStartTimestampNs(10)
      .setExposureLevel(Common.Process.ExposureLevel.PROFILEABLE)
      .build();
    myTransportService.addProcess(device, profileableEvent);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getDeviceProcessMap()).hasSize(1);
    assertThat(myProfilers.getDeviceProcessMap().get(device)).hasSize(1);
    assertThat(myProfilers.getDeviceProcessMap().get(device).get(0).getExposureLevel()).
      isEqualTo(Common.Process.ExposureLevel.DEBUGGABLE);
  }

  @Test
  public void testSetNullPreferredProcessDoesNotStartAutoProfiling() {
    final String PREFERRED_PROCESS = "Preferred";
    myProfilers.setPreferredProcess(null, null, p -> p.getStartTimestampNs() > 5);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isNull();
    assertThat(myProfilers.getProcess()).isNull();

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = Common.Process.newBuilder()
      .setDeviceId(device.getDeviceId())
      .setPid(21)
      .setName(PREFERRED_PROCESS)
      .setState(Common.Process.State.ALIVE)
      .setStartTimestampNs(10)
      .build();
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, null);
    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isNull();
    assertThat(myProfilers.getSession()).isEqualTo(Common.Session.getDefaultInstance());
  }

  @Test
  public void testConnectionError() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE)
      .toBuilder().setModel("FakeDevice").build();
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);

    myProfilers.setPreferredProcess("FakeDevice", "FakeProcess", null);
    // This should fail and not find any devices
    myTransportService.setThrowErrorOnGetDevices(true);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getDevice()).isNull();
    assertThat(myProfilers.getProcess()).isNull();

    // Server "is back up", try again
    myTransportService.setThrowErrorOnGetDevices(false);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDevice");
    assertThat(myProfilers.getProcess().getName()).isEqualTo("FakeProcess");
  }

  @Test
  public void testAlreadyConnected() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getStage()).isInstanceOf(StudioMonitorStage.class);
  }

  @Test
  public void testTimeResetOnConnectedDevice() {
    int nowInSeconds = 42;
    myTimer.setCurrentTimeNs(TimeUnit.SECONDS.toNanos(nowInSeconds));
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getTimeline().getDataRange().getMin()).isWithin(0.001).of(TimeUnit.SECONDS.toMicros(nowInSeconds));
    assertThat(myProfilers.getTimeline().getDataRange().getMax()).isWithin(0.001).of(TimeUnit.SECONDS.toMicros(nowInSeconds));

    // The timeline has reset in the previous tick, so we need to advance the current time to make sure the next tick advances data range.
    myTimer.setCurrentTimeNs(myTimer.getCurrentTimeNs() + FakeTimer.ONE_SECOND_IN_NS * 5);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS * 5);

    assertThat(myProfilers.getTimeline().getDataRange().getMin()).isWithin(0.001).of(TimeUnit.SECONDS.toMicros(nowInSeconds));
    assertThat(myProfilers.getTimeline().getDataRange().getMax()).isWithin(0.001).of(TimeUnit.SECONDS.toMicros(nowInSeconds + 5));
  }

  @Test
  public void TestDiscoverProfileableCommand() {
    Assume.assumeTrue(myNewEventPipeline);
    myIdeProfilerServices.enableProfileable(true);
    myIdeProfilerServices.enableProfileableInQr(true);
    // Devices that have executed the DISCOVER_PROFILEABLE command.
    List<Long> discoveringStreamIds = myTransportService.getDiscoveringProfileableStreamIds();
    assertThat(discoveringStreamIds).isEmpty();

    // DISCOVER_PROFILEABLE command should NOT be called on S devices.
    Common.Device deviceS = createDevice(AndroidVersion.VersionCodes.S, "FakeDeviceS", Common.Device.State.ONLINE);
    myTransportService.addDevice(deviceS);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(discoveringStreamIds).isEmpty();

    // DISCOVER_PROFILEABLE command should be called on R devices.
    Common.Device deviceR = createDevice(AndroidVersion.VersionCodes.R, "FakeDeviceR", Common.Device.State.ONLINE);
    myTransportService.addDevice(deviceR);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(discoveringStreamIds).containsExactly(deviceR.getDeviceId());

    // DISCOVER_PROFILEABLE command should be called on Q devices.
    // It's OK if multiple devices are connected at the same time.
    Common.Device deviceQ1 = createDevice(AndroidVersion.VersionCodes.Q, "FakeDeviceQ1", Common.Device.State.ONLINE);
    myTransportService.addDevice(deviceQ1);
    Common.Device deviceQ2 = createDevice(AndroidVersion.VersionCodes.Q, "FakeDeviceQ2", Common.Device.State.ONLINE);
    myTransportService.addDevice(deviceQ2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(discoveringStreamIds.subList(1, 3)).containsExactly(deviceQ1.getDeviceId(), deviceQ2.getDeviceId());

    // DISCOVER_PROFILEABLE command should NOT be called on P devices.
    Common.Device deviceP = createDevice(AndroidVersion.VersionCodes.P, "FakeDeviceP", Common.Device.State.ONLINE);
    myTransportService.addDevice(deviceP);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(discoveringStreamIds).hasSize(3);

    // DISCOVER_PROFILEABLE command should be called if a supported device is disconnected and then connected again.
    deviceQ1 = deviceQ1.toBuilder().setState(Common.Device.State.DISCONNECTED).build();
    myTransportService.addDevice(deviceQ1);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    deviceQ1 = deviceQ1.toBuilder().setState(Common.Device.State.ONLINE).build();
    myTransportService.addDevice(deviceQ1);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(discoveringStreamIds).hasSize(4);
    assertThat(discoveringStreamIds.get(3)).isEqualTo(deviceQ1.getDeviceId());
  }


  @Test
  public void testAgentUnattachableAfterMaxRetries() {
    Assume.assumeTrue(myNewEventPipeline);
    ((BeginSession)myTransportService.getRegisteredCommand(Commands.Command.CommandType.BEGIN_SESSION))
      .setAgentStatus(AgentData.Status.UNSPECIFIED);
    myProfilers.getSessionsManager().endCurrentSession();
    myProfilers.getSessionsManager().beginSession(FAKE_DEVICE.getDeviceId(), FAKE_DEVICE, FAKE_PROCESS);

    for (int i = 0; i < AGENT_STATUS_MAX_RETRY_COUNT; i++) {
      assertThat(myProfilers.getAgentData().getStatus()).isEqualTo(AgentData.Status.UNSPECIFIED);
      myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    }
    assertThat(myProfilers.getAgentData().getStatus()).isEqualTo(AgentData.Status.UNATTACHABLE);

    // Ensures that if the agent becomes attached at a later point, the status will be correct.
    Common.AgentData agentData = Common.AgentData.newBuilder().setStatus(Common.AgentData.Status.ATTACHED).build();
    long sessionStreamId = myProfilers.getSession().getStreamId();
    myTransportService.addEventToStream(sessionStreamId, Common.Event.newBuilder()
      .setPid(FAKE_PROCESS.getPid())
      .setKind(Common.Event.Kind.AGENT)
      .setAgentData(agentData)
      .build());
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getAgentData().getStatus()).isEqualTo(AgentData.Status.ATTACHED);
  }

  @Test
  public void testAgentStatusRetryCachedForSession() {
    Assume.assumeTrue(myNewEventPipeline);
    ((BeginSession)myTransportService.getRegisteredCommand(Commands.Command.CommandType.BEGIN_SESSION))
      .setAgentStatus(AgentData.Status.UNSPECIFIED);
    myProfilers.getSessionsManager().endCurrentSession();
    myProfilers.getSessionsManager().beginSession(FAKE_DEVICE.getDeviceId(), FAKE_DEVICE, FAKE_PROCESS);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    Common.Session session1 = myProfilers.getSession();

    // Switch to a different process.
    Common.Process process2 = FAKE_PROCESS.toBuilder().setPid(FAKE_PROCESS.getPid() + 1).build();
    myProfilers.getSessionsManager().endCurrentSession();
    myProfilers.getSessionsManager().beginSession(FAKE_DEVICE.getDeviceId(), FAKE_DEVICE, process2);
    // Note the following tick will update the selected session and mySessionIdToAgentStatusRetryMap for session 2.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    Common.Session session2 = myProfilers.getSession();
    int session2RetryCount = 1;  // the latest tick (two lines above) has updated the retry count.
    for (; session2RetryCount < AGENT_STATUS_MAX_RETRY_COUNT / 2; session2RetryCount++) {
      assertThat(myProfilers.getAgentData().getStatus()).isEqualTo(AgentData.Status.UNSPECIFIED);
      myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    }

    // Switch back to the first session, agent status should remain unspecified because it is ended.
    // Note we cannot call 'setSession(session1)' because the session object in the session manager has been updated
    // when it ended, and session manager doesn't want to set to an out-of-date session.
    myProfilers.getSessionsManager().setSessionById(session1.getSessionId());
    for (int j = 0; j < AGENT_STATUS_MAX_RETRY_COUNT * 2; j++) {
      myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    }
    assertThat(myProfilers.getAgentData().getStatus()).isEqualTo(AgentData.Status.UNSPECIFIED);

    // Switch back to the second session, we should only need another
    // (AGENT_STATUS_MAX_RETRY_COUNT - session2RetryCount) ticks to reach UNATTACHABLE.
    myProfilers.getSessionsManager().setSession(session2);
    for (; session2RetryCount < AGENT_STATUS_MAX_RETRY_COUNT; session2RetryCount++) {
      assertThat(myProfilers.getAgentData().getStatus()).isEqualTo(AgentData.Status.UNSPECIFIED);
      myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    }
    assertThat(myProfilers.getAgentData().getStatus()).isEqualTo(AgentData.Status.UNATTACHABLE);

    // Switch to the first session and back should give UNATTACHABLE immediately.
    myProfilers.getSessionsManager().setSessionById(session1.getSessionId());
    myProfilers.getSessionsManager().setSessionById(session2.getSessionId());
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getAgentData().getStatus()).isEqualTo(AgentData.Status.UNATTACHABLE);
  }

  @Test
  public void testAgentAspectFiring() {
    AgentStatusAspectObserver observer = new AgentStatusAspectObserver();
    myProfilers.addDependency(observer).onChange(ProfilerAspect.AGENT, observer::AgentStatusChanged);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getAgentData()).isEqualTo(AgentData.getDefaultInstance());
    assertThat(observer.getAgentStatusChangedCount()).isEqualTo(0);

    // Test that status changes if no process is selected does nothing
    AgentData attachedResponse = AgentData.newBuilder().setStatus(AgentData.Status.ATTACHED).build();
    myTransportService.setAgentStatus(attachedResponse);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getProcess()).isNull();
    assertThat(myProfilers.getAgentData()).isEqualTo(AgentData.getDefaultInstance());
    assertThat(observer.getAgentStatusChangedCount()).isEqualTo(0);

    // Test that agent status change fires after a process is selected.
    Common.Device device = createDevice(AndroidVersion.VersionCodes.O, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process1 = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    Common.Process process2 = createProcess(device.getDeviceId(), 21, "FakeProcess2", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process1);
    myTransportService.addProcess(device, process2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process1);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getProcess()).isEqualTo(process1);
    assertThat(myProfilers.getAgentData()).isEqualTo(attachedResponse);
    assertThat(observer.getAgentStatusChangedCount()).isEqualTo(1);

    // Test that manually setting a process fires an agent status change
    myProfilers.setProcess(device, process2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getProcess()).isSameAs(process2);
    assertThat(myProfilers.getAgentData()).isEqualTo(attachedResponse);
    assertThat(observer.getAgentStatusChangedCount()).isEqualTo(2);

    // Setting the same agent status should not trigger an aspect change.
    attachedResponse = AgentData.newBuilder().setStatus(AgentData.Status.ATTACHED).build();
    myTransportService.setAgentStatus(attachedResponse);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getAgentData()).isEqualTo(attachedResponse);
    assertThat(observer.getAgentStatusChangedCount()).isEqualTo(2);
  }

  @Test
  public void testAgentAspectNotFiredWhenSettingSameDeviceProcess() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);

    AgentStatusAspectObserver observer = new AgentStatusAspectObserver();
    myProfilers.addDependency(observer).onChange(ProfilerAspect.AGENT, observer::AgentStatusChanged);

    // Test that the status changed is fired when the process first gets selected.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getDevice()).isSameAs(device);
    assertThat(myProfilers.getProcess()).isEqualTo(process);
    assertThat(myProfilers.isAgentAttached()).isFalse();
    assertThat(observer.getAgentStatusChangedCount()).isEqualTo(1);

    // Test that resetting the same device/process would not trigger the status changed event.
    myProfilers.setProcess(device, process);
    assertThat(myProfilers.getDevice()).isSameAs(device);
    assertThat(myProfilers.getProcess()).isEqualTo(process);
    assertThat(myProfilers.isAgentAttached()).isFalse();
    assertThat(observer.getAgentStatusChangedCount()).isEqualTo(1);
  }

  @Test
  public void testRestartedPreferredProcessNotSelected() {
    Assume.assumeTrue(myNewEventPipeline);
    //int nowInSeconds = 42;
    //myTransportService.setTimestampNs(TimeUnit.SECONDS.toNanos(nowInSeconds));
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    Common.Device device =
      createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE).toBuilder().setModel("FakeDevice").build();
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myProfilers.setPreferredProcess("FakeDevice", process.getName(), null);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getProcess().getPid()).isEqualTo(20);
    assertThat(myProfilers.getProcess().getState()).isEqualTo(Common.Process.State.ALIVE);

    // Change the alive (active) process to DEAD, and create a new ALIVE process simulating a debugger restart.
    myTransportService.removeProcess(device, process);
    process = process.toBuilder()
      .setState(Common.Process.State.DEAD)
      .build();
    myTransportService.addProcess(device, process);

    // Verify the process is in the dead state.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getProcess().getPid()).isEqualTo(20);
    assertThat(myProfilers.getProcess().getState()).isEqualTo(Common.Process.State.DEAD);

    process = process.toBuilder()
      .setPid(21)
      .setState(Common.Process.State.ALIVE)
      .build();
    myTransportService.addProcess(device, process);


    // The profiler should not automatically selects the alive, preferred process again.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getProcess().getPid()).isEqualTo(20);
    assertThat(myProfilers.getProcess().getState()).isEqualTo(Common.Process.State.DEAD);
    assertThat(myProfilers.getAutoProfilingEnabled()).isFalse();

    // Re-enable auto-profiling should pick up the new process.
    myProfilers.setAutoProfilingEnabled(true);
    // We need a change in processes to trigger the pickup. In production, setAutoProfilingEnabled(true)
    // is called only by StudioProfilers.setPreferredProcess() which is called when (1) the app is deployed,
    // (2) profiler tool window is initialized, or (3) profiler window is reopened and the app was deployed
    // but not profiled before. We simulate (1) here.
    myTransportService.removeProcess(device, process); // for legacy pipeline
    process = process.toBuilder().setState(Common.Process.State.DEAD).build();
    myTransportService.addProcess(device, process); // for unified pipeline
    process = process.toBuilder()
      .setPid(22)
      .setState(Common.Process.State.ALIVE)
      .build();
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getProcess().getPid()).isEqualTo(22);
    assertThat(myProfilers.getProcess().getState()).isEqualTo(Common.Process.State.ALIVE);
  }

  @Test
  public void shouldNotSelectPreferredAfterUserSelectsOtherProcess() {
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE)
      .toBuilder().setModel("FakeDevice").build();
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myProfilers.setPreferredProcess("FakeDevice", process.getName(), null);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getProcess().getPid()).isEqualTo(20);
    assertThat(myProfilers.getProcess().getState()).isEqualTo(Common.Process.State.ALIVE);

    Common.Process otherProcess = createProcess(device.getDeviceId(), 21, "OtherProcess", Common.Process.State.ALIVE);
    myTransportService.addProcess(device, otherProcess);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, otherProcess);
    // The user selected the other process explicitly
    assertThat(myProfilers.getProcess().getPid()).isEqualTo(21);
    assertThat(myProfilers.getProcess().getState()).isEqualTo(Common.Process.State.ALIVE);

    // Should select the other process again
    myProfilers.setProcess(device, null);
    assertThat(myProfilers.getProcess().getPid()).isEqualTo(21);
    assertThat(myProfilers.getProcess().getState()).isEqualTo(Common.Process.State.ALIVE);
  }

  @Test
  public void shouldOpenMemoryProfileStageIfStartupProfilingStarted() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);

    myTransportService.addEventToStream(device.getDeviceId(), Common.Event.newBuilder()
      .setPid(process.getPid())
      .setCommandId(1)
      .setKind(Common.Event.Kind.MEMORY_NATIVE_SAMPLE_STATUS)
      .setTimestamp(myTimer.getCurrentTimeNs())
      .setGroupId(myTimer.getCurrentTimeNs())
      .setMemoryNativeTrackingStatus(Memory.MemoryNativeTrackingData.newBuilder()
                                       .setStartTime(myTimer.getCurrentTimeNs())
                                       .setStatus(Memory.MemoryNativeTrackingData.Status.SUCCESS)
                                       .build())
      .build());
    // To make sure that StudioProfilers#update is called, which in a consequence polls devices and processes,
    // and starts a new session with the preferred process name.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getProcess().getPid()).isEqualTo(20);
    assertThat(myProfilers.getProcess().getState()).isEqualTo(Common.Process.State.ALIVE);
    assertThat(myProfilers.getStage()).isInstanceOf(MainMemoryProfilerStage.class);
  }

  @Test
  public void shouldOpenCpuProfileStageIfStartupProfilingStarted() {
    myIdeProfilerServices.enableStartupCpuProfiling(true);

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);

    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    Cpu.CpuTraceInfo traceInfo = Cpu.CpuTraceInfo.newBuilder()
      .setConfiguration(Cpu.CpuTraceConfiguration.newBuilder()
                          .setInitiationType(Cpu.TraceInitiationType.INITIATED_BY_STARTUP))
      .build();
    if (myNewEventPipeline) {
      myTransportService.addEventToStream(device.getDeviceId(), Common.Event.newBuilder()
        .setGroupId(myTimer.getCurrentTimeNs())
        .setPid(process.getPid())
        .setKind(Common.Event.Kind.CPU_TRACE)
        .setCpuTrace(Cpu.CpuTraceData.newBuilder()
                       .setTraceEnded(Cpu.CpuTraceData.TraceEnded.newBuilder().setTraceInfo(traceInfo).build()))
        .build());
    }
    else {
      myCpuService.addTraceInfo(traceInfo);
    }

    // To make sure that StudioProfilers#update is called, which in a consequence polls devices and processes,
    // and starts a new session with the preferred process name.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getProcess().getPid()).isEqualTo(20);
    assertThat(myProfilers.getProcess().getState()).isEqualTo(Common.Process.State.ALIVE);
    assertThat(myProfilers.getStage()).isInstanceOf(CpuProfilerStage.class);
  }

  @Test
  public void testProcessStateChangesShouldNotTriggerStageChange() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getProcess().getPid()).isEqualTo(20);
    assertThat(Common.Process.State.ALIVE).isEqualTo(myProfilers.getProcess().getState());

    AspectObserver observer = new AspectObserver();
    myProfilers.addDependency(observer).onChange(ProfilerAspect.STAGE, () -> {
      assert false;
    });
    // Change the alive (active) process to DEAD
    myTransportService.removeProcess(device, process);
    process = process.toBuilder()
      .setState(Common.Process.State.DEAD)
      .build();
    myTransportService.addProcess(device, process);

    //Verify the process is in the dead state.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getProcess().getPid()).isEqualTo(20);
    assertThat(Common.Process.State.DEAD).isEqualTo(myProfilers.getProcess().getState());
  }

  @Test
  public void timelineShouldBeStreamingWhenProcessIsSelected() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getTimeline().isStreaming()).isTrue();
  }

  @Test
  public void timelineShouldStopStreamingWhenRangeIsSelected() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    StreamingTimeline timeline = myProfilers.getTimeline();
    assertTrue(timeline.isStreaming());
    timeline.getDataRange().set(0, FakeTimer.ONE_SECOND_IN_NS);
    timeline.getSelectionRange().set(0, 0);
    assertFalse(timeline.isStreaming());

    timeline.setStreaming(true);
    assertTrue(timeline.isStreaming());
    timeline.getSelectionRange().set(0, FakeTimer.ONE_SECOND_IN_NS);
    assertFalse(timeline.isStreaming());
  }

  @Test
  public void onlineDeviceShouldNotOverrideSelectedOfflineDevice() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isEqualTo(process);

    // Connect a new device, and marks the old one as disconnected
    Common.Device dead_device = device.toBuilder().setState(Common.Device.State.DISCONNECTED).build();
    Common.Device device2 = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice2", Common.Device.State.ONLINE);
    Common.Process process2 = createProcess(device2.getDeviceId(), 21, "FakeProcess2", Common.Process.State.ALIVE);
    myTransportService.updateDevice(device, dead_device);
    myTransportService.addDevice(device2);
    myTransportService.addProcess(device2, process2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    // Connecting an online device should not override previously selection automatically
    assertThat(myProfilers.getDevice()).isEqualTo(dead_device);
    assertThat(myProfilers.getProcess()).isEqualTo(process);
  }

  @Test
  public void preferredDeviceShouldNotOverrideSelectedDevice() {
    myProfilers.setPreferredProcess("Manufacturer Model", "ProcessName", null);

    // A device with a process that can be profiled
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);

    // The preferred device
    Common.Device preferredDevice = createDevice(AndroidVersion.VersionCodes.BASE, "PreferredDevice", Common.Device.State.ONLINE);
    preferredDevice = preferredDevice.toBuilder().setManufacturer("Manufacturer").setModel("Model").build();
    Common.Process preferredProcess =
      createProcess(preferredDevice.getDeviceId(), 21, "PreferredProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(preferredDevice);
    myTransportService.addProcess(preferredDevice, preferredProcess);

    // Preferred should be selected.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isEqualTo(preferredDevice);

    // Selecting device manually should keep it selected
    myProfilers.setProcess(device, null);
    assertThat(myProfilers.getDevice()).isEqualTo(device);

    // Changing states on the preferred device should have no effects.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isEqualTo(device);

    Common.Device offlinePreferredDevice = preferredDevice.toBuilder().setState(Common.Device.State.DISCONNECTED).build();
    myTransportService.updateDevice(preferredDevice, offlinePreferredDevice);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isEqualTo(device);

    myTransportService.updateDevice(offlinePreferredDevice, preferredDevice);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isEqualTo(device);
  }

  @Test
  public void preferredDeviceHasPriority() {
    myProfilers.setPreferredProcess("Manufacturer Model", "PreferredProcess", null);

    // A device with a process that can be profiled
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);

    // Create the preferred device but have it offline to start with.
    Common.Device offlinePreferredDevice = createDevice(AndroidVersion.VersionCodes.BASE, "PreferredDevice", Common.Device.State.OFFLINE);
    offlinePreferredDevice = offlinePreferredDevice.toBuilder().setManufacturer("Manufacturer").setModel("Model").build();
    Common.Process preferredProcess =
      createProcess(offlinePreferredDevice.getDeviceId(), 21, "PreferredProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(offlinePreferredDevice);
    myTransportService.addProcess(offlinePreferredDevice, preferredProcess);
    // No device should be selected given no online preferred device is found.
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isNull();
    assertThat(myProfilers.getProcess()).isNull();

    // Turn the preferred device online and it should be selected.
    Common.Device preferredDevice = offlinePreferredDevice.toBuilder().setState(Common.Device.State.ONLINE).build();
    myTransportService.updateDevice(offlinePreferredDevice, preferredDevice);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isEqualTo(preferredDevice);
    assertThat(myProfilers.getProcess()).isEqualTo(preferredProcess);

    Common.Device preferredDevice2 = createDevice(AndroidVersion.VersionCodes.BASE, "PreferredDevice2", Common.Device.State.ONLINE);
    preferredDevice2 = preferredDevice2.toBuilder().setManufacturer("Manufacturer2").setModel("Model2").build();
    Common.Process preferredProcess2 = createProcess(preferredDevice2.getDeviceId(), 22, "PreferredProcess2", Common.Process.State.ALIVE);
    myTransportService.addDevice(preferredDevice2);
    myTransportService.addProcess(preferredDevice2, preferredProcess2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isEqualTo(preferredDevice);
    assertThat(myProfilers.getProcess()).isEqualTo(preferredProcess);

    // Updating the preferred device should switch over.
    myProfilers.setPreferredProcess("Manufacturer2 Model2", "PreferredProcess", null);
    // We need a change in processes to trigger the pickup. In production, setAutoProfilingEnabled(true)
    // is called only by StudioProfilers.setPreferredProcess() which is called when (1) the app is deployed,
    // (2) profiler tool window is initialized, or (3) profiler window is reopened and the app was deployed
    // but not profiled before. We simulate (1) here.
    process = preferredProcess2.toBuilder()
      .setState(Common.Process.State.DEAD).build();
    myTransportService.addProcess(preferredDevice2, process);
    myTransportService.removeProcess(preferredDevice2, preferredProcess2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myTransportService.addProcess(preferredDevice2, preferredProcess2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isEqualTo(preferredDevice2);
    assertThat(myProfilers.getProcess()).isNull();
  }

  @Test
  public void keepSelectedDeviceAfterDisconnectingAllDevices() {
    Common.Device device1 = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process1 = createProcess(device1.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device1);
    myTransportService.addProcess(device1, process1);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    // Connect a new device
    Common.Device device2 = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice2", Common.Device.State.ONLINE);
    Common.Process process2 = createProcess(device2.getDeviceId(), 21, "FakeProcess2", Common.Process.State.ALIVE);
    myTransportService.addDevice(device2);
    myTransportService.addProcess(device2, process2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    myProfilers.setProcess(device2, null);
    assertThat(myProfilers.getDevice()).isEqualTo(device2);
    // Update device1 state to disconnect
    Common.Device disconnectedDevice = Common.Device.newBuilder()
      .setDeviceId(device1.getDeviceId())
      .setSerial(device1.getSerial())
      .setState(Common.Device.State.DISCONNECTED)
      .build();
    myTransportService.updateDevice(device1, disconnectedDevice);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    // Update device2 state to disconnect
    Common.Device disconnectedDevice2 = Common.Device.newBuilder()
      .setDeviceId(device2.getDeviceId())
      .setSerial(device2.getSerial())
      .setState(Common.Device.State.DISCONNECTED)
      .build();
    myTransportService.updateDevice(device2, disconnectedDevice2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    // Selected device should be FakeDevice2, which was selected before disconnecting all devices
    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDevice2");
    // Make sure the device is disconnected
    assertThat(myProfilers.getDevice().getState()).isEqualTo(Common.Device.State.DISCONNECTED);
  }

  @Test
  public void testProfileOneProcessAtATime() {
    Common.Device device1 = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process1 = createProcess(device1.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    Common.Process process2 = createProcess(device1.getDeviceId(), 21, "FakeProcess2", Common.Process.State.ALIVE);
    myTransportService.addDevice(device1);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(0);
    myTransportService.addProcess(device1, process1);
    myTransportService.addProcess(device1, process2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device1, process1);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getProcess()).isEqualTo(process1);
    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(1);

    // Switch to another process.
    myProfilers.setProcess(device1, process2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(1);
    assertThat(myProfilers.getProcess()).isEqualTo(process2);

    // Connect a new device with a process.
    Common.Device device2 = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice2", Common.Device.State.ONLINE);
    Common.Process process3 = createProcess(device2.getDeviceId(), 22, "FakeProcess3", Common.Process.State.ALIVE);
    myTransportService.addDevice(device2);
    myTransportService.addProcess(device2, process3);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    // Switch to the new device + process
    myProfilers.setProcess(device2, process3);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(1);
    assertThat(myProfilers.getProcess()).isEqualTo(process3);

    // Update device2 state to disconnect
    Common.Device disconnectedDevice2 = device2.toBuilder()
      .setState(Common.Device.State.DISCONNECTED)
      .build();
    myTransportService.updateDevice(device2, disconnectedDevice2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(0);

    // Switch back to the first device.
    myProfilers.setProcess(device1, process1);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(1);

    // Update device1 state to disconnect
    Common.Device disconnectedDevice = device1.toBuilder()
      .setState(Common.Device.State.DISCONNECTED)
      .build();
    myTransportService.updateDevice(device1, disconnectedDevice);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(0);
  }

  @Test
  public void testAttachAgentCalledPostO() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.O, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process1 = createProcess(device.getDeviceId(), 1, "FakeProcess1", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process1);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process1);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isEqualTo(process1);
    assertThat(myNewEventPipeline ? myTransportService.getAgentAttachCalled() : myProfilerService.getAgentAttachCalled()).isTrue();
  }

  @Test
  public void testAttachAgentNotCalledPreO() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.N, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process1 = createProcess(device.getDeviceId(), 1, "FakeProcess1", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process1);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process1);

    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isEqualTo(process1);
    assertThat(myNewEventPipeline ? myTransportService.getAgentAttachCalled() : myProfilerService.getAgentAttachCalled()).isFalse();
  }

  /**
   * We need to account for an scenario where perfd reinstantiates and needs to pass a new client socket to the app. Hence we make the
   * same attach agent call from Studio side and let perfd handles the rest.
   */
  @Test
  public void testAttachAgentEvenIfAlreadyAttached() {
    AgentData attachedResponse = AgentData.newBuilder().setStatus(AgentData.Status.ATTACHED).build();
    myTransportService.setAgentStatus(attachedResponse);
    Common.Device device = createDevice(AndroidVersion.VersionCodes.O, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process1 = createProcess(device.getDeviceId(), 1, "FakeProcess1", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process1);

    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process1);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isEqualTo(process1);
    assertThat(myNewEventPipeline ? myTransportService.getAgentAttachCalled() : myProfilerService.getAgentAttachCalled()).isTrue();
  }

  @Test
  public void testProfilingStops() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE)
      .toBuilder().setModel("FakeDevice").build();
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);

    myTransportService.addDevice(device);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(0);
    myTransportService.addProcess(device, process);

    myProfilers.setPreferredProcess("FakeDevice", "FakeProcess", null);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getProcess()).isEqualTo(process);
    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(1);
    assertThat(myProfilers.getProcess()).isEqualTo(process);
    assertThat(myTimer.isRunning()).isTrue();

    // Stop the profiler
    myProfilers.stop();

    assertThat(myGrpcServer.getProfiledProcessCount()).isEqualTo(0);
    assertThat(myProfilers.getProcess()).isNull();
    assertThat(myProfilers.getDevice()).isNull();
    assertThat(myTimer.isRunning()).isFalse();
  }

  @Test
  public void testNullDeviceKeepsPreviousSession() {
    Common.Device device1 = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice1", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device1.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    Common.Device device2 = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice2", Common.Device.State.ONLINE);
    myTransportService.addDevice(device1);
    myTransportService.addProcess(device1, process);
    myTransportService.addDevice(device2);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device1, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    Common.Session session = myProfilers.getSession();
    assertThat(myProfilers.getDevice()).isEqualTo(device1);
    assertThat(myProfilers.getProcess()).isEqualTo(process);
    assertThat(session).isNotEqualTo(Common.Session.getDefaultInstance());
    assertThat(myProfilers.getStageClass()).isEqualTo(StudioMonitorStage.class);

    // Setting device and process to null should maintain the current session.
    myProfilers.setProcess(null, null);
    assertThat(myProfilers.getDevice()).isEqualTo(null);
    assertThat(myProfilers.getProcess()).isEqualTo(null);
    assertThat(myProfilers.getSession().getSessionId()).isEqualTo(session.getSessionId());
    assertThat(myProfilers.getStageClass()).isEqualTo(StudioMonitorStage.class);
  }

  @Test
  public void testUnsupportedDeviceShowsNullStage() {
    String deviceName = "UnsupportedDevice";
    String unsupportedReason = "Unsupported device";
    Common.Device device = Common.Device.newBuilder()
      .setDeviceId(deviceName.hashCode())
      .setFeatureLevel(AndroidVersion.VersionCodes.KITKAT)
      .setModel(deviceName)
      .setState(Common.Device.State.ONLINE)
      .setUnsupportedReason(unsupportedReason)
      .build();
    myTransportService.addDevice(device);
    myProfilers.setPreferredProcess(deviceName, "FakeProcess", null);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isNull();
    assertThat(myProfilers.getStageClass()).isEqualTo(NullMonitorStage.class);
    assertThat(((NullMonitorStage)myProfilers.getStage()).getUnsupportedReason()).isEqualTo(unsupportedReason);
  }

  @Test
  public void testProfilingStopsWithLiveAllocationEnabled() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.O, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);

    myTransportService.addDevice(device);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);

    assertThat(myTimer.isRunning()).isTrue();

    assertThat(myProfilers.getDevice()).isEqualTo(device);
    assertThat(myProfilers.getProcess()).isEqualTo(process);

    // Stop the profiler
    myProfilers.stop();

    assertThat(myTimer.isRunning()).isFalse();
    assertThat(myProfilers.getProcess()).isEqualTo(null);
    assertThat(myProfilers.getDevice()).isEqualTo(null);
  }

  @Test
  public void testStoppingTwice() {
    // Should be modified when STAGE aspect is fired.
    boolean[] stageAspectTriggered = {false};
    myProfilers.addDependency(new AspectObserver())
      .onChange(ProfilerAspect.STAGE, () -> stageAspectTriggered[0] = true);

    // Check profiler is not stopped.
    assertThat(myProfilers.isStopped()).isFalse();
    assertThat(myTimer.isRunning()).isTrue();
    // Stop the profiler
    myProfilers.stop();
    // Profiler should have stopped and STAGE is supposed to have been fired.
    assertThat(stageAspectTriggered[0]).isTrue();

    // Check profiler is stopped.
    assertThat(myProfilers.isStopped()).isTrue();
    assertThat(myTimer.isRunning()).isFalse();
    stageAspectTriggered[0] = false;
    // Try to stop the profiler again.
    myProfilers.stop();
    // Profiler was already stopped and STAGE is not supposed to have been fired.
    assertThat(stageAspectTriggered[0]).isFalse();
  }

  @Test
  public void testBeginAndEndSessionOnProcessChange() {
    assertThat(myProfilers.getSession()).isEqualTo(Common.Session.getDefaultInstance());

    // Adds a device without processes. Session should be null.
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    myTransportService.addDevice(device);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up
    assertThat(myProfilers.getSession()).isEqualTo(Common.Session.getDefaultInstance());

    // Adds a process, which should trigger the session to start.
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getSession().getStreamId()).isEqualTo(device.getDeviceId());
    assertThat(myProfilers.getSession().getPid()).isEqualTo(process.getPid());
    assertThat(myProfilers.getSession().getEndTimestamp()).isEqualTo(Long.MAX_VALUE);

    // Mark the process as dead, which should ends the session.
    myTransportService.removeProcess(device, process);
    process = process.toBuilder().setState(Common.Process.State.DEAD).build();
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getSession().getStreamId()).isEqualTo(device.getDeviceId());
    assertThat(myProfilers.getSession().getPid()).isEqualTo(process.getPid());
    assertThat(myProfilers.getSession().getEndTimestamp()).isNotEqualTo(Long.MAX_VALUE);
  }

  @Test
  public void testBeginAndEndSessionOnDeviceChange() {
    assertThat(myProfilers.getSession()).isEqualTo(Common.Session.getDefaultInstance());

    // Adds a device with process. Session should start immediately
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getSession().getStreamId()).isEqualTo(device.getDeviceId());
    assertThat(myProfilers.getSession().getPid()).isEqualTo(process.getPid());
    assertThat(myProfilers.getSession().getEndTimestamp()).isEqualTo(Long.MAX_VALUE);

    // Killing the device should stop the session
    myTransportService.removeProcess(device, process);
    Common.Device deadDevice = device.toBuilder().setState(Common.Device.State.DISCONNECTED).build();
    Common.Process deadProcess = process.toBuilder().setState(Common.Process.State.DEAD).build();
    myTransportService.addDevice(deadDevice);
    myTransportService.addProcess(deadDevice, deadProcess);
    myTimer.setCurrentTimeNs(FakeTimer.ONE_SECOND_IN_NS);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getSession().getStreamId()).isEqualTo(device.getDeviceId());
    assertThat(myProfilers.getSession().getPid()).isEqualTo(process.getPid());
    assertThat(myProfilers.getSession().getEndTimestamp()).isNotEqualTo(Long.MAX_VALUE);
  }

  @Test
  public void testSessionDoesNotAutoStartOnSameProcess() {
    assertThat(myProfilers.getSession()).isEqualTo(Common.Session.getDefaultInstance());

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    // End the session.
    myTransportService.removeProcess(device, process);
    process = process.toBuilder().setState(Common.Process.State.DEAD).build();
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    Common.Session session = myProfilers.getSession();
    assertThat(session).isNotNull();
    assertThat(session.getStreamId()).isEqualTo(device.getDeviceId());
    assertThat(session.getPid()).isEqualTo(process.getPid());

    // The same process coming alive should not start a new session automatically.
    myTransportService.removeProcess(device, process);
    process = process.toBuilder().setState(Common.Process.State.ALIVE).build();
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getSession()).isEqualTo(session);
  }

  @Test
  public void testNewSessionResetsStage() {
    assertThat(myProfilers.getSession()).isEqualTo(Common.Session.getDefaultInstance());

    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS); // One second must be enough for new devices to be picked up
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getSession()).isNotNull();
    assertThat(myProfilers.getSession().getStreamId()).isEqualTo(device.getDeviceId());
    assertThat(myProfilers.getSession().getPid()).isEqualTo(process.getPid());
    assertThat(myProfilers.getSession().getEndTimestamp()).isEqualTo(Long.MAX_VALUE);
    assertThat(myProfilers.getStage()).isInstanceOf(StudioMonitorStage.class);

    // Goes into a different stage
    myProfilers.setStage(new FakeStage(myProfilers));
    assertThat(myProfilers.getStage()).isInstanceOf(FakeStage.class);

    // Ending a session should not leave the stage automatically.
    myTransportService.removeProcess(device, process);
    process = process.toBuilder().setState(Common.Process.State.DEAD).build();
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getSession()).isNotNull();
    assertThat(myProfilers.getSession().getStreamId()).isEqualTo(device.getDeviceId());
    assertThat(myProfilers.getSession().getPid()).isEqualTo(process.getPid());
    assertThat(myProfilers.getSession().getEndTimestamp()).isNotEqualTo(Long.MAX_VALUE);
    assertThat(myProfilers.getStage()).isInstanceOf(FakeStage.class);

    // Restarting a session on the same process should re-enter the StudioMonitorStage
    myTransportService.removeProcess(device, process);
    process = process.toBuilder().setState(Common.Process.State.ALIVE).build();
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    assertThat(myProfilers.getSession()).isNotNull();
    assertThat(myProfilers.getSession().getStreamId()).isEqualTo(device.getDeviceId());
    assertThat(myProfilers.getSession().getPid()).isEqualTo(process.getPid());
    assertThat(myProfilers.getSession().getEndTimestamp()).isEqualTo(Long.MAX_VALUE);
    assertThat(myProfilers.getStage()).isInstanceOf(StudioMonitorStage.class);
  }

  @Test
  public void testGetDirectStagesReturnsOnlyExpectedStages() {
    // When energy flag is enabled and device is pre-O, GetDirectStages does not return Energy stage.
    myIdeProfilerServices.enableEnergyProfiler(true);
    Common.Device deviceNougat = createDevice(AndroidVersion.VersionCodes.N_MR1, "FakeDeviceN", Common.Device.State.ONLINE);
    myTransportService.addDevice(deviceNougat);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(deviceNougat, null);
    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDeviceN");

    assertThat(myProfilers.getDirectStages()).containsExactly(
      CpuProfilerStage.class,
      MainMemoryProfilerStage.class,
      NetworkProfilerStage.class).inOrder();

    // When energy flag is enabled and device is O, GetDirectStages returns Energy stage.
    Common.Device deviceOreo = createDevice(AndroidVersion.VersionCodes.O, "FakeDeviceO", Common.Device.State.ONLINE);
    myTransportService.addDevice(deviceOreo);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(deviceOreo, null);
    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDeviceO");

    assertThat(myProfilers.getDirectStages()).containsExactly(
      CpuProfilerStage.class,
      MainMemoryProfilerStage.class,
      NetworkProfilerStage.class,
      EnergyProfilerStage.class).inOrder();

    // When energy flag is disabled and device is O, GetDirectStages does not return Energy stage.
    myIdeProfilerServices.enableEnergyProfiler(false);
    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDeviceO");

    assertThat(myProfilers.getDirectStages()).containsExactly(
      CpuProfilerStage.class,
      MainMemoryProfilerStage.class,
      NetworkProfilerStage.class).inOrder();

    // When custom event flag is enabled and device is O, GetDirectStages returns Custom Event stage.
    myIdeProfilerServices.enableCustomEventVisualization(true);
    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDeviceO");

    assertThat(myProfilers.getDirectStages()).containsExactly(
      CpuProfilerStage.class,
      MainMemoryProfilerStage.class,
      NetworkProfilerStage.class,
      CustomEventProfilerStage.class).inOrder();

    // When custom event flag is disabled and device is O, GetDirectStages does not return Custom Event stage.
    myIdeProfilerServices.enableCustomEventVisualization(false);
    assertThat(myProfilers.getDevice().getSerial()).isEqualTo("FakeDeviceO");

    assertThat(myProfilers.getDirectStages()).containsExactly(
      CpuProfilerStage.class,
      MainMemoryProfilerStage.class,
      NetworkProfilerStage.class).inOrder();
  }

  @Test
  public void testGetDirectStageReturnsEnergyOnlyForPostOSession() {
    // When energy flag is enabled and the session is pre-O, GetDirectStages does not return Energy stage.
    myIdeProfilerServices.enableEnergyProfiler(true);
    Common.Session sessionPreO = Common.Session.newBuilder()
      .setSessionId(1).setStartTimestamp(FakeTimer.ONE_SECOND_IN_NS).setEndTimestamp(FakeTimer.ONE_SECOND_IN_NS * 2).build();
    Common.SessionMetaData sessionPreOMetadata = Common.SessionMetaData.newBuilder()
      .setSessionId(1).setType(Common.SessionMetaData.SessionType.FULL).setJvmtiEnabled(false).setStartTimestampEpochMs(1).build();

    if (myNewEventPipeline) {
      myTransportService.addSession(sessionPreO, sessionPreOMetadata);
    }
    else {
      myProfilerService.addSession(sessionPreO, sessionPreOMetadata);
    }
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.getSessionsManager().setSession(myProfilers.getSessionsManager().getSessionArtifacts().get(0).getSession());
    assertThat(myProfilers.getSessionsManager().getSelectedSessionMetaData().getJvmtiEnabled()).isFalse();

    assertThat(myProfilers.getDirectStages()).containsExactly(
      CpuProfilerStage.class,
      MainMemoryProfilerStage.class,
      NetworkProfilerStage.class).inOrder();

    // When energy flag is enabled and the session is O, GetDirectStages returns Energy stage.
    Common.Session sessionO = Common.Session.newBuilder()
      .setSessionId(2).setStartTimestamp(FakeTimer.ONE_SECOND_IN_NS).setEndTimestamp(FakeTimer.ONE_SECOND_IN_NS * 2).build();
    Common.SessionMetaData sessionOMetadata = Common.SessionMetaData.newBuilder()
      .setSessionId(2).setType(Common.SessionMetaData.SessionType.FULL).setJvmtiEnabled(true).setStartTimestampEpochMs(1).build();
    if (myNewEventPipeline) {
      myTransportService.addSession(sessionO, sessionOMetadata);
    }
    else {
      myProfilerService.addSession(sessionO, sessionOMetadata);
    }
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.getSessionsManager().setSession(myProfilers.getSessionsManager().getSessionArtifacts().get(0).getSession());
    assertThat(myProfilers.getSessionsManager().getSelectedSessionMetaData().getJvmtiEnabled()).isTrue();

    assertThat(myProfilers.getDirectStages()).containsExactly(
      CpuProfilerStage.class,
      MainMemoryProfilerStage.class,
      NetworkProfilerStage.class,
      EnergyProfilerStage.class).inOrder();

    // When energy flag is disabled and the session is pre-O, GetDirectStages does not return Energy stage.
    myIdeProfilerServices.enableEnergyProfiler(false);
    assertThat(myProfilers.getSessionsManager().getSelectedSessionMetaData().getJvmtiEnabled()).isTrue();
    assertThat(myProfilers.getDirectStages()).containsExactly(
      CpuProfilerStage.class,
      MainMemoryProfilerStage.class,
      NetworkProfilerStage.class).inOrder();
  }

  @Test
  public void testBuildSessionName() {
    Common.Device device1 = Common.Device.newBuilder()
      .setManufacturer("Manufacturer")
      .setModel("Model")
      .setSerial("Serial")
      .build();
    Common.Device device2 = Common.Device.newBuilder()
      .setModel("Model-Serial")
      .setSerial("Serial")
      .build();
    Common.Process process1 = Common.Process.newBuilder()
      .setPid(10)
      .setAbiCpuArch("x86")
      .setName("Process1")
      .build();
    Common.Process process2 = Common.Process.newBuilder()
      .setPid(20)
      .setAbiCpuArch("arm")
      .setName("Process2")
      .build();

    assertThat(StudioProfilers.buildSessionName(device1, process1)).isEqualTo("Process1 (Manufacturer Model)");
    assertThat(StudioProfilers.buildSessionName(device2, process2)).isEqualTo("Process2 (Model)");
  }

  @Test
  public void testBuildDeviceName() {
    Common.Device device = Common.Device.newBuilder()
      .setManufacturer("Manufacturer")
      .setModel("Model")
      .setSerial("Serial")
      .build();
    assertThat(StudioProfilers.buildDeviceName(device)).isEqualTo("Manufacturer Model");

    Common.Device deviceWithEmptyManufacturer = Common.Device.newBuilder()
      .setModel("Model")
      .setSerial("Serial")
      .build();
    assertThat(StudioProfilers.buildDeviceName(deviceWithEmptyManufacturer)).isEqualTo("Model");

    Common.Device deviceWithSerialInModel = Common.Device.newBuilder()
      .setManufacturer("Manufacturer")
      .setModel("Model-Serial")
      .setSerial("Serial")
      .build();
    assertThat(StudioProfilers.buildDeviceName(deviceWithSerialInModel)).isEqualTo("Manufacturer Model");
  }

  @Test
  public void testSelectedAppNameFromSession() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess (phone)", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getSession()).isNotEqualTo(Common.Session.getDefaultInstance());
    assertThat(myProfilers.getSelectedAppName()).isEqualTo("FakeProcess");
  }

  @Test
  public void testSelectedAppNameFromProcessWhenNoSession() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    Common.Process process = createProcess(device.getDeviceId(), 20, "FakeProcess (phone)", Common.Process.State.ALIVE);
    myTransportService.addDevice(device);
    myTransportService.addProcess(device, process);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    myProfilers.setProcess(device, process);

    myProfilers.getSessionsManager().setSession(Common.Session.getDefaultInstance());
    assertThat(myProfilers.getSelectedAppName()).isEqualTo("FakeProcess");
  }

  @Test
  public void testSelectedAppNameWhenNoProcessAndNoSession() {
    Common.Device device = createDevice(AndroidVersion.VersionCodes.BASE, "FakeDevice", Common.Device.State.ONLINE);
    myTransportService.addDevice(device);
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getSession()).isEqualTo(Common.Session.getDefaultInstance());
    assertThat(myProfilers.getProcess()).isNull();
    assertThat(myProfilers.getSelectedAppName()).isEmpty();
  }

  @Test
  public void testSessionViewRangeCaches() {
    Common.Session finishedSession = Common.Session.newBuilder()
      .setSessionId(1).setStartTimestamp(FakeTimer.ONE_SECOND_IN_NS)
      .setEndTimestamp(FakeTimer.ONE_SECOND_IN_NS * 2).build();
    Common.SessionMetaData finishedSessionMetadata = Common.SessionMetaData.newBuilder()
      .setSessionId(1)
      .setType(Common.SessionMetaData.SessionType.FULL)
      .setStartTimestampEpochMs(1).build();
    Common.Session ongoingSession = Common.Session.newBuilder()
      .setSessionId(2).setStartTimestamp(0).setEndTimestamp(Long.MAX_VALUE).build();
    Common.SessionMetaData ongoingSessionMetadata = Common.SessionMetaData.newBuilder()
      .setSessionId(2).setType(Common.SessionMetaData.SessionType.FULL)
      .setStartTimestampEpochMs(2).build();
    if (myNewEventPipeline) {
      myTransportService.addSession(finishedSession, finishedSessionMetadata);
    }
    else {
      myProfilerService.addSession(finishedSession, finishedSessionMetadata);
    }
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    if (myNewEventPipeline) {
      myTransportService.addSession(ongoingSession, ongoingSessionMetadata);
    }
    else {
      myProfilerService.addSession(ongoingSession, ongoingSessionMetadata);
    }
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    // Arbitrary view range min/max to be set for each session
    long viewRangeMin = TimeUnit.MILLISECONDS.toMicros(1200);
    long viewRangeMax = TimeUnit.MILLISECONDS.toMicros(1600);

    // selecting an ongoing session should use the default zoom with streaming enabled
    myProfilers.getSessionsManager().setSession(myProfilers.getSessionsManager().getSessionArtifacts().get(0).getSession());
    assertThat(myProfilers.getTimeline().getViewRange().getMin()).isWithin(0).of(-StreamingTimeline.DEFAULT_VIEW_LENGTH_US);
    assertThat(myProfilers.getTimeline().getViewRange().getMax()).isWithin(0).of(0);
    assertThat(myProfilers.getTimeline().isStreaming()).isTrue();
    assertThat(myProfilers.getTimeline().isPaused()).isFalse();
    myProfilers.getTimeline().getViewRange().set(viewRangeMin, viewRangeMax);

    // selecting a finished session without a view range cache should use the entire data range
    myProfilers.getSessionsManager().setSession(myProfilers.getSessionsManager().getSessionArtifacts().get(1).getSession());
    assertThat(myProfilers.getTimeline().getViewRange().getMin()).isWithin(0).of(TimeUnit.SECONDS.toMicros(1));
    assertThat(myProfilers.getTimeline().getViewRange().getMax()).isWithin(0).of(TimeUnit.SECONDS.toMicros(2));
    assertThat(myProfilers.getTimeline().isStreaming()).isFalse();
    assertThat(myProfilers.getTimeline().isPaused()).isTrue();
    myProfilers.getTimeline().getViewRange().set(viewRangeMin, viewRangeMax);

    // Navigate back to the ongoing session should still use the default zoom
    myProfilers.getSessionsManager().setSession(myProfilers.getSessionsManager().getSessionArtifacts().get(0).getSession());
    assertThat(myProfilers.getTimeline().getViewRange().getMin()).isWithin(0).of(-StreamingTimeline.DEFAULT_VIEW_LENGTH_US);
    assertThat(myProfilers.getTimeline().getViewRange().getMax()).isWithin(0).of(0);
    assertThat(myProfilers.getTimeline().isStreaming()).isTrue();
    assertThat(myProfilers.getTimeline().isPaused()).isFalse();

    // Navigate again to the finished session should use the last view range
    myProfilers.getSessionsManager().setSession(myProfilers.getSessionsManager().getSessionArtifacts().get(1).getSession());
    assertThat(myProfilers.getTimeline().getViewRange().getMin()).isWithin(0).of(viewRangeMin);
    assertThat(myProfilers.getTimeline().getViewRange().getMax()).isWithin(0).of(viewRangeMax);
    assertThat(myProfilers.getTimeline().isStreaming()).isFalse();
    assertThat(myProfilers.getTimeline().isPaused()).isTrue();

    // Arbitrarily setting the view range to something beyond the data range should force the timeline to clamp to data range.
    myProfilers.getTimeline().getViewRange().set(TimeUnit.SECONDS.toMicros(-10), TimeUnit.SECONDS.toMicros(10));
    myProfilers.getSessionsManager().setSession(Common.Session.getDefaultInstance());
    myProfilers.getSessionsManager().setSession(myProfilers.getSessionsManager().getSessionArtifacts().get(1).getSession());
    assertThat(myProfilers.getTimeline().getViewRange().getMin()).isWithin(0).of(TimeUnit.SECONDS.toMicros(1));
    assertThat(myProfilers.getTimeline().getViewRange().getMax()).isWithin(0).of(TimeUnit.SECONDS.toMicros(2));
    assertThat(myProfilers.getTimeline().isStreaming()).isFalse();
    assertThat(myProfilers.getTimeline().isPaused()).isTrue();
  }

  @Test
  public void testMultipleUpdateTicksShouldNotChangeSession() {
    Common.Session finishedSession = Common.Session.newBuilder()
      .setSessionId(1).setStartTimestamp(FakeTimer.ONE_SECOND_IN_NS)
      .setEndTimestamp(FakeTimer.ONE_SECOND_IN_NS * 2).build();
    Common.SessionMetaData finishedSessionMetadata = Common.SessionMetaData.newBuilder()
      .setSessionId(1)
      .setType(Common.SessionMetaData.SessionType.FULL)
      .setStartTimestampEpochMs(1).build();
    Common.Session ongoingSession = Common.Session.newBuilder()
      .setSessionId(2).setStartTimestamp(0).setEndTimestamp(Long.MAX_VALUE).build();
    Common.SessionMetaData ongoingSessionMetadata = Common.SessionMetaData.newBuilder()
      .setSessionId(2).setType(Common.SessionMetaData.SessionType.FULL)
      .setStartTimestampEpochMs(2).build();
    if (myNewEventPipeline) {
      myTransportService.addSession(finishedSession, finishedSessionMetadata);
    }
    else {
      myProfilerService.addSession(finishedSession, finishedSessionMetadata);
    }
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    if (myNewEventPipeline) {
      myTransportService.addSession(ongoingSession, ongoingSessionMetadata);
    }
    else {
      myProfilerService.addSession(ongoingSession, ongoingSessionMetadata);
    }
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);

    myProfilers.getSessionsManager().setSession(myProfilers.getSessionsManager().getSessionArtifacts().get(0).getSession());
    assertThat(myProfilers.getSessionsManager().getSelectedSession().getSessionId()).isEqualTo(ongoingSession.getSessionId());
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getSessionsManager().getSelectedSession().getSessionId()).isEqualTo(ongoingSession.getSessionId());

    myProfilers.getSessionsManager().setSession(myProfilers.getSessionsManager().getSessionArtifacts().get(1).getSession());
    assertThat(myProfilers.getSessionsManager().getSelectedSession().getSessionId()).isEqualTo(finishedSession.getSessionId());
    myTimer.tick(FakeTimer.ONE_SECOND_IN_NS);
    assertThat(myProfilers.getSessionsManager().getSelectedSession().getSessionId()).isEqualTo(finishedSession.getSessionId());
  }

  @Test
  public void runAsyncResumesWithIntermediateValue() throws InterruptedException {
    int[] box = {0};
    CountDownLatch latch = new CountDownLatch(1);
    myIdeProfilerServices.runAsync(() -> 1 + 2,
                                   n -> {
                                     box[0] = n;
                                     latch.countDown();
                                   });
    assertThat(latch.await(1, TimeUnit.SECONDS)).isTrue();
    assertThat(box[0]).isEqualTo(3);
  }

  private static Common.Device createDevice(int featureLevel, @NotNull String serial, @NotNull Common.Device.State state) {
    return Common.Device.newBuilder()
      .setDeviceId(serial.hashCode())
      .setFeatureLevel(featureLevel)
      .setSerial(serial)
      .setState(state)
      .build();
  }

  private Common.Process createProcess(long deviceId, int pid, @NotNull String name, Common.Process.State state) {
    return Common.Process.newBuilder()
      .setDeviceId(deviceId)
      .setPid(pid)
      .setName(name)
      .setState(state)
      .setExposureLevel(Common.Process.ExposureLevel.DEBUGGABLE)
      .build();
  }

  private static class AgentStatusAspectObserver extends AspectObserver {
    private int myAgentStatusChangedCount;

    void AgentStatusChanged() {
      myAgentStatusChangedCount++;
    }

    int getAgentStatusChangedCount() {
      return myAgentStatusChangedCount;
    }
  }

  private static class FakeStage extends StreamingStage {
    private FakeStage(@NotNull StudioProfilers myProfilers) {
      super(myProfilers);
    }

    @Override
    public void enter() {
    }

    @Override
    public void exit() {
    }

    @Override
    public AndroidProfilerEvent.Stage getStageType() {
      return AndroidProfilerEvent.Stage.UNKNOWN_STAGE;
    }
  }
}