File: test_cmdline.py

package info (click to toggle)
python-briefcase 0.3.22-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,300 kB
  • sloc: python: 59,405; makefile: 57
file content (659 lines) | stat: -rw-r--r-- 21,973 bytes parent folder | download | duplicates (2)
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
import shlex
import sys
from unittest import mock

import pytest

from briefcase import __version__, cmdline
from briefcase.commands import ConvertCommand, DevCommand, NewCommand, UpgradeCommand
from briefcase.console import Console, LogLevel
from briefcase.exceptions import (
    InvalidFormatError,
    InvalidPlatformError,
    NoCommandError,
    UnsupportedCommandError,
)
from briefcase.platforms.linux.system import LinuxSystemCreateCommand
from briefcase.platforms.macOS.app import (
    macOSAppCreateCommand,
    macOSAppPublishCommand,
    macOSAppRunCommand,
)
from briefcase.platforms.windows.app import WindowsAppCreateCommand


@pytest.fixture
def console() -> Console:
    return Console()


def do_cmdline_parse(args: list, console: Console):
    """Simulate process to parse command line."""
    Command, extra_cmdline = cmdline.parse_cmdline(args)
    cmd = Command(console=console)
    options, overrides = cmd.parse_options(extra=extra_cmdline)
    return cmd, options, overrides


def test_empty():
    """``briefcase`` returns basic usage."""
    with pytest.raises(NoCommandError, match=r"usage: briefcase") as excinfo:
        cmdline.parse_cmdline("".split())

    assert excinfo.value.msg.startswith(
        "usage: briefcase [-h] <command> [<platform>] [<format>] ...\n"
        "\n"
        "Briefcase is a tool for converting a Python project into a standalone native\n"
        "application for distribution.\n"
        "\n"
        "Commands:\n"
    )


def test_help_only():
    """``briefcase -h`` returns basic usage."""
    with pytest.raises(NoCommandError, match=r"usage: briefcase") as excinfo:
        cmdline.parse_cmdline("-h".split())

    assert excinfo.value.msg.startswith(
        "usage: briefcase [-h] <command> [<platform>] [<format>] ...\n"
        "\n"
        "Briefcase is a tool for converting a Python project into a standalone native\n"
        "application for distribution.\n"
        "\n"
        "Commands:\n"
    )


def test_version_only(capsys):
    """``briefcase -V`` returns current version."""
    with pytest.raises(SystemExit) as excinfo:
        cmdline.parse_cmdline("-V".split())

    # Normal exit due to displaying help
    assert excinfo.value.code == 0
    # Version is displayed.
    output = capsys.readouterr().out
    assert output == f"{__version__}\n"


def test_unknown_command():
    """``briefcase foobar`` fails as an invalid command."""
    with pytest.raises(SystemExit) as excinfo:
        cmdline.parse_cmdline("foobar".split())

    assert excinfo.value.code == 2
    assert excinfo.value.__context__.argument_name == "command"
    assert excinfo.value.__context__.message.startswith(
        "invalid choice: 'foobar' (choose from"
    )


@pytest.mark.parametrize(
    "cmdline, expected_options, expected_overrides",
    [
        (
            "new",
            {
                "template": None,
                "template_branch": None,
                "project_overrides": None,
            },
            {},
        ),
        (
            "new --template=path/to/template --template-branch=experiment -C version=\\'1.2.3\\' -C other=42",
            {
                "template": "path/to/template",
                "template_branch": "experiment",
                "project_overrides": None,
            },
            {
                "version": "1.2.3",
                "other": 42,
            },
        ),
    ],
)
def test_new_command(console, cmdline, expected_options, expected_overrides):
    """``briefcase new`` returns the New command."""
    cmd, options, overrides = do_cmdline_parse(shlex.split(cmdline), console)

    assert isinstance(cmd, NewCommand)
    assert cmd.platform == "all"
    assert cmd.output_format is None
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == expected_options
    assert overrides == expected_overrides


@pytest.mark.parametrize(
    "cmdline, expected_options, expected_overrides",
    [
        (
            "convert",
            {
                "template": None,
                "template_branch": None,
                "project_overrides": None,
            },
            {},
        ),
        (
            "convert --template=path/to/template --template-branch=experiment -C version=\\'1.2.3\\' -C other=42",
            {
                "template": "path/to/template",
                "template_branch": "experiment",
                "project_overrides": None,
            },
            {
                "version": "1.2.3",
                "other": 42,
            },
        ),
    ],
)
def test_convert_command(console, cmdline, expected_options, expected_overrides):
    """``briefcase convert`` returns the Convert command."""
    cmd, options, overrides = do_cmdline_parse(shlex.split(cmdline), console)

    assert isinstance(cmd, ConvertCommand)
    assert cmd.platform == "all"
    assert cmd.output_format is None
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == expected_options
    assert overrides == expected_overrides


# Common tests for dev and run commands.
def dev_run_parameters(command):
    return [
        (f"{command} {args}", expected, overrides)
        for args, expected, overrides in [
            ("", {}, {}),
            ("-r", {"update_requirements": True}, {}),
            (
                "-r -C version=\\'1.2.3\\' -C other=42",
                {"update_requirements": True},
                {
                    "version": "1.2.3",
                    "other": 42,
                },
            ),
            ("--update-requirements", {"update_requirements": True}, {}),
            ("--test", {"test_mode": True}, {}),
            ("--test -r", {"test_mode": True, "update_requirements": True}, {}),
            ("--", {}, {}),
            ("-- ''", {"passthrough": [""]}, {}),
            ("-- --test", {"passthrough": ["--test"]}, {}),
            ("--test -- --test", {"test_mode": True, "passthrough": ["--test"]}, {}),
            ("--test -- -r", {"test_mode": True, "passthrough": ["-r"]}, {}),
            (
                "-r -- --test",
                {"update_requirements": True, "passthrough": ["--test"]},
                {},
            ),
            ("-- -y --no maybe", {"passthrough": ["-y", "--no", "maybe"]}, {}),
            (
                "--test -- -y --no maybe",
                {"test_mode": True, "passthrough": ["-y", "--no", "maybe"]},
                {},
            ),
        ]
    ]


@pytest.mark.parametrize(
    "cmdline, expected_options, expected_overrides",
    dev_run_parameters("dev")
    + [
        ("dev --no-run", {"run_app": False}, {}),
    ],
)
def test_dev_command(
    monkeypatch,
    console,
    cmdline,
    expected_options,
    expected_overrides,
):
    """``briefcase dev`` returns the Dev command."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    cmd, options, overrides = do_cmdline_parse(shlex.split(cmdline), console)

    assert isinstance(cmd, DevCommand)
    assert cmd.platform == "macOS"
    assert cmd.output_format is None
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {
        "appname": None,
        "update_requirements": False,
        "run_app": True,
        "test_mode": False,
        "passthrough": [],
        **expected_options,
    }
    assert overrides == expected_overrides


@pytest.mark.parametrize(
    "cmdline, expected_options, expected_overrides",
    dev_run_parameters("run")
    + [
        ("run -u", {"update": True}, {}),
        ("run --update", {"update": True}, {}),
        ("run --update-resources", {"update_resources": True}, {}),
        ("run --update-support", {"update_support": True}, {}),
        ("run --update-stub", {"update_stub": True}, {}),
        ("run --no-update", {"no_update": True}, {}),
    ],
)
def test_run_command(
    monkeypatch,
    console,
    cmdline,
    expected_options,
    expected_overrides,
):
    """``briefcase run`` returns the Run command for the correct platform."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    cmd, options, overrides = do_cmdline_parse(shlex.split(cmdline), console)

    assert isinstance(cmd, macOSAppRunCommand)
    assert cmd.platform == "macOS"
    assert cmd.output_format == "app"
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {
        "appname": None,
        "update": False,
        "update_requirements": False,
        "update_resources": False,
        "update_support": False,
        "update_stub": False,
        "no_update": False,
        "test_mode": False,
        "passthrough": [],
        **expected_options,
    }
    assert overrides == expected_overrides


@pytest.mark.parametrize(
    "cmdline,expected_options,expected_overrides",
    [
        (
            "upgrade",
            {
                "list_tools": False,
                "tool_list": [],
            },
            {},
        ),
        (
            "upgrade -C version='1.2.3' -C other=42",
            {
                "list_tools": False,
                "tool_list": [],
            },
            {
                "version": "1.2.3",
                "other": 42,
            },
        ),
    ],
)
def test_upgrade_command(
    monkeypatch,
    console,
    cmdline,
    expected_options,
    expected_overrides,
):
    """``briefcase upgrade`` returns the upgrade command."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    cmd, options, overrides = do_cmdline_parse(cmdline.split(), console)

    assert isinstance(cmd, UpgradeCommand)
    assert cmd.platform == "macOS"
    assert cmd.output_format is None
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == expected_options
    assert overrides == expected_overrides


def test_bare_command(monkeypatch, console):
    """``briefcase create`` returns the macOS create app command."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    cmd, options, overrides = do_cmdline_parse("create".split(), console)

    assert isinstance(cmd, macOSAppCreateCommand)
    assert cmd.platform == "macOS"
    assert cmd.output_format == "app"
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {}
    assert overrides == {}


@pytest.mark.skipif(sys.platform != "linux", reason="requires Linux")
def test_linux_default(console):
    """``briefcase create`` returns the linux create system command on Linux."""

    cmd, options, overrides = do_cmdline_parse("create".split(), console)

    assert isinstance(cmd, LinuxSystemCreateCommand)
    assert cmd.platform == "linux"
    assert cmd.output_format == "system"
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {}


@pytest.mark.skipif(sys.platform != "darwin", reason="requires macOS")
def test_macOS_default(console):
    """``briefcase create`` returns the macOS create command on Linux."""

    cmd, options, overrides = do_cmdline_parse("create".split(), console)

    assert isinstance(cmd, macOSAppCreateCommand)
    assert cmd.platform == "macOS"
    assert cmd.output_format == "app"
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {}
    assert overrides == {}


@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows")
def test_windows_default(console):
    """``briefcase create`` returns the Windows create app command on Windows."""

    cmd, options, overrides = do_cmdline_parse("create".split(), console)

    assert isinstance(cmd, WindowsAppCreateCommand)
    assert cmd.platform == "windows"
    assert cmd.output_format == "app"
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {}
    assert overrides == {}


def test_bare_command_help(monkeypatch, capsys, console):
    """``briefcase create -h`` returns the macOS create app command help."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    with pytest.raises(SystemExit) as excinfo:
        do_cmdline_parse("create -h".split(), console)

    # Normal exit due to displaying help
    assert excinfo.value.code == 0

    output = capsys.readouterr().out
    # Help message is for default platform and format
    expected_output = """\
usage: briefcase create macOS app [-h] [-C KEY=VALUE] [-v] [-V] [--no-input]
                                  [--log]

Create and populate a macOS app.
"""
    assert expected_output in output


def test_bare_command_version(capsys, console):
    """``briefcase create -V`` returns the version."""
    with pytest.raises(SystemExit) as excinfo:
        do_cmdline_parse("create -V".split(), console)

    # Normal exit due to displaying help
    assert excinfo.value.code == 0
    # Version is displayed.
    output = capsys.readouterr().out
    assert output == f"{__version__}\n"


def test_command_unknown_platform(monkeypatch, console):
    """``briefcase create foobar`` raises an unknown platform error."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    expected_exc_regex = r"Invalid platform 'foobar'; \(choose from: .*\)"
    with pytest.raises(InvalidPlatformError, match=expected_exc_regex):
        do_cmdline_parse("create foobar".split(), console)


def test_command_explicit_platform(monkeypatch, console):
    """``briefcase create linux`` returns linux create app command."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    cmd, options, overrides = do_cmdline_parse("create linux".split(), console)

    assert isinstance(cmd, LinuxSystemCreateCommand)
    assert cmd.platform == "linux"
    assert cmd.output_format == "system"
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {}
    assert overrides == {}


def test_command_explicit_platform_case_handling(monkeypatch, console):
    """``briefcase create macOS`` returns macOS create app command."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    # This is all lower case; the command normalizes to macOS
    cmd, options, overrides = do_cmdline_parse("create macOS".split(), console)

    assert isinstance(cmd, macOSAppCreateCommand)
    assert cmd.platform == "macOS"
    assert cmd.output_format == "app"
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {}
    assert overrides == {}


def test_command_explicit_platform_help(monkeypatch, capsys, console):
    """``briefcase create macOS -h`` returns the macOS create app command help."""
    import sys

    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    with pytest.raises(SystemExit) as excinfo:
        do_cmdline_parse("create macOS -h".split(), console)

    # Normal exit due to displaying help
    assert excinfo.value.code == 0

    output = capsys.readouterr().out.strip()
    output = "\n".join([line for line in output.splitlines() if not line.startswith("** WARNING")])

    # Help message is for default platform and format
    expected_output_start = """\
usage: briefcase create macOS app [-h] [-C KEY=VALUE] [-v] [-V] [--no-input]
                                  [--log]

Create and populate a macOS app.

Supported formats:
  app (default), Xcode
"""
    assert output.startswith(expected_output_start)


def test_command_explicit_format(monkeypatch, console):
    """``briefcase create macOS app`` returns the macOS create app command."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    cmd, options, overrides = do_cmdline_parse("create macOS app".split(), console)

    assert isinstance(cmd, macOSAppCreateCommand)
    assert cmd.platform == "macOS"
    assert cmd.output_format == "app"
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {}
    assert overrides == {}


def test_command_unknown_format(monkeypatch, console):
    """``briefcase create macOS foobar`` returns an invalid format error."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    expected_exc_regex = r"Invalid format 'foobar'; \(choose from: app, Xcode\)"
    with pytest.raises(InvalidFormatError, match=expected_exc_regex):
        do_cmdline_parse("create macOS foobar".split(), console)


def test_command_explicit_unsupported_format(monkeypatch, console):
    """``briefcase create macOS homebrew`` raises an error because the format isn't
    supported (yet)"""
    # Mock the output formats to include a "homebrew" backend with no commands.
    monkeypatch.setattr(
        cmdline,
        "get_output_formats",
        mock.MagicMock(return_value={"homebrew": None}),
    )

    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    with pytest.raises(
        UnsupportedCommandError,
        match=r"The create command for the macOS homebrew format has not been implemented \(yet!\).",
    ):
        do_cmdline_parse("create macOS homebrew".split(), console)


def test_command_explicit_format_help(monkeypatch, capsys, console):
    """``briefcase create macOS app -h`` returns the macOS create app help."""

    monkeypatch.setattr(sys, "platform", "darwin")

    with pytest.raises(SystemExit) as excinfo:
        do_cmdline_parse("create macOS app -h".split(), console)

    assert excinfo.value.code == 0

    output = capsys.readouterr().out

    expected_output_with_warning = """\
*************************************************************************
** WARNING: Default system encoding is not supported                   **
*************************************************************************

usage: briefcase create macOS app [-h] [-C KEY=VALUE] [-v] [-V] [--no-input]
                                  [--log]

Create and populate a macOS app.

Supported formats:
  app (default), Xcode
"""

    expected_output_without_warning = """\
usage: briefcase create macOS app [-h] [-C KEY=VALUE] [-v] [-V] [--no-input]
                                  [--log]

Create and populate a macOS app.

Supported formats:
  app (default), Xcode
"""

    assert output.startswith(expected_output_with_warning) or output.startswith(expected_output_without_warning)

def test_command_disable_input(monkeypatch, console):
    """``briefcase create --no-input`` disables console input."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    cmd, options, overrides = do_cmdline_parse("create --no-input".split(), console)

    assert isinstance(cmd, macOSAppCreateCommand)
    assert cmd.platform == "macOS"
    assert cmd.output_format == "app"
    assert not cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {}
    assert overrides == {}


def test_command_options(monkeypatch, capsys, console):
    """Commands can provide their own arguments."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    # Invoke a command that is known to have its own custom arguments
    # (In this case, the channel argument for publication)
    cmd, options, overrides = do_cmdline_parse(
        "publish macos app -c s3".split(), console
    )

    assert isinstance(cmd, macOSAppPublishCommand)
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {"channel": "s3"}
    assert overrides == {}


def test_command_overrides(monkeypatch, capsys, console):
    """Configuration overrides can be specified."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    # Invoke a command that is known to have its own custom arguments
    # (In this case, the channel argument for publication)
    cmd, options, overrides = do_cmdline_parse(
        "publish macos app -C version='1.2.3' -C extra=42".split(),
        console,
    )

    assert isinstance(cmd, macOSAppPublishCommand)
    assert cmd.console.input_enabled
    assert cmd.console.verbosity == LogLevel.INFO
    assert options == {"channel": "s3"}
    assert overrides == {
        "version": "1.2.3",
        "extra": 42,
    }


def test_unknown_command_options(monkeypatch, capsys, console):
    """Commands can provide their own arguments."""
    # Pretend we're on macOS, regardless of where the tests run.
    monkeypatch.setattr(sys, "platform", "darwin")

    # Invoke a command but provide an option. that isn't defined
    with pytest.raises(SystemExit) as excinfo:
        do_cmdline_parse("publish macOS xcode -x foobar".split(), console)

    # Normal exit due to displaying help
    assert excinfo.value.code == 2
    # Help message is for default platform and format
    output = capsys.readouterr().err

    assert output.startswith(
        "usage: briefcase publish macOS Xcode [-h] [-C KEY=VALUE] [-v] [-V]\n"
        "                                     [--no-input] [--log] [-c {s3}]\n"
        "briefcase publish macOS Xcode: error: unrecognized arguments: -x"
    )