module main import json2 import os #include #include fn C.__fpurge(stream &C.FILE) fn C.clearerr(stream &C.FILE) // Scripted is a second frontend's prompter in miniature: it answers every // question the same, and keeps what it was asked struct Scripted { mut: noconfirm bool yes bool asked []string } fn (mut p Scripted) confirm(msg string, _ bool) bool { p.asked << msg return p.yes } fn (mut p Scripted) proceed(msg string) bool { p.asked << msg return p.yes } fn (mut p Scripted) choose(msg string, choices []string) int { p.asked << msg return choices.len - 1 } fn (mut p Scripted) pick(msg string, count int) []bool { p.asked << msg return []bool{len: count, init: p.yes} } fn test_parse_selection_as_pacman() ! { // the first word selecting starts from nothing; ranges and commas assert parse_selection('2 4', 5)! == [false, true, false, true, false] assert parse_selection('1-3,5', 5)! == [true, true, true, false, true] // a first word leaving out starts from everything assert parse_selection('^2', 3)! == [true, false, true] assert parse_selection('^1-2', 3)! == [false, false, true] // later words add to or take from what stands assert parse_selection('1-4 ^3', 4)! == [true, true, false, true] for bad in ['0', '6', 'x', '3-2', '2-9', '1-'] { if _ := parse_selection(bad, 5) { assert false, '"${bad}" was taken' } } } fn test_select_answer_is_a_list_of_indices() ! { assert parse_select_answer('{"id": 3, "answer": [0, 2]}', 3, 3)! == [true, false, true] assert parse_select_answer('{"id": 3, "answer": []}', 3, 3)! == [false, false, false] for bad in ['{"id": 3, "answer": true}', '{"id": 3, "answer": [3]}', '{"id": 3, "answer": [0.5]}', '{"id": 2, "answer": [0]}', 'noise'] { if _ := parse_select_answer(bad, 3, 3) { assert false, '${bad} was taken' } } } fn test_noconfirm_takes_the_defaults() { // the questions go to stderr; stdin is never read, so none of these blocks mut ui := new_trans_ui(noconfirm: true) assert ui.yesno('a?') assert !ui.noyes('b?') assert ui.proceed('proceed?') assert ui.choose('which one?', ['a', 'b', 'c']) == 0 assert ui.pick('which ones?', 3) == [true, true, true] } fn test_policy_through_the_interface() { mut ui := new_trans_ui() assert !ui.prompt.noconfirm // a mode may flip the policy for one listing, through the interface, // whichever prompter is behind it ui.prompt.noconfirm = true assert ui.proceed('proceed?') } fn test_every_prompt_reaches_the_prompter() ! { mut ui := new_trans_ui() ui.prompt = Scripted{ yes: true } assert did_you_mean(mut ui, 'zshh', ['zsh', 'bash'])! == 'zsh' assert ui.choose('which one?', ['a', 'b', 'c']) == 2 assert ui.proceed('proceed?') // nothing near the query: the error comes without a question if _ := did_you_mean(mut ui, 'qqqqqq', ['zsh']) { assert false } s := ui.prompt as Scripted assert s.asked.len == 3 assert s.asked[1..] == ['which one?', 'proceed?'] ui.prompt = Scripted{ yes: false } if _ := did_you_mean(mut ui, 'zshh', ['zsh']) { assert false } } // StdinSource is what a scripted stdin reads: the text given, a stdin that // is closed, or a directory, which every read fails on enum StdinSource { text closed directory } // Scripted run is what on_stdin hands back: the answers the prompts gave, // what they wrote to stderr, and the ipc channel's lines struct ScriptedRun { answers []int stderr string channel []string } // reset_stdin drops what stdio buffered of the stdin before, and its end of // file mark, so one script's leftovers never reach the next fn reset_stdin() { C.__fpurge(C.stdin) C.clearerr(C.stdin) } // on_stdin runs ask with fd 0 reading from source, fd 2 and the ipc channel // each written to a file, then puts all three back. it is the real stdin // that is read, through stdio as the prompters read it, so what the libc // and the line reader make of an end or a failure is what is tested fn on_stdin(source StdinSource, text string, ask fn () []int) !ScriptedRun { dir := os.join_path(os.vtmp_dir(), 'vpac_test_prompt_${os.getpid()}') os.mkdir_all(dir)! defer { os.rmdir_all(dir) or {} } os.write_file(os.join_path(dir, 'stdin'), text)! mut in_file := os.open(os.join_path(dir, 'stdin'))! defer { in_file.close() } mut err_file := os.create(os.join_path(dir, 'stderr'))! mut chan_file := os.create(os.join_path(dir, 'channel'))! defer { err_file.close() chan_file.close() } dir_fd := C.open(&char(dir.str), C.O_RDONLY) saved_in := C.dup(0) saved_err := C.dup(2) // whatever was opened is closed again on every way out, the failed // setup's included: a descriptor left behind would be the next // script's stdin by number defer { for fd in [dir_fd, saved_in, saved_err] { if fd >= 0 { C.close(fd) } } } if dir_fd < 0 || saved_in < 0 || saved_err < 0 { return error('could not set the scripted stdin up') } saved_ipc := ipc_fd reset_stdin() // dup2 answers the new descriptor, never 0, on success wired_in := match source { .text { C.dup2(in_file.fd, 0) >= 0 } .closed { C.close(0) == 0 } .directory { C.dup2(dir_fd, 0) >= 0 } } wired_err := C.dup2(err_file.fd, 2) >= 0 mut answers := []int{} if wired_in && wired_err { ipc_fd = chan_file.fd answers = ask() ipc_fd = saved_ipc } // the real stdin and stderr come back whether or not the script ran back_in := C.dup2(saved_in, 0) >= 0 back_err := C.dup2(saved_err, 2) >= 0 reset_stdin() if !wired_in || !wired_err { return error('could not point stdin or stderr at the script') } if !back_in || !back_err { return error('could not put stdin or stderr back after the script') } err_file.flush() chan_file.flush() return ScriptedRun{ answers: answers stderr: os.read_file(os.join_path(dir, 'stderr'))! channel: os.read_lines(os.join_path(dir, 'channel'))! } } fn yn(b bool) int { return if b { 1 } else { 0 } } // confirm_both asks one question on the script with a yes preset, and the // same on the same script with a no preset fn confirm_both(text string) ![]int { yes := on_stdin(.text, text, fn () []int { mut p := TermPrompter{} return [yn(p.confirm('a?', true))] })! no := on_stdin(.text, text, fn () []int { mut p := TermPrompter{} return [yn(p.confirm('a?', false))] })! return [yes.answers[0], no.answers[0]] } fn test_term_confirm_reads_the_answer_on_stdin() ! { // [with a yes preset, with a no preset], as pacman's question() answers for text, want in { // end of input is no, whatever the preset '': [0, 0] // an empty answer, blanks or not, takes the preset '\n': [1, 0] ' \t \n': [1, 0] 'y\n': [1, 1] 'Y\n': [1, 1] 'yes\n': [1, 1] ' YeS \n': [1, 1] 'n\n': [0, 0] 'no\n': [0, 0] // anything else is no, even with a yes preset 'maybe\n': [0, 0] 'yess\n': [0, 0] // a last line without its newline is an answer, as fgets reads it 'y': [1, 1] 'n': [0, 0] } { assert confirm_both(text)! == want, 'stdin ${text}' } } fn test_term_confirm_unreadable_stdin_is_no() ! { // a closed stdin, or one that is a directory, fails the read: no answer // comes, so the question is no — no panic, and no yes from the preset for source in [StdinSource.closed, .directory] { run := on_stdin(source, '', fn () []int { mut p := TermPrompter{} return [yn(p.confirm('a?', true)), yn(p.proceed('go?')), p.choose('which?', ['x', 'y', 'z'])] })! assert run.answers == [0, 0, 0], '${source}' // the questions were still put assert run.stderr.contains('a?') && run.stderr.contains('go?') } } fn test_term_prompts_take_one_line_each() ! { // each question reads its own line, no more; the end comes after run := on_stdin(.text, 'y\nn\n\n2\n', fn () []int { mut p := TermPrompter{} return [yn(p.confirm('one?', false)), yn(p.confirm('two?', true)), yn(p.confirm('three?', true)), p.choose('four?', ['a', 'b']), yn(p.confirm('five?', true))] })! assert run.answers == [1, 0, 1, 1, 0] // the prompts go to stderr, in order, with their answer labels for q in ['one?', 'two?', 'three?', 'four?', 'five?'] { assert run.stderr.contains(q) } assert run.stderr.index('one?')? < run.stderr.index('five?')? } fn test_term_proceed_end_of_input_is_no() ! { // the go-ahead has a yes preset, which an empty answer takes, but the end // of input never gives it for text, want in { '': 0 '\n': 1 'n\n': 0 'yes': 1 } { run := on_stdin(.text, text, fn () []int { mut p := TermPrompter{} return [yn(p.proceed('proceed?'))] })! assert run.answers == [want], 'stdin ${text}' } } fn test_term_choose_reads_a_number() ! { for text, want in { '2\n': 1 ' 3 \n': 2 // an empty answer and the end of input take the first '\n': 0 '': 0 // what is not a number of the list asks again 'x\n9\n0\n3\n': 2 '-1\n2\n': 1 // and the end of input after it takes the first 'x\n': 0 } { run := on_stdin(.text, text, fn () []int { mut p := TermPrompter{} return [p.choose('which?', ['a', 'b', 'c'])] })! assert run.answers == [want], 'stdin ${text}' // every answer that is not a number of the list is said, and the // question asked again: once more than the bad answers before the // good one, or before the input ended bad := text.split('\n').filter(it.trim_space() in ['x', '9', '0', '-1']) for b in bad { assert run.stderr.contains('invalid number: ${b}'), 'stdin ${text}: ${run.stderr}' } assert run.stderr.count('which?') == bad.len + 1, 'stdin ${text}: ${run.stderr}' } } fn test_term_noconfirm_leaves_stdin_unread() ! { // --noconfirm shows each question and takes its default; the answer on // stdin is still there for the first question that does read it run := on_stdin(.text, '3\n', fn () []int { mut quiet := TermPrompter{ noconfirm: true } mut asks := TermPrompter{} return [yn(quiet.confirm('a?', false)), yn(quiet.proceed('go?')), quiet.choose('which?', ['a', 'b', 'c']), asks.choose('again?', ['a', 'b', 'c'])] })! assert run.answers == [0, 1, 0, 2] assert run.stderr.contains('(yes, --noconfirm)') } fn test_stdin_line() ! { // a line comes without its newline, an empty line as '', a last line // without a newline whole; then the end, a StdinEnd. an unreadable stdin // is an error of its own, not the end run := on_stdin(.text, 'one\n\nlast', fn () []int { mut got := []int{} for want in ['one', '', 'last'] { line := stdin_line() or { return [-1] } got << yn(line == want) } stdin_line() or { got << yn(err is StdinEnd) } return got })! assert run.answers == [1, 1, 1, 1] for source in [StdinSource.closed, .directory] { failed := on_stdin(source, '', fn () []int { stdin_line() or { return [yn(err !is StdinEnd), yn(err.msg().starts_with('could not read stdin'))] } return [-1] })! assert failed.answers == [1, 1], '${source}' } } fn test_stdin_line_outlives_the_read_buffer() ! { // a line is the caller's own copy: getline's buffer is freed on the way // out, and the next read (same length, so the allocator hands the same // block back) must not show through a line already returned. lines with // and without the newline, an empty one, and a long one that makes // getline grow its buffer long := 'x'.repeat(5000) run := on_stdin(.text, 'aaaa\nbbbb\n\n${long}\ncccc', fn [long] () []int { mut lines := []string{} for _ in 0 .. 5 { lines << stdin_line() or { return [-1] } // churn the heap between reads, as a prompt's own work does mut junk := []string{} for i in 0 .. 64 { junk << 'zzzz${i}'.repeat(1 + i % 7) } } return [yn(lines == ['aaaa', 'bbbb', '', long, 'cccc']), lines[3].len] })! assert run.answers == [1, 5000] } fn test_stdin_text() ! { run := on_stdin(.text, 'https://a.example/\nhttps://b.example/\n', fn () []int { text := stdin_text() or { return [-1] } return [yn(text == 'https://a.example/\nhttps://b.example/')] })! assert run.answers == [1] // a read that fails is an error, not an empty list failed := on_stdin(.directory, '', fn () []int { stdin_text() or { return [yn(err.msg().contains('could not read stdin'))] } return [-1] })! assert failed.answers == [1] } // ipc_events decodes the channel's lines, every one a whole json object fn ipc_events(lines []string) ![]map[string]json2.Any { mut out := []map[string]json2.Any{} for line in lines { out << json2.decode[json2.Any](line)!.as_map() } return out } fn test_ipc_prompter_reads_answers_on_stdin() ! { run := on_stdin(.text, '{"id": 1, "answer": true}\n{"id": 2, "answer": 2}\n', fn () []int { mut p := IpcPrompter{} return [yn(p.confirm('a?', false)), p.choose('which?', ['x', 'y', 'z'])] })! assert run.answers == [1, 2] events := ipc_events(run.channel)! assert events.len == 2 assert events[0]['type']!.str() == 'question' assert events[0]['question']!.str() == 'confirm' assert events[0]['id']!.int() == 1 assert events[1]['question']!.str() == 'choose' assert events[1]['id']!.int() == 2 } fn test_ipc_prompter_invalid_lines_keep_the_question() ! { // noise, an empty line and another question's answer are each an invalid // event; the question stays, and the next valid line answers it run := on_stdin(.text, 'garbage\n\n{"id": 9, "answer": true}\n{"id": 1, "answer": false}\n', fn () []int { mut p := IpcPrompter{} return [yn(p.confirm('a?', true))] })! assert run.answers == [0] events := ipc_events(run.channel)! assert events.map(it['type']!.str()) == ['question', 'invalid', 'invalid', 'invalid'] for e in events[1..] { assert e['id']!.int() == 1 } } fn test_ipc_prompter_end_of_input() ! { // the end of input, and a stdin that cannot be read, answer as on a // terminal: no, and the first choice — no panic for source in [StdinSource.text, .closed, .directory] { run := on_stdin(source, '', fn () []int { mut p := IpcPrompter{} return [yn(p.confirm('a?', true)), yn(p.proceed('go?')), p.choose('which?', [ 'x', 'y', ])] })! assert run.answers == [0, 0, 0], '${source}' assert ipc_events(run.channel)!.len == 3 } } fn test_ipc_prompter_noconfirm_answers_in_the_event() ! { run := on_stdin(.text, '{"id": 1, "answer": false}\n', fn () []int { mut p := IpcPrompter{ noconfirm: true } return [yn(p.confirm('a?', true))] })! assert run.answers == [1] events := ipc_events(run.channel)! assert events.len == 1 assert events[0]['answer']!.bool() == true } fn test_verbose_log_says_what_a_run_went_on_from() ! { saved_flag, saved_cfg, saved_kind := verbose_flag, cfg_verbose, ui_kind defer { verbose_flag, cfg_verbose, ui_kind = saved_flag, saved_cfg, saved_kind } fail := fn () []int { went_on('release the alpm handle', error('the handle is not there')) went_on('remove the temp dir /tmp/x', error('')) return [] } // without --verbose a housekeeping failure stays as quiet as it was: // nothing on stderr, nothing on the channel verbose_flag, cfg_verbose, ui_kind = false, false, 'tty' quiet := on_stdin(.text, '', fail)! assert quiet.stderr == '' && quiet.channel.len == 0 ui_kind = 'ipc' quiet_ipc := on_stdin(.text, '', fail)! assert quiet_ipc.stderr == '' && quiet_ipc.channel.len == 0 // the flag and the config's option each turn it on, alone for flag in [true, false] { verbose_flag, cfg_verbose, ui_kind = flag, !flag, 'tty' said := on_stdin(.text, '', fail)! // a terminal gets it on stderr, marked, the reason after the what; // a failure with no text of its own still names what failed 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 assert said.channel.len == 0 // a frontend gets a message event marked verbose, and a warning for // a reader that knows no verbose mark; stderr stays clean ui_kind = 'ipc' told := on_stdin(.text, '', fail)! assert told.stderr == '', told.stderr events := ipc_events(told.channel)! assert events.len == 2 assert events[0]['type']!.str() == 'message' assert events[0]['text']!.str() == 'could not release the alpm handle: the handle is not there' assert events[0]['verbose']!.bool() && events[0]['warning']!.bool() } // an ordinary warning never carries the mark, verbose on or not verbose_flag, ui_kind = true, 'ipc' plain := on_stdin(.text, '', fn () []int { warn('a real warning') return [] })! assert 'verbose' !in ipc_events(plain.channel)![0] assert verbose_on() verbose_flag, cfg_verbose = false, false assert !verbose_on() }