File: test_commands.py

package info (click to toggle)
python-click 6.6-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 1,068 kB
  • sloc: python: 6,964; makefile: 124
file content (255 lines) | stat: -rw-r--r-- 7,114 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
# -*- coding: utf-8 -*-
import re
import click


def test_other_command_invoke(runner):
    @click.command()
    @click.pass_context
    def cli(ctx):
        return ctx.invoke(other_cmd, arg=42)

    @click.command()
    @click.argument('arg', type=click.INT)
    def other_cmd(arg):
        click.echo(arg)

    result = runner.invoke(cli, [])
    assert not result.exception
    assert result.output == '42\n'


def test_other_command_forward(runner):
    cli = click.Group()

    @cli.command()
    @click.option('--count', default=1)
    def test(count):
        click.echo('Count: %d' % count)

    @cli.command()
    @click.option('--count', default=1)
    @click.pass_context
    def dist(ctx, count):
        ctx.forward(test)
        ctx.invoke(test, count=42)

    result = runner.invoke(cli, ['dist'])
    assert not result.exception
    assert result.output == 'Count: 1\nCount: 42\n'


def test_auto_shorthelp(runner):
    @click.group()
    def cli():
        pass

    @cli.command()
    def short():
        """This is a short text."""

    @cli.command()
    def special_chars():
        """Login and store the token in ~/.netrc."""

    @cli.command()
    def long():
        """This is a long text that is too long to show as short help
        and will be truncated instead."""

    result = runner.invoke(cli, ['--help'])
    assert re.search(
        r'Commands:\n\s+'
        r'long\s+This is a long text that is too long to show\.\.\.\n\s+'
        r'short\s+This is a short text\.\n\s+'
        r'special_chars\s+Login and store the token in ~/.netrc\.\s*',
        result.output) is not None


def test_default_maps(runner):
    @click.group()
    def cli():
        pass

    @cli.command()
    @click.option('--name', default='normal')
    def foo(name):
        click.echo(name)

    result = runner.invoke(cli, ['foo'], default_map={
        'foo': {'name': 'changed'}
    })

    assert not result.exception
    assert result.output == 'changed\n'


def test_group_with_args(runner):
    @click.group()
    @click.argument('obj')
    def cli(obj):
        click.echo('obj=%s' % obj)

    @cli.command()
    def move():
        click.echo('move')

    result = runner.invoke(cli, [])
    assert result.exit_code == 0
    assert 'Show this message and exit.' in result.output

    result = runner.invoke(cli, ['obj1'])
    assert result.exit_code == 2
    assert 'Error: Missing command.' in result.output

    result = runner.invoke(cli, ['obj1', '--help'])
    assert result.exit_code == 0
    assert 'Show this message and exit.' in result.output

    result = runner.invoke(cli, ['obj1', 'move'])
    assert result.exit_code == 0
    assert result.output == 'obj=obj1\nmove\n'


def test_base_command(runner):
    import optparse

    @click.group()
    def cli():
        pass

    class OptParseCommand(click.BaseCommand):

        def __init__(self, name, parser, callback):
            click.BaseCommand.__init__(self, name)
            self.parser = parser
            self.callback = callback

        def parse_args(self, ctx, args):
            try:
                opts, args = parser.parse_args(args)
            except Exception as e:
                ctx.fail(str(e))
            ctx.args = args
            ctx.params = vars(opts)

        def get_usage(self, ctx):
            return self.parser.get_usage()

        def get_help(self, ctx):
            return self.parser.format_help()

        def invoke(self, ctx):
            ctx.invoke(self.callback, ctx.args, **ctx.params)

    parser = optparse.OptionParser(usage='Usage: foo test [OPTIONS]')
    parser.add_option("-f", "--file", dest="filename",
                      help="write report to FILE", metavar="FILE")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="don't print status messages to stdout")

    def test_callback(args, filename, verbose):
        click.echo(' '.join(args))
        click.echo(filename)
        click.echo(verbose)
    cli.add_command(OptParseCommand('test', parser, test_callback))

    result = runner.invoke(cli, ['test', '-f', 'test.txt', '-q',
                                 'whatever.txt', 'whateverelse.txt'])
    assert not result.exception
    assert result.output.splitlines() == [
        'whatever.txt whateverelse.txt',
        'test.txt',
        'False',
    ]

    result = runner.invoke(cli, ['test', '--help'])
    assert not result.exception
    assert result.output.splitlines() == [
        'Usage: foo test [OPTIONS]',
        '',
        'Options:',
        '  -h, --help            show this help message and exit',
        '  -f FILE, --file=FILE  write report to FILE',
        '  -q, --quiet           don\'t print status messages to stdout',
    ]


def test_object_propagation(runner):
    for chain in False, True:
        @click.group(chain=chain)
        @click.option('--debug/--no-debug', default=False)
        @click.pass_context
        def cli(ctx, debug):
            if ctx.obj is None:
                ctx.obj = {}
            ctx.obj['DEBUG'] = debug

        @cli.command()
        @click.pass_context
        def sync(ctx):
            click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))

        result = runner.invoke(cli, ['sync'])
        assert result.exception is None
        assert result.output == 'Debug is off\n'


def test_other_command_invoke_with_defaults(runner):
    @click.command()
    @click.pass_context
    def cli(ctx):
        return ctx.invoke(other_cmd)

    @click.command()
    @click.option('--foo', type=click.INT, default=42)
    @click.pass_context
    def other_cmd(ctx, foo):
        assert ctx.info_name == 'other_cmd'
        click.echo(foo)

    result = runner.invoke(cli, [])
    assert not result.exception
    assert result.output == '42\n'


def test_invoked_subcommand(runner):
    @click.group(invoke_without_command=True)
    @click.pass_context
    def cli(ctx):
        if ctx.invoked_subcommand is None:
            click.echo('no subcommand, use default')
            ctx.invoke(sync)
        else:
            click.echo('invoke subcommand')

    @cli.command()
    def sync():
        click.echo('in subcommand')

    result = runner.invoke(cli, ['sync'])
    assert not result.exception
    assert result.output == 'invoke subcommand\nin subcommand\n'

    result = runner.invoke(cli)
    assert not result.exception
    assert result.output == 'no subcommand, use default\nin subcommand\n'


def test_unprocessed_options(runner):
    @click.command(context_settings=dict(
        ignore_unknown_options=True
    ))
    @click.argument('args', nargs=-1, type=click.UNPROCESSED)
    @click.option('--verbose', '-v', count=True)
    def cli(verbose, args):
        click.echo('Verbosity: %s' % verbose)
        click.echo('Args: %s' % '|'.join(args))

    result = runner.invoke(cli, ['-foo', '-vvvvx', '--muhaha', 'x', 'y', '-x'])
    assert not result.exception
    assert result.output.splitlines() == [
        'Verbosity: 4',
        'Args: -foo|-x|--muhaha|x|y|-x',
    ]