vpac / src / prompt_test.v
512 lines · 476 sloc · 16.22 KB · 3609dfbd82867dc1034a443f8f9ced529ddbbedd
Raw
1module main
2
3import json2
4import os
5
6#include <stdio_ext.h>
7#include <fcntl.h>
8
9fn C.__fpurge(stream &C.FILE)
10
11fn C.clearerr(stream &C.FILE)
12
13// Scripted is a second frontend's prompter in miniature: it answers every
14// question the same, and keeps what it was asked
15struct Scripted {
16mut:
17 noconfirm bool
18 yes bool
19 asked []string
20}
21
22fn (mut p Scripted) confirm(msg string, _ bool) bool {
23 p.asked << msg
24 return p.yes
25}
26
27fn (mut p Scripted) proceed(msg string) bool {
28 p.asked << msg
29 return p.yes
30}
31
32fn (mut p Scripted) choose(msg string, choices []string) int {
33 p.asked << msg
34 return choices.len - 1
35}
36
37fn (mut p Scripted) pick(msg string, count int) []bool {
38 p.asked << msg
39 return []bool{len: count, init: p.yes}
40}
41
42fn test_parse_selection_as_pacman() ! {
43 // the first word selecting starts from nothing; ranges and commas
44 assert parse_selection('2 4', 5)! == [false, true, false, true, false]
45 assert parse_selection('1-3,5', 5)! == [true, true, true, false, true]
46 // a first word leaving out starts from everything
47 assert parse_selection('^2', 3)! == [true, false, true]
48 assert parse_selection('^1-2', 3)! == [false, false, true]
49 // later words add to or take from what stands
50 assert parse_selection('1-4 ^3', 4)! == [true, true, false, true]
51 for bad in ['0', '6', 'x', '3-2', '2-9', '1-'] {
52 if _ := parse_selection(bad, 5) {
53 assert false, '"${bad}" was taken'
54 }
55 }
56}
57
58fn test_select_answer_is_a_list_of_indices() ! {
59 assert parse_select_answer('{"id": 3, "answer": [0, 2]}', 3, 3)! == [true, false, true]
60 assert parse_select_answer('{"id": 3, "answer": []}', 3, 3)! == [false, false, false]
61 for bad in ['{"id": 3, "answer": true}', '{"id": 3, "answer": [3]}', '{"id": 3, "answer": [0.5]}',
62 '{"id": 2, "answer": [0]}', 'noise'] {
63 if _ := parse_select_answer(bad, 3, 3) {
64 assert false, '${bad} was taken'
65 }
66 }
67}
68
69fn test_noconfirm_takes_the_defaults() {
70 // the questions go to stderr; stdin is never read, so none of these blocks
71 mut ui := new_trans_ui(noconfirm: true)
72 assert ui.yesno('a?')
73 assert !ui.noyes('b?')
74 assert ui.proceed('proceed?')
75 assert ui.choose('which one?', ['a', 'b', 'c']) == 0
76 assert ui.pick('which ones?', 3) == [true, true, true]
77}
78
79fn test_policy_through_the_interface() {
80 mut ui := new_trans_ui()
81 assert !ui.prompt.noconfirm
82 // a mode may flip the policy for one listing, through the interface,
83 // whichever prompter is behind it
84 ui.prompt.noconfirm = true
85 assert ui.proceed('proceed?')
86}
87
88fn test_every_prompt_reaches_the_prompter() ! {
89 mut ui := new_trans_ui()
90 ui.prompt = Scripted{
91 yes: true
92 }
93 assert did_you_mean(mut ui, 'zshh', ['zsh', 'bash'])! == 'zsh'
94 assert ui.choose('which one?', ['a', 'b', 'c']) == 2
95 assert ui.proceed('proceed?')
96 // nothing near the query: the error comes without a question
97 if _ := did_you_mean(mut ui, 'qqqqqq', ['zsh']) {
98 assert false
99 }
100 s := ui.prompt as Scripted
101 assert s.asked.len == 3
102 assert s.asked[1..] == ['which one?', 'proceed?']
103
104 ui.prompt = Scripted{
105 yes: false
106 }
107 if _ := did_you_mean(mut ui, 'zshh', ['zsh']) {
108 assert false
109 }
110}
111
112// StdinSource is what a scripted stdin reads: the text given, a stdin that
113// is closed, or a directory, which every read fails on
114enum StdinSource {
115 text
116 closed
117 directory
118}
119
120// Scripted run is what on_stdin hands back: the answers the prompts gave,
121// what they wrote to stderr, and the ipc channel's lines
122struct ScriptedRun {
123 answers []int
124 stderr string
125 channel []string
126}
127
128// reset_stdin drops what stdio buffered of the stdin before, and its end of
129// file mark, so one script's leftovers never reach the next
130fn reset_stdin() {
131 C.__fpurge(C.stdin)
132 C.clearerr(C.stdin)
133}
134
135// on_stdin runs ask with fd 0 reading from source, fd 2 and the ipc channel
136// each written to a file, then puts all three back. it is the real stdin
137// that is read, through stdio as the prompters read it, so what the libc
138// and the line reader make of an end or a failure is what is tested
139fn on_stdin(source StdinSource, text string, ask fn () []int) !ScriptedRun {
140 dir := os.join_path(os.vtmp_dir(), 'vpac_test_prompt_${os.getpid()}')
141 os.mkdir_all(dir)!
142 defer { os.rmdir_all(dir) or {} }
143 os.write_file(os.join_path(dir, 'stdin'), text)!
144 mut in_file := os.open(os.join_path(dir, 'stdin'))!
145 defer { in_file.close() }
146 mut err_file := os.create(os.join_path(dir, 'stderr'))!
147 mut chan_file := os.create(os.join_path(dir, 'channel'))!
148 defer {
149 err_file.close()
150 chan_file.close()
151 }
152 dir_fd := C.open(&char(dir.str), C.O_RDONLY)
153 saved_in := C.dup(0)
154 saved_err := C.dup(2)
155 // whatever was opened is closed again on every way out, the failed
156 // setup's included: a descriptor left behind would be the next
157 // script's stdin by number
158 defer {
159 for fd in [dir_fd, saved_in, saved_err] {
160 if fd >= 0 {
161 C.close(fd)
162 }
163 }
164 }
165 if dir_fd < 0 || saved_in < 0 || saved_err < 0 {
166 return error('could not set the scripted stdin up')
167 }
168 saved_ipc := ipc_fd
169 reset_stdin()
170 // dup2 answers the new descriptor, never 0, on success
171 wired_in := match source {
172 .text { C.dup2(in_file.fd, 0) >= 0 }
173 .closed { C.close(0) == 0 }
174 .directory { C.dup2(dir_fd, 0) >= 0 }
175 }
176 wired_err := C.dup2(err_file.fd, 2) >= 0
177 mut answers := []int{}
178 if wired_in && wired_err {
179 ipc_fd = chan_file.fd
180 answers = ask()
181 ipc_fd = saved_ipc
182 }
183 // the real stdin and stderr come back whether or not the script ran
184 back_in := C.dup2(saved_in, 0) >= 0
185 back_err := C.dup2(saved_err, 2) >= 0
186 reset_stdin()
187 if !wired_in || !wired_err {
188 return error('could not point stdin or stderr at the script')
189 }
190 if !back_in || !back_err {
191 return error('could not put stdin or stderr back after the script')
192 }
193 err_file.flush()
194 chan_file.flush()
195 return ScriptedRun{
196 answers: answers
197 stderr: os.read_file(os.join_path(dir, 'stderr'))!
198 channel: os.read_lines(os.join_path(dir, 'channel'))!
199 }
200}
201
202fn yn(b bool) int {
203 return if b { 1 } else { 0 }
204}
205
206// confirm_both asks one question on the script with a yes preset, and the
207// same on the same script with a no preset
208fn confirm_both(text string) ![]int {
209 yes := on_stdin(.text, text, fn () []int {
210 mut p := TermPrompter{}
211 return [yn(p.confirm('a?', true))]
212 })!
213 no := on_stdin(.text, text, fn () []int {
214 mut p := TermPrompter{}
215 return [yn(p.confirm('a?', false))]
216 })!
217 return [yes.answers[0], no.answers[0]]
218}
219
220fn test_term_confirm_reads_the_answer_on_stdin() ! {
221 // [with a yes preset, with a no preset], as pacman's question() answers
222 for text, want in {
223 // end of input is no, whatever the preset
224 '': [0, 0]
225 // an empty answer, blanks or not, takes the preset
226 '\n': [1, 0]
227 ' \t \n': [1, 0]
228 'y\n': [1, 1]
229 'Y\n': [1, 1]
230 'yes\n': [1, 1]
231 ' YeS \n': [1, 1]
232 'n\n': [0, 0]
233 'no\n': [0, 0]
234 // anything else is no, even with a yes preset
235 'maybe\n': [0, 0]
236 'yess\n': [0, 0]
237 // a last line without its newline is an answer, as fgets reads it
238 'y': [1, 1]
239 'n': [0, 0]
240 } {
241 assert confirm_both(text)! == want, 'stdin ${text}'
242 }
243}
244
245fn test_term_confirm_unreadable_stdin_is_no() ! {
246 // a closed stdin, or one that is a directory, fails the read: no answer
247 // comes, so the question is no — no panic, and no yes from the preset
248 for source in [StdinSource.closed, .directory] {
249 run := on_stdin(source, '', fn () []int {
250 mut p := TermPrompter{}
251 return [yn(p.confirm('a?', true)), yn(p.proceed('go?')),
252 p.choose('which?', ['x', 'y', 'z'])]
253 })!
254 assert run.answers == [0, 0, 0], '${source}'
255 // the questions were still put
256 assert run.stderr.contains('a?') && run.stderr.contains('go?')
257 }
258}
259
260fn test_term_prompts_take_one_line_each() ! {
261 // each question reads its own line, no more; the end comes after
262 run := on_stdin(.text, 'y\nn\n\n2\n', fn () []int {
263 mut p := TermPrompter{}
264 return [yn(p.confirm('one?', false)), yn(p.confirm('two?', true)),
265 yn(p.confirm('three?', true)), p.choose('four?', ['a', 'b']), yn(p.confirm('five?', true))]
266 })!
267 assert run.answers == [1, 0, 1, 1, 0]
268 // the prompts go to stderr, in order, with their answer labels
269 for q in ['one?', 'two?', 'three?', 'four?', 'five?'] {
270 assert run.stderr.contains(q)
271 }
272 assert run.stderr.index('one?')? < run.stderr.index('five?')?
273}
274
275fn test_term_proceed_end_of_input_is_no() ! {
276 // the go-ahead has a yes preset, which an empty answer takes, but the end
277 // of input never gives it
278 for text, want in {
279 '': 0
280 '\n': 1
281 'n\n': 0
282 'yes': 1
283 } {
284 run := on_stdin(.text, text, fn () []int {
285 mut p := TermPrompter{}
286 return [yn(p.proceed('proceed?'))]
287 })!
288 assert run.answers == [want], 'stdin ${text}'
289 }
290}
291
292fn test_term_choose_reads_a_number() ! {
293 for text, want in {
294 '2\n': 1
295 ' 3 \n': 2
296 // an empty answer and the end of input take the first
297 '\n': 0
298 '': 0
299 // what is not a number of the list asks again
300 'x\n9\n0\n3\n': 2
301 '-1\n2\n': 1
302 // and the end of input after it takes the first
303 'x\n': 0
304 } {
305 run := on_stdin(.text, text, fn () []int {
306 mut p := TermPrompter{}
307 return [p.choose('which?', ['a', 'b', 'c'])]
308 })!
309 assert run.answers == [want], 'stdin ${text}'
310 // every answer that is not a number of the list is said, and the
311 // question asked again: once more than the bad answers before the
312 // good one, or before the input ended
313 bad := text.split('\n').filter(it.trim_space() in ['x', '9', '0', '-1'])
314 for b in bad {
315 assert run.stderr.contains('invalid number: ${b}'), 'stdin ${text}: ${run.stderr}'
316 }
317 assert run.stderr.count('which?') == bad.len + 1, 'stdin ${text}: ${run.stderr}'
318 }
319}
320
321fn test_term_noconfirm_leaves_stdin_unread() ! {
322 // --noconfirm shows each question and takes its default; the answer on
323 // stdin is still there for the first question that does read it
324 run := on_stdin(.text, '3\n', fn () []int {
325 mut quiet := TermPrompter{
326 noconfirm: true
327 }
328 mut asks := TermPrompter{}
329 return [yn(quiet.confirm('a?', false)), yn(quiet.proceed('go?')),
330 quiet.choose('which?', ['a', 'b', 'c']), asks.choose('again?', ['a', 'b', 'c'])]
331 })!
332 assert run.answers == [0, 1, 0, 2]
333 assert run.stderr.contains('(yes, --noconfirm)')
334}
335
336fn test_stdin_line() ! {
337 // a line comes without its newline, an empty line as '', a last line
338 // without a newline whole; then the end, a StdinEnd. an unreadable stdin
339 // is an error of its own, not the end
340 run := on_stdin(.text, 'one\n\nlast', fn () []int {
341 mut got := []int{}
342 for want in ['one', '', 'last'] {
343 line := stdin_line() or { return [-1] }
344 got << yn(line == want)
345 }
346 stdin_line() or { got << yn(err is StdinEnd) }
347 return got
348 })!
349 assert run.answers == [1, 1, 1, 1]
350 for source in [StdinSource.closed, .directory] {
351 failed := on_stdin(source, '', fn () []int {
352 stdin_line() or {
353 return [yn(err !is StdinEnd), yn(err.msg().starts_with('could not read stdin'))]
354 }
355 return [-1]
356 })!
357 assert failed.answers == [1, 1], '${source}'
358 }
359}
360
361fn test_stdin_line_outlives_the_read_buffer() ! {
362 // a line is the caller's own copy: getline's buffer is freed on the way
363 // out, and the next read (same length, so the allocator hands the same
364 // block back) must not show through a line already returned. lines with
365 // and without the newline, an empty one, and a long one that makes
366 // getline grow its buffer
367 long := 'x'.repeat(5000)
368 run := on_stdin(.text, 'aaaa\nbbbb\n\n${long}\ncccc', fn [long] () []int {
369 mut lines := []string{}
370 for _ in 0 .. 5 {
371 lines << stdin_line() or { return [-1] }
372 // churn the heap between reads, as a prompt's own work does
373 mut junk := []string{}
374 for i in 0 .. 64 {
375 junk << 'zzzz${i}'.repeat(1 + i % 7)
376 }
377 }
378 return [yn(lines == ['aaaa', 'bbbb', '', long, 'cccc']), lines[3].len]
379 })!
380 assert run.answers == [1, 5000]
381}
382
383fn test_stdin_text() ! {
384 run := on_stdin(.text, 'https://a.example/\nhttps://b.example/\n', fn () []int {
385 text := stdin_text() or { return [-1] }
386 return [yn(text == 'https://a.example/\nhttps://b.example/')]
387 })!
388 assert run.answers == [1]
389 // a read that fails is an error, not an empty list
390 failed := on_stdin(.directory, '', fn () []int {
391 stdin_text() or { return [yn(err.msg().contains('could not read stdin'))] }
392 return [-1]
393 })!
394 assert failed.answers == [1]
395}
396
397// ipc_events decodes the channel's lines, every one a whole json object
398fn ipc_events(lines []string) ![]map[string]json2.Any {
399 mut out := []map[string]json2.Any{}
400 for line in lines {
401 out << json2.decode[json2.Any](line)!.as_map()
402 }
403 return out
404}
405
406fn test_ipc_prompter_reads_answers_on_stdin() ! {
407 run := on_stdin(.text, '{"id": 1, "answer": true}\n{"id": 2, "answer": 2}\n', fn () []int {
408 mut p := IpcPrompter{}
409 return [yn(p.confirm('a?', false)), p.choose('which?', ['x', 'y', 'z'])]
410 })!
411 assert run.answers == [1, 2]
412 events := ipc_events(run.channel)!
413 assert events.len == 2
414 assert events[0]['type']!.str() == 'question'
415 assert events[0]['question']!.str() == 'confirm'
416 assert events[0]['id']!.int() == 1
417 assert events[1]['question']!.str() == 'choose'
418 assert events[1]['id']!.int() == 2
419}
420
421fn test_ipc_prompter_invalid_lines_keep_the_question() ! {
422 // noise, an empty line and another question's answer are each an invalid
423 // event; the question stays, and the next valid line answers it
424 run := on_stdin(.text, 'garbage\n\n{"id": 9, "answer": true}\n{"id": 1, "answer": false}\n', fn () []int {
425 mut p := IpcPrompter{}
426 return [yn(p.confirm('a?', true))]
427 })!
428 assert run.answers == [0]
429 events := ipc_events(run.channel)!
430 assert events.map(it['type']!.str()) == ['question', 'invalid', 'invalid', 'invalid']
431 for e in events[1..] {
432 assert e['id']!.int() == 1
433 }
434}
435
436fn test_ipc_prompter_end_of_input() ! {
437 // the end of input, and a stdin that cannot be read, answer as on a
438 // terminal: no, and the first choice — no panic
439 for source in [StdinSource.text, .closed, .directory] {
440 run := on_stdin(source, '', fn () []int {
441 mut p := IpcPrompter{}
442 return [yn(p.confirm('a?', true)), yn(p.proceed('go?')), p.choose('which?', [
443 'x',
444 'y',
445 ])]
446 })!
447 assert run.answers == [0, 0, 0], '${source}'
448 assert ipc_events(run.channel)!.len == 3
449 }
450}
451
452fn test_ipc_prompter_noconfirm_answers_in_the_event() ! {
453 run := on_stdin(.text, '{"id": 1, "answer": false}\n', fn () []int {
454 mut p := IpcPrompter{
455 noconfirm: true
456 }
457 return [yn(p.confirm('a?', true))]
458 })!
459 assert run.answers == [1]
460 events := ipc_events(run.channel)!
461 assert events.len == 1
462 assert events[0]['answer']!.bool() == true
463}
464
465fn test_verbose_log_says_what_a_run_went_on_from() ! {
466 saved_flag, saved_cfg, saved_kind := verbose_flag, cfg_verbose, ui_kind
467 defer {
468 verbose_flag, cfg_verbose, ui_kind = saved_flag, saved_cfg, saved_kind
469 }
470 fail := fn () []int {
471 went_on('release the alpm handle', error('the handle is not there'))
472 went_on('remove the temp dir /tmp/x', error(''))
473 return []
474 }
475 // without --verbose a housekeeping failure stays as quiet as it was:
476 // nothing on stderr, nothing on the channel
477 verbose_flag, cfg_verbose, ui_kind = false, false, 'tty'
478 quiet := on_stdin(.text, '', fail)!
479 assert quiet.stderr == '' && quiet.channel.len == 0
480 ui_kind = 'ipc'
481 quiet_ipc := on_stdin(.text, '', fail)!
482 assert quiet_ipc.stderr == '' && quiet_ipc.channel.len == 0
483 // the flag and the config's option each turn it on, alone
484 for flag in [true, false] {
485 verbose_flag, cfg_verbose, ui_kind = flag, !flag, 'tty'
486 said := on_stdin(.text, '', fail)!
487 // a terminal gets it on stderr, marked, the reason after the what;
488 // a failure with no text of its own still names what failed
489 assert said.stderr == 'verbose: could not release the alpm handle: the handle is not there\nverbose: could not remove the temp dir /tmp/x: \n', said.stderr
490 assert said.channel.len == 0
491 // a frontend gets a message event marked verbose, and a warning for
492 // a reader that knows no verbose mark; stderr stays clean
493 ui_kind = 'ipc'
494 told := on_stdin(.text, '', fail)!
495 assert told.stderr == '', told.stderr
496 events := ipc_events(told.channel)!
497 assert events.len == 2
498 assert events[0]['type']!.str() == 'message'
499 assert events[0]['text']!.str() == 'could not release the alpm handle: the handle is not there'
500 assert events[0]['verbose']!.bool() && events[0]['warning']!.bool()
501 }
502 // an ordinary warning never carries the mark, verbose on or not
503 verbose_flag, ui_kind = true, 'ipc'
504 plain := on_stdin(.text, '', fn () []int {
505 warn('a real warning')
506 return []
507 })!
508 assert 'verbose' !in ipc_events(plain.channel)![0]
509 assert verbose_on()
510 verbose_flag, cfg_verbose = false, false
511 assert !verbose_on()
512}
513