File: test_run.py

package info (click to toggle)
python-briefcase 0.3.25-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,596 kB
  • sloc: python: 62,519; makefile: 60
file content (871 lines) | stat: -rw-r--r-- 29,539 bytes parent folder | download
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
import datetime
import os
import platform
import sys
import time
from pathlib import Path
from unittest import mock

import httpx
import pytest

from briefcase.exceptions import BriefcaseCommandError
from briefcase.integrations.android_sdk import ADB, AndroidSDK
from briefcase.integrations.java import JDK
from briefcase.integrations.subprocess import Subprocess
from briefcase.platforms.android.gradle import (
    GradleRunCommand,
    android_log_clean_filter,
)

from ....utils import create_file


@pytest.fixture
def jdk():
    jdk = mock.MagicMock()
    jdk.java_home = Path("/path/to/java")
    return jdk


@pytest.fixture
def run_command(dummy_console, tmp_path, first_app_config, jdk):
    command = GradleRunCommand(
        console=dummy_console,
        base_path=tmp_path / "base_path",
        data_path=tmp_path / "briefcase",
    )
    command.tools.mock_adb = mock.MagicMock(spec_set=ADB)
    command.tools.mock_adb.pidof = mock.MagicMock(return_value="777")
    command.tools.java = mock.MagicMock(spec=JDK)
    command.tools.java.java_home = "/path/to/java"
    command.tools.android_sdk = AndroidSDK(
        command.tools,
        root_path=Path("/path/to/android_sdk"),
    )
    command.tools.android_sdk.adb = mock.MagicMock(return_value=command.tools.mock_adb)

    command.tools.os = mock.MagicMock(spec_set=os)
    command.tools.os.environ = {}
    command.tools.httpx = mock.MagicMock(spec_set=httpx)
    command.tools.subprocess = mock.MagicMock(spec_set=Subprocess)
    command.tools.sys = mock.MagicMock(spec_set=sys)

    command._stream_app_logs = mock.MagicMock()

    command.base_path.mkdir(parents=True)
    return command


def test_binary_path(run_command, first_app_config, tmp_path):
    assert (
        run_command.binary_path(first_app_config)
        == tmp_path
        / "base_path"
        / "build"
        / "first-app"
        / "android"
        / "gradle"
        / "app"
        / "build"
        / "outputs"
        / "apk"
        / "debug"
        / "app-debug.apk"
    )


def test_device_option(run_command):
    """The -d option can be parsed."""
    options, overrides = run_command.parse_options(["-d", "myphone"])

    assert options == {
        "device_or_avd": "myphone",
        "appname": None,
        "update": False,
        "update_requirements": False,
        "update_resources": False,
        "update_support": False,
        "update_stub": False,
        "no_update": False,
        "test_mode": False,
        "passthrough": [],
        "extra_emulator_args": None,
        "shutdown_on_exit": False,
        "forward_ports": None,
        "reverse_ports": None,
    }
    assert overrides == {}


def test_extra_emulator_args_option(run_command):
    """The -d option can be parsed."""
    options, overrides = run_command.parse_options(
        ["--Xemulator=-no-window", "--Xemulator=-no-audio"]
    )

    assert options == {
        "device_or_avd": None,
        "appname": None,
        "update": False,
        "update_requirements": False,
        "update_resources": False,
        "update_support": False,
        "update_stub": False,
        "no_update": False,
        "test_mode": False,
        "passthrough": [],
        "extra_emulator_args": ["-no-window", "-no-audio"],
        "shutdown_on_exit": False,
        "forward_ports": None,
        "reverse_ports": None,
    }
    assert overrides == {}


def test_shutdown_on_exit_option(run_command):
    """The -d option can be parsed."""
    options, overrides = run_command.parse_options(["--shutdown-on-exit"])

    assert options == {
        "device_or_avd": None,
        "appname": None,
        "update": False,
        "update_requirements": False,
        "update_resources": False,
        "update_support": False,
        "update_stub": False,
        "no_update": False,
        "test_mode": False,
        "passthrough": [],
        "extra_emulator_args": None,
        "shutdown_on_exit": True,
        "forward_ports": None,
        "reverse_ports": None,
    }
    assert overrides == {}


def test_forward_ports_option(run_command):
    """The --forward-port option can be parsed."""
    options, overrides = run_command.parse_options(
        ["--forward-port", "80", "--forward-port", "81"]
    )

    assert options == {
        "device_or_avd": None,
        "appname": None,
        "update": False,
        "update_requirements": False,
        "update_resources": False,
        "update_support": False,
        "update_stub": False,
        "no_update": False,
        "test_mode": False,
        "passthrough": [],
        "extra_emulator_args": None,
        "shutdown_on_exit": False,
        "forward_ports": [80, 81],
        "reverse_ports": None,
    }
    assert overrides == {}


def test_reverse_ports_option(run_command):
    """The --reverse-port option can be parsed."""
    options, overrides = run_command.parse_options(
        ["--reverse-port", "78", "--reverse-port", "79"]
    )

    assert options == {
        "device_or_avd": None,
        "appname": None,
        "update": False,
        "update_requirements": False,
        "update_resources": False,
        "update_support": False,
        "update_stub": False,
        "no_update": False,
        "test_mode": False,
        "passthrough": [],
        "extra_emulator_args": None,
        "shutdown_on_exit": False,
        "forward_ports": None,
        "reverse_ports": [78, 79],
    }
    assert overrides == {}


def test_unsupported_template_version(run_command, first_app_generated):
    """Error raised if template's target version is not supported."""
    run_command.apps = {"first-app": first_app_generated}

    # Skip verifying tools
    run_command.verify_tools = mock.MagicMock()

    # Mock the build command previously called
    create_file(run_command.binary_path(first_app_generated), content="")

    run_command.verify_app = mock.MagicMock(wraps=run_command.verify_app)

    run_command._briefcase_toml.update(
        {first_app_generated: {"briefcase": {"target_epoch": "0.3.16"}}}
    )

    with pytest.raises(
        BriefcaseCommandError,
        match="The app template used to generate this app is not compatible",
    ):
        run_command(first_app_generated.app_name)

    run_command.verify_app.assert_called_once_with(first_app_generated)


def test_run_existing_device(run_command, first_app_config):
    """An app can be run on an existing device."""
    # Set up device selection to return a running physical device.
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=("exampleDevice", "ExampleDevice", None)
    )

    # Set up the log streamer to return a known stream
    log_popen = mock.MagicMock()
    run_command.tools.mock_adb.logcat.return_value = log_popen

    # To satisfy coverage, the stop function must be invoked at least once
    # when invoking stream_output.
    def mock_stream_output(app, stop_func, **kwargs):
        stop_func()

    run_command._stream_app_logs.side_effect = mock_stream_output

    # Set up app config to have a `-` in the `bundle`, to ensure it gets
    # normalized into a `_` via `package_name`.
    first_app_config.bundle = "com.ex-ample"

    # Invoke run_app
    run_command.run_app(
        first_app_config,
        device_or_avd="exampleDevice",
        passthrough=[],
    )

    # select_target_device was invoked with a specific device
    run_command.tools.android_sdk.select_target_device.assert_called_once_with(
        "exampleDevice"
    )

    # The ADB wrapper is created
    run_command.tools.android_sdk.adb.assert_called_once_with(device="exampleDevice")

    # The adb wrapper is invoked with the expected arguments
    run_command.tools.mock_adb.install_apk.assert_called_once_with(
        run_command.binary_path(first_app_config)
    )
    run_command.tools.mock_adb.force_stop_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
    )

    run_command.tools.mock_adb.forward.assert_not_called()
    run_command.tools.mock_adb.reverse.assert_not_called()

    run_command.tools.mock_adb.start_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        "org.beeware.android.MainActivity",
        [],
    )

    run_command.tools.mock_adb.forward_remove.assert_not_called()
    run_command.tools.mock_adb.reverse_remove.assert_not_called()

    run_command.tools.mock_adb.pidof.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        quiet=2,
    )
    run_command.tools.mock_adb.logcat.assert_called_once_with(pid="777")

    run_command._stream_app_logs.assert_called_once_with(
        first_app_config,
        popen=log_popen,
        clean_filter=android_log_clean_filter,
        clean_output=False,
        stop_func=mock.ANY,
        log_stream=True,
    )

    # The emulator was not killed at the end of the test
    run_command.tools.mock_adb.kill.assert_not_called()


def test_run_with_passthrough(run_command, first_app_config):
    """An app can be run with passthrough args."""
    # Set up device selection to return a running physical device.
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=("exampleDevice", "ExampleDevice", None)
    )

    # Set up the log streamer to return a known stream
    log_popen = mock.MagicMock()
    run_command.tools.mock_adb.logcat.return_value = log_popen

    # To satisfy coverage, the stop function must be invoked at least once
    # when invoking stream_output.
    def mock_stream_output(app, stop_func, **kwargs):
        stop_func()

    run_command._stream_app_logs.side_effect = mock_stream_output

    # Set up app config to have a `-` in the `bundle`, to ensure it gets
    # normalized into a `_` via `package_name`.
    first_app_config.bundle = "com.ex-ample"

    # Invoke run_app with args.
    run_command.run_app(
        first_app_config,
        device_or_avd="exampleDevice",
        passthrough=["foo", "--bar"],
    )

    # select_target_device was invoked with a specific device
    run_command.tools.android_sdk.select_target_device.assert_called_once_with(
        "exampleDevice"
    )

    # The ADB wrapper is created
    run_command.tools.android_sdk.adb.assert_called_once_with(device="exampleDevice")

    # The adb wrapper is invoked with the expected arguments
    run_command.tools.mock_adb.install_apk.assert_called_once_with(
        run_command.binary_path(first_app_config)
    )
    run_command.tools.mock_adb.force_stop_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
    )

    run_command.tools.mock_adb.start_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        "org.beeware.android.MainActivity",
        ["foo", "--bar"],
    )

    run_command.tools.mock_adb.pidof.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        quiet=2,
    )
    run_command.tools.mock_adb.logcat.assert_called_once_with(pid="777")

    run_command._stream_app_logs.assert_called_once_with(
        first_app_config,
        popen=log_popen,
        clean_filter=android_log_clean_filter,
        clean_output=False,
        stop_func=mock.ANY,
        log_stream=True,
    )

    # The emulator was not killed at the end of the test
    run_command.tools.mock_adb.kill.assert_not_called()


def test_run_forward_reverse_ports(run_command, first_app_config):
    """An app can be run with port forwarding and reversing."""
    # Set up device selection to return a running physical device.
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=("exampleDevice", "ExampleDevice", None)
    )

    # Invoke run_app with args.
    run_command.run_app(
        first_app_config,
        passthrough=[],
        forward_ports=[80, 81],
        reverse_ports=[78, 79],
    )

    assert run_command.tools.mock_adb.forward.mock_calls == [
        mock.call(80, 80),
        mock.call(81, 81),
    ]
    assert run_command.tools.mock_adb.reverse.mock_calls == [
        mock.call(78, 78),
        mock.call(79, 79),
    ]

    run_command.tools.mock_adb.start_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        "org.beeware.android.MainActivity",
        [],
    )

    assert run_command.tools.mock_adb.forward_remove.mock_calls == [
        mock.call(80),
        mock.call(81),
    ]
    assert run_command.tools.mock_adb.reverse_remove.mock_calls == [
        mock.call(78),
        mock.call(79),
    ]


def test_run_slow_start(run_command, first_app_config, monkeypatch):
    """If the app is slow to start, multiple calls to pidof will be made."""
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=("exampleDevice", "ExampleDevice", None)
    )

    # Set up the log streamer to return a known stream
    log_popen = mock.MagicMock()
    run_command.tools.mock_adb.logcat.return_value = log_popen

    # Mock the pidof call taking 3 attempts to return
    run_command.tools.mock_adb.pidof.side_effect = [None, None, "888"]
    monkeypatch.setattr(time, "sleep", mock.MagicMock())

    run_command.run_app(
        first_app_config,
        device_or_avd="exampleDevice",
        passthrough=[],
    )

    assert (
        run_command.tools.mock_adb.pidof.mock_calls
        == [mock.call("com.example.first_app", quiet=2)] * 3
    )
    assert time.sleep.mock_calls == [mock.call(0.01)] * 2
    run_command.tools.mock_adb.logcat.assert_called_once_with(pid="888")

    run_command._stream_app_logs.assert_called_once_with(
        first_app_config,
        popen=log_popen,
        clean_filter=android_log_clean_filter,
        clean_output=False,
        stop_func=mock.ANY,
        log_stream=True,
    )


def test_run_crash_at_start(run_command, first_app_config, monkeypatch):
    """If the app crashes before a PID can be read, a log dump is shown."""
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=("exampleDevice", "ExampleDevice", None)
    )

    # Mock the pidof call failing multiple times before a timeout.
    run_command.tools.mock_adb.pidof.side_effect = [None] * 5
    monkeypatch.setattr(time, "sleep", mock.MagicMock())

    # It's the eternal september...
    device_start_datetime = datetime.datetime(2022, 9, 9, 7, 6, 42)
    pid_lookup_start_datetime = datetime.datetime(2022, 9, 8, 7, 6, 42)

    # Mock time progression so PID lookup loops 5 times
    mock_datetime = mock.MagicMock(spec=datetime.datetime)
    # Mock datetime.now() at +0s, +0.5s, +1.5s,... +5.5s
    mock_datetime.now.side_effect = [
        pid_lookup_start_datetime + datetime.timedelta(seconds=delay)
        for delay in [0] + [x + 0.5 for x in range(0, 6)]
    ]
    monkeypatch.setattr(datetime, "datetime", mock_datetime)

    # Mock the device start datetime
    run_command.tools.mock_adb.datetime.return_value = device_start_datetime

    with pytest.raises(
        BriefcaseCommandError, match=r"Problem starting app 'first-app'"
    ):
        run_command.run_app(
            first_app_config,
            device_or_avd="exampleDevice",
            passthrough=[],
        )

    assert (
        run_command.tools.mock_adb.pidof.mock_calls
        == [mock.call("com.example.first_app", quiet=2)] * 5
    )
    assert time.sleep.mock_calls == [mock.call(0.01)] * 5

    # The PID was never found, so logs can't be streamed
    run_command.tools.mock_adb.logcat.assert_not_called()

    # But we will get a log dump from logcat_tail
    run_command.tools.mock_adb.logcat_tail.assert_called_once_with(
        since=device_start_datetime
    )


def test_run_created_emulator(run_command, first_app_config):
    """The user can choose to run on a newly created emulator."""
    # Set up device selection to return a completely new emulator
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=(None, None, None)
    )
    run_command.tools.android_sdk.create_emulator = mock.MagicMock(
        return_value="newDevice"
    )
    run_command.tools.android_sdk.verify_avd = mock.MagicMock()
    run_command.tools.android_sdk.start_emulator = mock.MagicMock(
        return_value=("emulator-3742", "New Device")
    )

    # Set up the log streamer to return a known stream
    log_popen = mock.MagicMock()
    run_command.tools.mock_adb.logcat.return_value = log_popen

    # Invoke run_app
    run_command.run_app(first_app_config, passthrough=[])

    # A new emulator was created
    run_command.tools.android_sdk.create_emulator.assert_called_once_with()

    # No attempt was made to verify the AVD (it is pre-verified through
    # the creation process)
    run_command.tools.android_sdk.verify_avd.assert_not_called()

    # The emulator was started
    run_command.tools.android_sdk.start_emulator.assert_called_once_with(
        "newDevice", None
    )

    # The ADB wrapper is created
    run_command.tools.android_sdk.adb.assert_called_once_with(device="emulator-3742")

    # The adb wrapper is invoked with the expected arguments
    run_command.tools.mock_adb.install_apk.assert_called_once_with(
        run_command.binary_path(first_app_config)
    )
    run_command.tools.mock_adb.force_stop_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
    )

    run_command.tools.mock_adb.start_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        "org.beeware.android.MainActivity",
        [],
    )

    run_command.tools.mock_adb.logcat.assert_called_once_with(pid="777")

    run_command._stream_app_logs.assert_called_once_with(
        first_app_config,
        popen=log_popen,
        clean_filter=android_log_clean_filter,
        clean_output=False,
        stop_func=mock.ANY,
        log_stream=True,
    )


def test_run_idle_device(run_command, first_app_config):
    """The user can choose to run on an idle device."""
    # Set up device selection to return a new device that has an AVD,
    # but not a device ID.
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=(None, "Idle Device", "idleDevice")
    )

    run_command.tools.android_sdk.create_emulator = mock.MagicMock()
    run_command.tools.android_sdk.verify_avd = mock.MagicMock()
    run_command.tools.android_sdk.start_emulator = mock.MagicMock(
        return_value=("emulator-3742", "Idle Device")
    )

    # Set up the log streamer to return a known stream
    log_popen = mock.MagicMock()
    run_command.tools.mock_adb.logcat.return_value = log_popen

    # Invoke run_app
    run_command.run_app(first_app_config, passthrough=[])

    # No attempt was made to create a new emulator
    run_command.tools.android_sdk.create_emulator.assert_not_called()

    # The AVD has been verified
    run_command.tools.android_sdk.verify_avd.assert_called_with("idleDevice")

    # The emulator was started
    run_command.tools.android_sdk.start_emulator.assert_called_once_with(
        "idleDevice", None
    )

    # The ADB wrapper is created
    run_command.tools.android_sdk.adb.assert_called_once_with(device="emulator-3742")

    # The adb wrapper is invoked with the expected arguments
    run_command.tools.mock_adb.install_apk.assert_called_once_with(
        run_command.binary_path(first_app_config)
    )
    run_command.tools.mock_adb.force_stop_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
    )

    run_command.tools.mock_adb.start_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        "org.beeware.android.MainActivity",
        [],
    )

    run_command.tools.mock_adb.logcat.assert_called_once_with(pid="777")

    run_command._stream_app_logs.assert_called_once_with(
        first_app_config,
        popen=log_popen,
        clean_filter=android_log_clean_filter,
        clean_output=False,
        stop_func=mock.ANY,
        log_stream=True,
    )


def test_log_file_extra(run_command, monkeypatch):
    """Android commands register a log file extra to list SDK packages."""
    mock_android_sdk_verify = mock.MagicMock(return_value=run_command.tools.android_sdk)
    monkeypatch.setattr(AndroidSDK, "verify", mock_android_sdk_verify)
    monkeypatch.setattr(AndroidSDK, "verify_emulator", mock.MagicMock())

    # Even if one command triggers another, the sdkmanager should only be run once.
    run_command.update_command.verify_tools()
    run_command.verify_tools()

    # Android SDK tool was verified
    mock_android_sdk_verify.assert_has_calls([mock.call(tools=run_command.tools)] * 2)
    assert isinstance(run_command.tools.android_sdk, AndroidSDK)

    # list_packages() was not called
    run_command.tools.subprocess.check_output.assert_not_called()

    # list_packages() is called when saving the log
    run_command.tools.console.save_log = True
    run_command.tools.console.save_log_to_file(run_command)

    sdk_manager = Path(
        f"/path/to/android_sdk/cmdline-tools/{AndroidSDK.SDK_MANAGER_VER}"
        f"/bin/sdkmanager{'.bat' if platform.system() == 'Windows' else ''}"
    )
    run_command.tools.subprocess.check_output.assert_called_once_with(
        [sdk_manager, "--list_installed"],
        env={
            "ANDROID_HOME": str(run_command.tools.android_sdk.root_path),
            "ANDROID_SDK_ROOT": str(run_command.tools.android_sdk.root_path),
            "JAVA_HOME": str(run_command.tools.java.java_home),
        },
    )


def test_run_test_mode(run_command, first_app_config):
    """An app can be run in test mode."""
    first_app_config.test_mode = True

    # Set up device selection to return a running physical device.
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=("exampleDevice", "ExampleDevice", None)
    )

    # Set up the log streamer to return a known stream
    log_popen = mock.MagicMock()
    run_command.tools.mock_adb.logcat.return_value = log_popen

    # To satisfy coverage, the stop function must be invoked at least once
    # when invoking stream_output.
    def mock_stream_output(app, stop_func, **kwargs):
        stop_func()

    run_command._stream_app_logs.side_effect = mock_stream_output

    # Set up app config to have a `-` in the `bundle`, to ensure it gets
    # normalized into a `_` via `package_name`.
    first_app_config.bundle = "com.ex-ample"

    # Invoke run_app
    run_command.run_app(
        first_app_config,
        device_or_avd="exampleDevice",
        passthrough=[],
        shutdown_on_exit=True,
    )

    # select_target_device was invoked with a specific device
    run_command.tools.android_sdk.select_target_device.assert_called_once_with(
        "exampleDevice"
    )

    # The ADB wrapper is created
    run_command.tools.android_sdk.adb.assert_called_once_with(device="exampleDevice")

    # The adb wrapper is invoked with the expected arguments
    run_command.tools.mock_adb.install_apk.assert_called_once_with(
        run_command.binary_path(first_app_config)
    )
    run_command.tools.mock_adb.force_stop_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
    )

    run_command.tools.mock_adb.start_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        "org.beeware.android.MainActivity",
        [],
    )

    run_command.tools.mock_adb.pidof.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        quiet=2,
    )
    run_command.tools.mock_adb.logcat.assert_called_once_with(pid="777")

    run_command._stream_app_logs.assert_called_once_with(
        first_app_config,
        popen=log_popen,
        clean_filter=android_log_clean_filter,
        clean_output=False,
        stop_func=mock.ANY,
        log_stream=True,
    )

    # The emulator was killed at the end of the test
    run_command.tools.mock_adb.kill.assert_called_once_with()


def test_run_test_mode_with_passthrough(run_command, first_app_config):
    """An app can be run in test mode with passthrough args."""
    first_app_config.test_mode = True

    # Set up device selection to return a running physical device.
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=("exampleDevice", "ExampleDevice", None)
    )

    # Set up the log streamer to return a known stream
    log_popen = mock.MagicMock()
    run_command.tools.mock_adb.logcat.return_value = log_popen

    # To satisfy coverage, the stop function must be invoked at least once
    # when invoking stream_output.
    def mock_stream_output(app, stop_func, **kwargs):
        stop_func()

    run_command._stream_app_logs.side_effect = mock_stream_output

    # Set up app config to have a `-` in the `bundle`, to ensure it gets
    # normalized into a `_` via `package_name`.
    first_app_config.bundle = "com.ex-ample"

    # Invoke run_app in test mode with args.
    run_command.run_app(
        first_app_config,
        device_or_avd="exampleDevice",
        passthrough=["foo", "--bar"],
        shutdown_on_exit=True,
    )

    # select_target_device was invoked with a specific device
    run_command.tools.android_sdk.select_target_device.assert_called_once_with(
        "exampleDevice"
    )

    # The ADB wrapper is created
    run_command.tools.android_sdk.adb.assert_called_once_with(device="exampleDevice")

    # The adb wrapper is invoked with the expected arguments
    run_command.tools.mock_adb.install_apk.assert_called_once_with(
        run_command.binary_path(first_app_config)
    )
    run_command.tools.mock_adb.force_stop_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
    )

    run_command.tools.mock_adb.start_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        "org.beeware.android.MainActivity",
        ["foo", "--bar"],
    )

    run_command.tools.mock_adb.pidof.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        quiet=2,
    )
    run_command.tools.mock_adb.logcat.assert_called_once_with(pid="777")

    run_command._stream_app_logs.assert_called_once_with(
        first_app_config,
        popen=log_popen,
        clean_filter=android_log_clean_filter,
        clean_output=False,
        stop_func=mock.ANY,
        log_stream=True,
    )

    # The emulator was killed at the end of the test
    run_command.tools.mock_adb.kill.assert_called_once_with()


def test_run_test_mode_created_emulator(run_command, first_app_config):
    """The user can choose to run in test mode on a newly created emulator."""
    first_app_config.test_mode = True

    # Set up device selection to return a completely new emulator
    run_command.tools.android_sdk.select_target_device = mock.MagicMock(
        return_value=(None, None, None)
    )
    run_command.tools.android_sdk.create_emulator = mock.MagicMock(
        return_value="newDevice"
    )
    run_command.tools.android_sdk.verify_avd = mock.MagicMock()
    run_command.tools.android_sdk.start_emulator = mock.MagicMock(
        return_value=("emulator-3742", "New Device")
    )

    # Set up the log streamer to return a known stream
    log_popen = mock.MagicMock()
    run_command.tools.mock_adb.logcat.return_value = log_popen

    # Invoke run_app
    run_command.run_app(
        first_app_config,
        passthrough=[],
        extra_emulator_args=["-no-window", "-no-audio"],
        shutdown_on_exit=True,
    )

    # A new emulator was created
    run_command.tools.android_sdk.create_emulator.assert_called_once_with()

    # No attempt was made to verify the AVD (it is pre-verified through
    # the creation process)
    run_command.tools.android_sdk.verify_avd.assert_not_called()

    # The emulator was started
    run_command.tools.android_sdk.start_emulator.assert_called_once_with(
        "newDevice",
        ["-no-window", "-no-audio"],
    )

    # The ADB wrapper is created
    run_command.tools.android_sdk.adb.assert_called_once_with(device="emulator-3742")

    # The adb wrapper is invoked with the expected arguments
    run_command.tools.mock_adb.install_apk.assert_called_once_with(
        run_command.binary_path(first_app_config)
    )
    run_command.tools.mock_adb.force_stop_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
    )

    run_command.tools.mock_adb.start_app.assert_called_once_with(
        f"{first_app_config.package_name}.{first_app_config.module_name}",
        "org.beeware.android.MainActivity",
        [],
    )

    run_command.tools.mock_adb.logcat.assert_called_once_with(pid="777")

    run_command._stream_app_logs.assert_called_once_with(
        first_app_config,
        popen=log_popen,
        clean_filter=android_log_clean_filter,
        clean_output=False,
        stop_func=mock.ANY,
        log_stream=True,
    )

    # The emulator was killed at the end of the test
    run_command.tools.mock_adb.kill.assert_called_once_with()