summaryrefslogtreecommitdiff
path: root/tests/test_autocompletion.py
blob: 30cb5dad34d524581d77e889dac15781edf2543e (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
# coding=utf-8
# flake8: noqa E302
"""
Unit/functional testing for argparse completer in cmd2
"""
import argparse
from typing import List

import pytest

import cmd2
from cmd2 import with_argparser
from cmd2.argparse_custom import Cmd2ArgParser
from cmd2.utils import StdSim
from .conftest import run_cmd, complete_tester

# Lists used in our tests
static_choices_list = ['static', 'choices']
choices_from_function = ['choices', 'function']
choices_from_method = ['choices', 'method']


def choices_function() -> List[str]:
    """Function that provides choices"""
    return choices_from_function


class AutoCompleteTester(cmd2.Cmd):
    """Cmd2 app that exercises AutoCompleter class"""
    def __init__(self):
        super().__init__()

    def choices_method(self) -> List[str]:
        """Method that provides choices"""
        return choices_from_method

    # Basic command with no subcommands that exercises tab completing choices from various sources
    basic_parser = Cmd2ArgParser()
    basic_parser.add_argument("-n", "--no_choices", help="a flag with no choices")
    basic_parser.add_argument("-l", "--choices_list", help="a flag populated with a choices list",
                              choices=static_choices_list)
    basic_parser.add_argument("-f", "--choices_function", help="a flag populated with a choices function",
                              choices_function=choices_function)
    basic_parser.add_argument("-m", "--choices_method", help="a flag populated with a choices method",
                              choices_method=choices_method)

    basic_parser.add_argument("no_choice_pos", help="a positional with no choices")
    basic_parser.add_argument("choices_list_pos", help="a positional populated with a choices list",
                              choices=static_choices_list)
    basic_parser.add_argument("choices_function_pos", help="a positional populated with a choices function",
                              choices_function=choices_function)
    basic_parser.add_argument("choices_method_pos", help="a positional populated with a choices method",
                              choices_method=choices_method)

    @with_argparser(basic_parser)
    def do_basic(self, args: argparse.Namespace) -> None:
        pass


@pytest.fixture
def ac_app():
    app = AutoCompleteTester()
    app.stdout = StdSim(app.stdout)
    return app


def test_help_basic(ac_app):
    out1, err1 = run_cmd(ac_app, 'basic -h')
    out2, err2 = run_cmd(ac_app, 'help basic')
    assert out1 == out2


def test_autocomp_flags(ac_app):
    text = '-'
    line = 'basic {}'.format(text)
    endidx = len(line)
    begidx = endidx - len(text)

    first_match = complete_tester(text, line, begidx, endidx, ac_app)
    assert first_match is not None and \
           ac_app.completion_matches == ['--choices_function', '--choices_list', '--choices_method', '--help',
                                         '--no_choices', '-f', '-h', '-l', '-m', '-n']


def test_autcomp_hint(ac_app, capsys):
    text = ''
    line = 'basic -n {}'.format(text)
    endidx = len(line)
    begidx = endidx - len(text)

    first_match = complete_tester(text, line, begidx, endidx, ac_app)
    out, err = capsys.readouterr()

    assert first_match is None
    assert 'a flag with no choices' in out


def test_autcomp_flag_comp(ac_app):
    text = '--ch'
    line = 'basic {}'.format(text)
    endidx = len(line)
    begidx = endidx - len(text)

    first_match = complete_tester(text, line, begidx, endidx, ac_app)
    assert first_match is not None and \
           ac_app.completion_matches == ['--choices_function', '--choices_list', '--choices_method']


@pytest.mark.parametrize('flag, completions', [
    ('-l', static_choices_list),
    ('--choices_list', static_choices_list),
    ('-f', choices_from_function),
    ('--choices_function', choices_from_function),
    ('-m', choices_from_method),
    ('--choices_method', choices_from_method),
])
def test_autocomp_flags_choices(ac_app, flag, completions):
    text = ''
    line = 'basic {} {}'.format(flag, text)
    endidx = len(line)
    begidx = endidx - len(text)

    first_match = complete_tester(text, line, begidx, endidx, ac_app)
    assert first_match is not None and \
           ac_app.completion_matches == sorted(completions, key=ac_app.matches_sort_key)


# def test_autcomp_hint_in_narg_range(cmd2_app, capsys):
#     text = ''
#     line = 'suggest -d 2 {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
#     out, err = capsys.readouterr()
#
#     assert out == '''
# Hint:
#   -d, --duration DURATION    Duration constraint in minutes.
#                              	single value - maximum duration
#                              	[a, b] - duration range
#
# '''
#
# def test_autocomp_flags_narg_max(cmd2_app):
#     text = ''
#     line = 'suggest d 2 3 {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
#     assert first_match is None
#
#
# def test_autcomp_narg_beyond_max(cmd2_app):
#     out, err = run_cmd(cmd2_app, 'suggest -t movie -d 3 4 5')
#     assert 'Error: unrecognized arguments: 5' in err[1]
#
#
# def test_autocomp_subcmd_flag_comp_func_attr(cmd2_app):
#     text = 'A'
#     line = 'video movies list -a "{}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
#     assert first_match is not None and \
#            cmd2_app.completion_matches == ['Adam Driver', 'Alec Guinness', 'Andy Serkis', 'Anthony Daniels']
#
#
# def test_autocomp_subcmd_flag_comp_list_attr(cmd2_app):
#     text = 'G'
#     line = 'video movies list -d {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
#     assert first_match is not None and first_match == '"Gareth Edwards'
#
#
# def test_autocomp_pos_consumed(cmd2_app):
#     text = ''
#     line = 'library movie add SW_EP01 {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
#     assert first_match is None
#
#
# def test_autocomp_pos_after_flag(cmd2_app):
#     text = 'Joh'
#     line = 'video movies add -d "George Lucas" -- "Han Solo" PG "Emilia Clarke" "{}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
#     assert first_match is not None and \
#            cmd2_app.completion_matches == ['John Boyega" ']
#
#
# def test_autocomp_custom_func_dict_arg(cmd2_app):
#     text = '/home/user/'
#     line = 'video movies load {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
#     assert first_match is not None and \
#            cmd2_app.completion_matches == ['/home/user/another.db', '/home/user/file space.db', '/home/user/file.db']
#
#
# def test_argparse_remainder_flag_completion(cmd2_app):
#     import cmd2
#     import argparse
#
#     # Test flag completion as first arg of positional with nargs=argparse.REMAINDER
#     text = '--h'
#     line = 'help command {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     # --h should not complete into --help because we are in the argparse.REMAINDER section
#     assert complete_tester(text, line, begidx, endidx, cmd2_app) is None
#
#     # Test flag completion within an already started positional with nargs=argparse.REMAINDER
#     text = '--h'
#     line = 'help command subcommand {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     # --h should not complete into --help because we are in the argparse.REMAINDER section
#     assert complete_tester(text, line, begidx, endidx, cmd2_app) is None
#
#     # Test a flag with nargs=argparse.REMAINDER
#     parser = argparse.ArgumentParser()
#     parser.add_argument('-f', nargs=argparse.REMAINDER)
#
#     # Overwrite eof's parser for this test
#     cmd2.Cmd.do_eof.argparser = parser
#
#     text = '--h'
#     line = 'eof -f {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     # --h should not complete into --help because we are in the argparse.REMAINDER section
#     assert complete_tester(text, line, begidx, endidx, cmd2_app) is None
#
#
# def test_completion_after_double_dash(cmd2_app):
#     """
#     Test completion after --, which argparse says (all args after -- are non-options)
#     All of these tests occur outside of an argparse.REMAINDER section since those tests
#     are handled in test_argparse_remainder_flag_completion
#     """
#
#     # Test -- as the last token
#     text = '--'
#     line = 'help {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     # Since -- is the last token, then it should show flag choices
#     first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
#     assert first_match is not None and '--help' in cmd2_app.completion_matches
#
#     # Test -- to end all flag completion
#     text = '--'
#     line = 'help -- {}'.format(text)
#     endidx = len(line)
#     begidx = endidx - len(text)
#
#     # Since -- appeared before the -- being completed, nothing should be completed
#     assert complete_tester(text, line, begidx, endidx, cmd2_app) is None