File: test_common.py

package info (click to toggle)
python-questionary 2.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 960 kB
  • sloc: python: 3,917; makefile: 66
file content (273 lines) | stat: -rw-r--r-- 7,817 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
import asyncio
from unittest.mock import Mock
from unittest.mock import call

import pytest
from prompt_toolkit.document import Document
from prompt_toolkit.input.defaults import create_pipe_input
from prompt_toolkit.output import DummyOutput
from prompt_toolkit.styles import Attrs
from prompt_toolkit.validation import ValidationError
from prompt_toolkit.validation import Validator

from questionary import Choice
from questionary.prompts import common
from questionary.prompts.common import InquirerControl
from questionary.prompts.common import build_validator
from questionary.prompts.common import print_formatted_text
from tests.utils import prompt_toolkit_version


def test_to_many_choices_for_shortcut_assignment():
    ic = InquirerControl([str(i) for i in range(1, 100)], use_shortcuts=True)

    # IC should fail gracefully when running out of shortcuts
    assert len(list(filter(lambda x: x.shortcut_key is not None, ic.choices))) == len(
        InquirerControl.SHORTCUT_KEYS
    )


def test_validator_bool_function():
    def validate(t):
        return len(t) == 3

    validator = build_validator(validate)
    assert validator.validate(Document("foo")) is None  # should not raise


def test_validator_bool_function_fails():
    def validate(t):
        return len(t) == 3

    validator = build_validator(validate)
    with pytest.raises(ValidationError) as e:
        validator.validate(Document("fooooo"))

    assert e.value.message == "Invalid input"


def test_validator_instance():
    def validate(t):
        return len(t) == 3

    validator = Validator.from_callable(validate)

    validator = build_validator(validator)
    assert validator.validate(Document("foo")) is None  # should not raise


def test_validator_instance_fails():
    def validate(t):
        return len(t) == 3

    validator = Validator.from_callable(validate, error_message="invalid input")
    with pytest.raises(ValidationError) as e:
        validator.validate(Document("fooooo"))

    assert e.value.message == "invalid input"


def test_blank_line_fix():
    def get_prompt_tokens():
        return [("class:question", "What is your favourite letter?")]

    ic = InquirerControl(["a", "b", "c"])

    async def run(inp):
        inp.send_text("")
        layout = common.create_inquirer_layout(
            ic, get_prompt_tokens, input=inp, output=DummyOutput()
        )

        # usually this would be 2000000000000000000000000000000
        # but `common._fix_unecessary_blank_lines` makes sure
        # the main window is not as greedy (avoiding blank lines)
        assert (
            layout.container.preferred_height(100, 200).max
            == 1000000000000000000000000000001
        )

    if prompt_toolkit_version < (3, 0, 29):
        inp = create_pipe_input()
        try:
            return asyncio.run(run(inp))
        finally:
            inp.close()
    else:
        with create_pipe_input() as inp:
            asyncio.run(run(inp))


def test_prompt_highlight_coexist():
    ic = InquirerControl(["a", "b", "c"])

    expected_tokens = [
        ("class:pointer", " » "),
        ("[SetCursorPosition]", ""),
        ("class:text", "○ "),
        ("class:highlighted", "a"),
        ("", "\n"),
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "b"),
        ("", "\n"),
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "c"),
    ]
    assert ic.pointed_at == 0
    assert ic._get_choice_tokens() == expected_tokens

    ic.select_previous()
    expected_tokens = [
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "a"),
        ("", "\n"),
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "b"),
        ("", "\n"),
        ("class:pointer", " » "),
        ("[SetCursorPosition]", ""),
        ("class:text", "○ "),
        ("class:highlighted", "c"),
    ]
    assert ic.pointed_at == 2
    assert ic._get_choice_tokens() == expected_tokens


def test_prompt_show_answer_with_shortcuts():
    ic = InquirerControl(
        ["a", Choice("b", shortcut_key=False), "c"],
        show_selected=True,
        use_shortcuts=True,
    )

    expected_tokens = [
        ("class:pointer", " » "),
        ("[SetCursorPosition]", ""),
        ("class:text", "○ "),
        ("class:highlighted", "1) a"),
        ("", "\n"),
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "-) b"),
        ("", "\n"),
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "2) c"),
        ("", "\n"),
        ("class:text", "  Answer: 1) a"),
    ]
    assert ic.pointed_at == 0
    assert ic._get_choice_tokens() == expected_tokens

    ic.select_next()
    expected_tokens = [
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "1) a"),
        ("", "\n"),
        ("class:pointer", " » "),
        ("[SetCursorPosition]", ""),
        ("class:text", "○ "),
        ("class:highlighted", "-) b"),
        ("", "\n"),
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "2) c"),
        ("", "\n"),
        ("class:text", "  Answer: -) b"),
    ]
    assert ic.pointed_at == 1
    assert ic._get_choice_tokens() == expected_tokens


def test_print(monkeypatch):
    mock = Mock(return_value=None)
    monkeypatch.setattr(DummyOutput, "write", mock)

    print_formatted_text("Hello World", output=DummyOutput())

    mock.assert_has_calls([call("Hello World"), call("\r\n")])


def test_print_with_style(monkeypatch):
    mock = Mock(return_value=None)
    monkeypatch.setattr(DummyOutput, "write", mock.write)
    monkeypatch.setattr(DummyOutput, "set_attributes", mock.set_attributes)

    print_formatted_text(
        "Hello World", style="bold italic fg:darkred", output=DummyOutput()
    )

    assert len(mock.method_calls) == 4
    assert mock.method_calls[0][0] == "set_attributes"

    if prompt_toolkit_version < (3, 0, 20):
        assert mock.method_calls[0][1][0] == Attrs(
            color="8b0000",
            bgcolor="",
            bold=True,
            underline=False,
            italic=True,
            blink=False,
            reverse=False,
            hidden=False,
        )
    else:
        assert mock.method_calls[0][1][0] == Attrs(
            color="8b0000",
            bgcolor="",
            bold=True,
            underline=False,
            italic=True,
            blink=False,
            reverse=False,
            hidden=False,
            strike=False,
        )

    assert mock.method_calls[1][0] == "write"
    assert mock.method_calls[1][1][0] == "Hello World"


def test_prompt_show_description():
    ic = InquirerControl(
        ["a", Choice("b", description="B")],
        show_selected=True,
        show_description=True,
    )

    expected_tokens = [
        ("class:pointer", " » "),
        ("[SetCursorPosition]", ""),
        ("class:text", "○ "),
        ("class:highlighted", "a"),
        ("", "\n"),
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "b"),
        ("", "\n"),
        ("class:text", "  Answer: a"),
    ]
    assert ic.pointed_at == 0
    assert ic._get_choice_tokens() == expected_tokens

    ic.select_next()
    expected_tokens = [
        ("class:text", "   "),
        ("class:text", "○ "),
        ("class:text", "a"),
        ("", "\n"),
        ("class:pointer", " » "),
        ("[SetCursorPosition]", ""),
        ("class:text", "○ "),
        ("class:highlighted", "b"),
        ("", "\n"),
        ("class:text", "  Answer: b"),
        ("class:text", "  Description: B"),
    ]
    assert ic.pointed_at == 1
    assert ic._get_choice_tokens() == expected_tokens