module main import alpm import json2 import os fn test_parse_answer() ! { // a yes or no takes a bool, a choice an index in range assert parse_answer('{"id":1,"answer":true}', 1, 'confirm', 0)! == 1 assert parse_answer('{"id":1,"answer":false}\n', 1, 'proceed', 0)! == 0 assert parse_answer('{"id":4,"answer":2}', 4, 'choose', 3)! == 2 assert parse_answer('{"answer":0,"id":4}', 4, 'choose', 3)! == 0 // anything else is refused, and the question stands for line, why in { 'garbage': 'not json' '{"answer":true}': 'no id' '{"id":2,"answer":true}': 'is 1, not 2' '{"id":1}': 'no answer' '{"id":1,"answer":1}': 'true or false' '{"id":1,"answer":"yes"}': 'true or false' } { if _ := parse_answer(line, 1, 'confirm', 0) { assert false, line } else { assert err.msg().contains(why), '${line}: ${err.msg()}' } } for line in ['{"id":1,"answer":3}', '{"id":1,"answer":-1}', '{"id":1,"answer":true}'] { if _ := parse_answer(line, 1, 'choose', 3) { assert false, line } } } // channel_write lays a whole line on the channel: checked against a real // pipe, and against an fd that refuses writes, where the line's failure // comes back instead of hanging fn test_channel_write() ! { mut p := os.pipe()! defer { p.close() } old := ipc_fd defer { ipc_fd = old } ipc_fd = p.write_fd assert channel_write('{"a":1}\n') == true line, n := os.fd_read(p.read_fd, 64) assert line[..n] == '{"a":1}\n' // a whole line again, after the first assert channel_write('{}\n') == true line2, n2 := os.fd_read(p.read_fd, 64) assert line2[..n2] == '{}\n' } fn test_channel_write_fails_rather_than_hangs() ! { // a descriptor that cannot be written answers an error at once, the // closest a test gets to a channel whose reader is gone tmp := os.join_path(os.vtmp_dir(), 'vpac_test_ipc_ro_${os.getpid()}.txt') os.write_file(tmp, '')! os.chmod(tmp, 0o444)! defer { os.rm(tmp) or {} } mut f := os.open_file(tmp, 'r')! defer { f.close() } old := ipc_fd defer { ipc_fd = old } ipc_fd = f.fd assert !channel_write('{"a":1}\n') } // whole_of keeps a json number that is a whole one: the ids and the choice // indices have to arrive as integers, never as 1.5 or as text fn test_whole_of() { assert whole_of(json2.Any(f64(1))) or { -100 } == 1 assert whole_of(json2.Any(f64(0))) or { -100 } == 0 assert whole_of(json2.Any(f64(4096))) or { -100 } == 4096 assert whole_of(json2.Any(f64(1.5))) == none assert whole_of(json2.Any('1')) == none } fn test_event_shapes() { // the type field names the event; a yes or no travels as a bool, a // choice as its index, and an answer only under --noconfirm assert json2.encode(QuestionEvent{ id: 3 question: 'proceed' msg: 'proceed?' preset: json2.Any(true) }) == '{"type":"question","id":3,"question":"proceed","msg":"proceed?","preset":true}' assert json2.encode(QuestionEvent{ id: 1 question: 'choose' msg: 'pick' preset: json2.Any(0) choices: ['a', 'b'] answer: json2.Any(0) }) == '{"type":"question","id":1,"question":"choose","msg":"pick","preset":0,"choices":["a","b"],"answer":0}' // a search -g entry names its group; any other entry has none assert json2.encode(ListEntry{ name: 'zsh' values: [] group: 'shells' }) == '{"name":"zsh","values":[],"group":"shells"}' assert json2.encode(ListEntry{ name: 'zsh' values: [] }) == '{"name":"zsh","values":[]}' assert json2.encode(DoneEvent{ action: 'marked' reason: 'depend' packages: ['a'] }) == '{"type":"done","action":"marked","reason":"depend","packages":["a"]}' assert json2.encode(ProgressEvent{ op: 'removing' percent: 50 current: 1 total: 2 }) == '{"type":"progress","op":"removing","percent":50,"current":1,"total":2}' } fn test_download_event_shapes() { // a progress report keeps its shape: no retry fields unless retrying assert json2.encode(DownloadEvent{ file: 'a.pkg' downloaded: 10 total: 20 }) == '{"type":"download","file":"a.pkg","downloaded":10,"total":20,"done":false,"result":0}' assert json2.encode(DownloadEvent{ file: 'a.pkg' retry: true }) == '{"type":"download","file":"a.pkg","downloaded":0,"total":0,"done":false,"result":0,"retry":true}' assert json2.encode(DownloadEvent{ file: 'a.pkg' retry: true resume: true }).ends_with('"retry":true,"resume":true}') } fn test_download_due() { beat := download_beat // the first report of a download always goes out assert download_due(none, 0, 0) last := DownloadSent{ percent: 3 at: 1000 } // the percent moved: out, at once assert download_due(last, 4, 1001) // the same percent within a beat: held back assert !download_due(last, 3, 1000 + beat - 1) // the same percent a beat later: out, so a slow download keeps a frontend // informed between its percents assert download_due(last, 3, 1000 + beat) assert download_due(last, 3, 1000 + 10 * beat) } // downloads_said feeds ipc_download libalpm's own event structs and returns // the events it sent fn downloads_said(feed fn (mut ui TransUI)) ![]map[string]json2.Any { path := os.join_path(os.vtmp_dir(), 'vpac_test_dl_${os.getpid()}') mut f := os.create(path)! defer { os.rm(path) or {} } old := ipc_fd ipc_fd = f.fd mut ui := new_trans_ui() feed(mut ui) ipc_fd = old f.close() mut out := []map[string]json2.Any{} for line in os.read_lines(path)! { out << json2.decode[json2.Any](line)!.as_map() } return out } fn test_ipc_download_retry() ! { events := downloads_said(fn (mut ui TransUI) { mut p := alpm.DownloadEventProgress{ downloaded: 50 total: 100 } ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p)) // the same percent right after: held back ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p)) mut r := alpm.DownloadEventRetry{ resume: 0 } ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r)) // started over from the next mirror: its first report goes out, // whatever the percent last said p.downloaded = 0 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p)) mut r2 := alpm.DownloadEventRetry{ resume: 1 } ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r2)) mut c := alpm.DownloadEventCompleted{ total: 100 result: 0 } ipc_download(mut ui, 'a.pkg', .completed, voidptr(&c)) })! assert events.len == 5 assert events[0]['downloaded']!.int() == 50 assert events[1]['retry']!.bool() assert 'resume' !in events[1] assert events[2]['downloaded']!.int() == 0 assert 'retry' !in events[2] assert events[3]['retry']!.bool() assert events[3]['resume']!.bool() assert events[4]['done']!.bool() } fn test_ipc_download_dedupes_per_file() ! { events := downloads_said(fn (mut ui TransUI) { mut a := alpm.DownloadEventProgress{ downloaded: 10 total: 100 } mut b := alpm.DownloadEventProgress{ downloaded: 10 total: 100 } // two files at the same percent are two reports, not one held back ipc_download(mut ui, 'a.pkg', .progress, voidptr(&a)) ipc_download(mut ui, 'b.pkg', .progress, voidptr(&b)) // a's percent moves: out; b stays: held back a.downloaded = 20 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&a)) ipc_download(mut ui, 'b.pkg', .progress, voidptr(&b)) })! assert events.map(it['file']!.str()) == ['a.pkg', 'b.pkg', 'a.pkg'] } fn test_message_event_shape() { // a plain message and a warning keep their shape; only libalpm's errors // carry the error flag, beside the warning one assert json2.encode(MessageEvent{ text: 'system upgraded' }) == '{"type":"message","text":"system upgraded","warning":false}' assert json2.encode(MessageEvent{ text: 'careful' warning: true }) == '{"type":"message","text":"careful","warning":true}' assert json2.encode(MessageEvent{ text: 'broke' warning: true error: true }) == '{"type":"message","text":"broke","warning":true,"error":true}' } // ScriptedWrites is a write(2) that answers from a script: each step is how // many bytes the call takes (at most what it is offered), or -1 with an // errno; what it took is kept, in order @[heap] struct ScriptedWrites { mut: steps []int code int calls int got []u8 } fn (mut w ScriptedWrites) write(_ int, buf voidptr, n int) (int, int) { if w.calls >= w.steps.len { // past the script, take everything w.got << unsafe { (&u8(buf)).vbytes(n) } w.calls++ return n, 0 } step := w.steps[w.calls] w.calls++ if step < 0 { return -1, w.code } take := if step < n { step } else { n } w.got << unsafe { (&u8(buf)).vbytes(take) } return take, 0 } fn scripted_write(steps []int, code int, line string) (bool, string, int) { mut w := &ScriptedWrites{ steps: steps code: code } ok := channel_write_to(9, line, fn [mut w] (fd int, buf voidptr, n int) (int, int) { return w.write(fd, buf, n) }) return ok, w.got.bytestr(), w.calls } fn test_channel_write_interrupted_is_taken_again() { // EINTR before anything went out, and again part way: the line still // goes out whole, in order, nothing twice ok, got, calls := scripted_write([-1, 3, -1, 2], C.EINTR, '{"a":1}\n') assert ok assert got == '{"a":1}\n' assert calls == 5 } fn test_channel_write_short_writes_add_up() { ok, got, _ := scripted_write([1, 1, 1, 1, 1, 1, 1], 0, '{"b":22}\n') assert ok assert got == '{"b":22}\n' } fn test_channel_write_without_progress_fails() { // a write that answers nothing would loop forever: it is a failure, at // once, whatever went out before it ok, got, calls := scripted_write([2, 0], 0, '{"c":3}\n') assert !ok assert got == '{"' assert calls == 2 } fn test_channel_write_other_errors_fail() { // a reader that is gone (EPIPE) is no interruption: no retry ok, _, calls := scripted_write([-1], 32, '{}\n') assert !ok assert calls == 1 } fn test_transaction_event_shapes() ! { // the listing a go-ahead is asked for: its packages whole, the sizes // summed by whoever built it, and preview said either way so a reader // never guesses whether a question follows ev := TransactionEvent{ action: 'upgrade' packages: [ TransPkg{ name: 'foo' version: '2.0-1' old_version: '1.0-1' download_size: 10 installed_size: 30 }, TransPkg{ name: 'new' version: '1.0-1' }, ] download_size: 10 installed_size: 30 } m := json2.decode[json2.Any](json2.encode(ev))!.as_map() assert m['type']!.str() == 'transaction' assert m['action']!.str() == 'upgrade' assert m['download_size']!.i64() == 10 && m['installed_size']!.i64() == 30 assert !m['preview']!.bool() pkgs := m['packages']!.as_array().map(it.as_map()) assert pkgs.len == 2 assert pkgs[0]['name']!.str() == 'foo' && pkgs[0]['old_version']!.str() == '1.0-1' assert pkgs[0]['download_size']!.i64() == 10 && pkgs[0]['installed_size']!.i64() == 30 // a package that was not installed before has an empty old version, // present all the same: every package has the same keys assert pkgs[1]['old_version']!.str() == '' assert pkgs[1].keys() == pkgs[0].keys() // a preview is the same event with the mark set mut preview := ev preview.preview = true assert json2.decode[json2.Any](json2.encode(preview))!.as_map()['preview']!.bool() // a transaction of nothing still carries its list, empty empty := json2.decode[json2.Any](json2.encode(TransactionEvent{ action: 'remove' }))!.as_map() assert empty['packages']!.as_array().len == 0 assert empty['download_size']!.i64() == 0 // sizes past 32 bits travel whole big := json2.decode[json2.Any](json2.encode(TransactionEvent{ action: 'install' download_size: i64(6) * 1024 * 1024 * 1024 installed_size: i64(20) * 1024 * 1024 * 1024 }))!.as_map() assert big['download_size']!.i64() == i64(6) * 1024 * 1024 * 1024 assert big['installed_size']!.i64() == i64(20) * 1024 * 1024 * 1024 // the packages event beside it has the same package shape shown := json2.decode[json2.Any](json2.encode(PackagesEvent{ title: '1 packages to remove:' packages: [TransPkg{ name: 'old' version: '1.0-1' }] }))!.as_map() assert shown['type']!.str() == 'packages' assert shown['packages']!.as_array()[0].as_map().keys() == pkgs[0].keys() // a provides event names its files only when it has some to name assert json2.encode(ProvidesEvent{ path: '/usr/bin/x' fields: ['name'] }) == '{"type":"provides","path":"/usr/bin/x","fields":["name"],"entries":[]}' assert json2.encode(ProvidesEvent{ path: 'x' fields: ['name'] entries: [ListEntry{ name: 'p' values: ['p'] }] files: [['usr/bin/x']] }).ends_with(',"files":[["usr/bin/x"]]}') }