vpac / src / ipc_test.v
395 lines · 375 sloc · 12.35 KB · 841315c100c81d9e6b14c4b55a25d4e3d12db762
Raw
1module main
2
3import nspkg
4import json2
5import os
6
7fn test_parse_answer() ! {
8 // a yes or no takes a bool, a choice an index in range
9 assert parse_answer('{"id":1,"answer":true}', 1, 'confirm', 0)! == 1
10 assert parse_answer('{"id":1,"answer":false}\n', 1, 'proceed', 0)! == 0
11 assert parse_answer('{"id":4,"answer":2}', 4, 'choose', 3)! == 2
12 assert parse_answer('{"answer":0,"id":4}', 4, 'choose', 3)! == 0
13 // anything else is refused, and the question stands
14 for line, why in {
15 'garbage': 'not json'
16 '{"answer":true}': 'no id'
17 '{"id":2,"answer":true}': 'is 1, not 2'
18 '{"id":1}': 'no answer'
19 '{"id":1,"answer":1}': 'true or false'
20 '{"id":1,"answer":"yes"}': 'true or false'
21 } {
22 if _ := parse_answer(line, 1, 'confirm', 0) {
23 assert false, line
24 } else {
25 assert err.msg().contains(why), '${line}: ${err.msg()}'
26 }
27 }
28 for line in ['{"id":1,"answer":3}', '{"id":1,"answer":-1}', '{"id":1,"answer":true}'] {
29 if _ := parse_answer(line, 1, 'choose', 3) {
30 assert false, line
31 }
32 }
33}
34
35// channel_write lays a whole line on the channel: checked against a real
36// pipe, and against an fd that refuses writes, where the line's failure
37// comes back instead of hanging
38fn test_channel_write() ! {
39 mut p := os.pipe()!
40 defer { p.close() }
41 old := ipc_fd
42 defer { ipc_fd = old }
43 ipc_fd = p.write_fd
44 assert channel_write('{"a":1}\n') == true
45 line, n := os.fd_read(p.read_fd, 64)
46 assert line[..n] == '{"a":1}\n'
47 // a whole line again, after the first
48 assert channel_write('{}\n') == true
49 line2, n2 := os.fd_read(p.read_fd, 64)
50 assert line2[..n2] == '{}\n'
51}
52
53fn test_channel_write_fails_rather_than_hangs() ! {
54 // a descriptor that cannot be written answers an error at once, the
55 // closest a test gets to a channel whose reader is gone
56 tmp := os.join_path(os.vtmp_dir(), 'vpac_test_ipc_ro_${os.getpid()}.txt')
57 os.write_file(tmp, '')!
58 os.chmod(tmp, 0o444)!
59 defer { os.rm(tmp) or {} }
60 mut f := os.open_file(tmp, 'r')!
61 defer { f.close() }
62 old := ipc_fd
63 defer { ipc_fd = old }
64 ipc_fd = f.fd
65 assert !channel_write('{"a":1}\n')
66}
67
68// whole_of keeps a json number that is a whole one: the ids and the choice
69// indices have to arrive as integers, never as 1.5 or as text
70fn test_whole_of() {
71 assert whole_of(json2.Any(f64(1))) or { -100 } == 1
72 assert whole_of(json2.Any(f64(0))) or { -100 } == 0
73 assert whole_of(json2.Any(f64(4096))) or { -100 } == 4096
74 assert whole_of(json2.Any(f64(1.5))) == none
75 assert whole_of(json2.Any('1')) == none
76}
77
78fn test_event_shapes() {
79 // the type field names the event; a yes or no travels as a bool, a
80 // choice as its index, and an answer only under --noconfirm
81 assert json2.encode(QuestionEvent{
82 id: 3
83 question: 'proceed'
84 msg: 'proceed?'
85 preset: json2.Any(true)
86 }) == '{"type":"question","id":3,"question":"proceed","msg":"proceed?","preset":true}'
87 assert json2.encode(QuestionEvent{
88 id: 1
89 question: 'choose'
90 msg: 'pick'
91 preset: json2.Any(0)
92 choices: ['a', 'b']
93 answer: json2.Any(0)
94 }) == '{"type":"question","id":1,"question":"choose","msg":"pick","preset":0,"choices":["a","b"],"answer":0}'
95 // a search -g entry names its group; any other entry has none
96 assert json2.encode(ListEntry{
97 name: 'zsh'
98 values: []
99 group: 'shells'
100 }) == '{"name":"zsh","values":[],"group":"shells"}'
101 assert json2.encode(ListEntry{
102 name: 'zsh'
103 values: []
104 }) == '{"name":"zsh","values":[]}'
105 assert json2.encode(DoneEvent{
106 action: 'marked'
107 reason: 'depend'
108 packages: ['a']
109 }) == '{"type":"done","action":"marked","reason":"depend","packages":["a"]}'
110 assert json2.encode(ProgressEvent{
111 op: 'removing'
112 percent: 50
113 current: 1
114 total: 2
115 }) == '{"type":"progress","op":"removing","percent":50,"current":1,"total":2}'
116}
117
118fn test_download_event_shapes() {
119 // a progress report keeps its shape: no retry fields unless retrying
120 assert json2.encode(DownloadEvent{
121 file: 'a.pkg'
122 downloaded: 10
123 total: 20
124 }) == '{"type":"download","file":"a.pkg","downloaded":10,"total":20,"done":false,"result":0}'
125 assert json2.encode(DownloadEvent{
126 file: 'a.pkg'
127 retry: true
128 }) == '{"type":"download","file":"a.pkg","downloaded":0,"total":0,"done":false,"result":0,"retry":true}'
129 assert json2.encode(DownloadEvent{
130 file: 'a.pkg'
131 retry: true
132 resume: true
133 }).ends_with('"retry":true,"resume":true}')
134}
135
136fn test_download_due() {
137 beat := download_beat
138 // the first report of a download always goes out
139 assert download_due(none, 0, 0)
140 last := DownloadSent{
141 percent: 3
142 at: 1000
143 }
144 // the percent moved: out, at once
145 assert download_due(last, 4, 1001)
146 // the same percent within a beat: held back
147 assert !download_due(last, 3, 1000 + beat - 1)
148 // the same percent a beat later: out, so a slow download keeps a frontend
149 // informed between its percents
150 assert download_due(last, 3, 1000 + beat)
151 assert download_due(last, 3, 1000 + 10 * beat)
152}
153
154// downloads_said feeds ipc_download libalpm's own event structs and returns
155// the events it sent
156fn downloads_said(feed fn (mut ui TransUI)) ![]map[string]json2.Any {
157 path := os.join_path(os.vtmp_dir(), 'vpac_test_dl_${os.getpid()}')
158 mut f := os.create(path)!
159 defer { os.rm(path) or {} }
160 old := ipc_fd
161 ipc_fd = f.fd
162 mut ui := new_trans_ui()
163 feed(mut ui)
164 ipc_fd = old
165 f.close()
166 mut out := []map[string]json2.Any{}
167 for line in os.read_lines(path)! {
168 out << json2.decode[json2.Any](line)!.as_map()
169 }
170 return out
171}
172
173fn test_ipc_download_retry() ! {
174 events := downloads_said(fn (mut ui TransUI) {
175 mut p := nspkg.DownloadEventProgress{
176 downloaded: 50
177 total: 100
178 }
179 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p))
180 // the same percent right after: held back
181 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p))
182 mut r := nspkg.DownloadEventRetry{
183 resume: 0
184 }
185 ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r))
186 // started over from the next mirror: its first report goes out,
187 // whatever the percent last said
188 p.downloaded = 0
189 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p))
190 mut r2 := nspkg.DownloadEventRetry{
191 resume: 1
192 }
193 ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r2))
194 mut c := nspkg.DownloadEventCompleted{
195 total: 100
196 result: 0
197 }
198 ipc_download(mut ui, 'a.pkg', .completed, voidptr(&c))
199 })!
200 assert events.len == 5
201 assert events[0]['downloaded']!.int() == 50
202 assert events[1]['retry']!.bool()
203 assert 'resume' !in events[1]
204 assert events[2]['downloaded']!.int() == 0
205 assert 'retry' !in events[2]
206 assert events[3]['retry']!.bool()
207 assert events[3]['resume']!.bool()
208 assert events[4]['done']!.bool()
209}
210
211fn test_ipc_download_dedupes_per_file() ! {
212 events := downloads_said(fn (mut ui TransUI) {
213 mut a := nspkg.DownloadEventProgress{
214 downloaded: 10
215 total: 100
216 }
217 mut b := nspkg.DownloadEventProgress{
218 downloaded: 10
219 total: 100
220 }
221 // two files at the same percent are two reports, not one held back
222 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&a))
223 ipc_download(mut ui, 'b.pkg', .progress, voidptr(&b))
224 // a's percent moves: out; b stays: held back
225 a.downloaded = 20
226 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&a))
227 ipc_download(mut ui, 'b.pkg', .progress, voidptr(&b))
228 })!
229 assert events.map(it['file']!.str()) == ['a.pkg', 'b.pkg', 'a.pkg']
230}
231
232fn test_message_event_shape() {
233 // a plain message and a warning keep their shape; only libalpm's errors
234 // carry the error flag, beside the warning one
235 assert json2.encode(MessageEvent{
236 text: 'system upgraded'
237 }) == '{"type":"message","text":"system upgraded","warning":false}'
238 assert json2.encode(MessageEvent{
239 text: 'careful'
240 warning: true
241 }) == '{"type":"message","text":"careful","warning":true}'
242 assert json2.encode(MessageEvent{
243 text: 'broke'
244 warning: true
245 error: true
246 }) == '{"type":"message","text":"broke","warning":true,"error":true}'
247}
248
249// ScriptedWrites is a write(2) that answers from a script: each step is how
250// many bytes the call takes (at most what it is offered), or -1 with an
251// errno; what it took is kept, in order
252@[heap]
253struct ScriptedWrites {
254mut:
255 steps []int
256 code int
257 calls int
258 got []u8
259}
260
261fn (mut w ScriptedWrites) write(_ int, buf voidptr, n int) (int, int) {
262 if w.calls >= w.steps.len {
263 // past the script, take everything
264 w.got << unsafe { (&u8(buf)).vbytes(n) }
265 w.calls++
266 return n, 0
267 }
268 step := w.steps[w.calls]
269 w.calls++
270 if step < 0 {
271 return -1, w.code
272 }
273 take := if step < n { step } else { n }
274 w.got << unsafe { (&u8(buf)).vbytes(take) }
275 return take, 0
276}
277
278fn scripted_write(steps []int, code int, line string) (bool, string, int) {
279 mut w := &ScriptedWrites{
280 steps: steps
281 code: code
282 }
283 ok := channel_write_to(9, line, fn [mut w] (fd int, buf voidptr, n int) (int, int) {
284 return w.write(fd, buf, n)
285 })
286 return ok, w.got.bytestr(), w.calls
287}
288
289fn test_channel_write_interrupted_is_taken_again() {
290 // EINTR before anything went out, and again part way: the line still
291 // goes out whole, in order, nothing twice
292 ok, got, calls := scripted_write([-1, 3, -1, 2], C.EINTR, '{"a":1}\n')
293 assert ok
294 assert got == '{"a":1}\n'
295 assert calls == 5
296}
297
298fn test_channel_write_short_writes_add_up() {
299 ok, got, _ := scripted_write([1, 1, 1, 1, 1, 1, 1], 0, '{"b":22}\n')
300 assert ok
301 assert got == '{"b":22}\n'
302}
303
304fn test_channel_write_without_progress_fails() {
305 // a write that answers nothing would loop forever: it is a failure, at
306 // once, whatever went out before it
307 ok, got, calls := scripted_write([2, 0], 0, '{"c":3}\n')
308 assert !ok
309 assert got == '{"'
310 assert calls == 2
311}
312
313fn test_channel_write_other_errors_fail() {
314 // a reader that is gone (EPIPE) is no interruption: no retry
315 ok, _, calls := scripted_write([-1], 32, '{}\n')
316 assert !ok
317 assert calls == 1
318}
319
320fn test_transaction_event_shapes() ! {
321 // the listing a go-ahead is asked for: its packages whole, the sizes
322 // summed by whoever built it, and preview said either way so a reader
323 // never guesses whether a question follows
324 ev := TransactionEvent{
325 action: 'upgrade'
326 packages: [
327 TransPkg{
328 name: 'foo'
329 version: '2.0-1'
330 old_version: '1.0-1'
331 download_size: 10
332 installed_size: 30
333 },
334 TransPkg{
335 name: 'new'
336 version: '1.0-1'
337 },
338 ]
339 download_size: 10
340 installed_size: 30
341 }
342 m := json2.decode[json2.Any](json2.encode(ev))!.as_map()
343 assert m['type']!.str() == 'transaction'
344 assert m['action']!.str() == 'upgrade'
345 assert m['download_size']!.i64() == 10 && m['installed_size']!.i64() == 30
346 assert !m['preview']!.bool()
347 pkgs := m['packages']!.as_array().map(it.as_map())
348 assert pkgs.len == 2
349 assert pkgs[0]['name']!.str() == 'foo' && pkgs[0]['old_version']!.str() == '1.0-1'
350 assert pkgs[0]['download_size']!.i64() == 10 && pkgs[0]['installed_size']!.i64() == 30
351 // a package that was not installed before has an empty old version,
352 // present all the same: every package has the same keys
353 assert pkgs[1]['old_version']!.str() == ''
354 assert pkgs[1].keys() == pkgs[0].keys()
355 // a preview is the same event with the mark set
356 mut preview := ev
357 preview.preview = true
358 assert json2.decode[json2.Any](json2.encode(preview))!.as_map()['preview']!.bool()
359 // a transaction of nothing still carries its list, empty
360 empty := json2.decode[json2.Any](json2.encode(TransactionEvent{ action: 'remove' }))!.as_map()
361 assert empty['packages']!.as_array().len == 0
362 assert empty['download_size']!.i64() == 0
363 // sizes past 32 bits travel whole
364 big := json2.decode[json2.Any](json2.encode(TransactionEvent{
365 action: 'install'
366 download_size: i64(6) * 1024 * 1024 * 1024
367 installed_size: i64(20) * 1024 * 1024 * 1024
368 }))!.as_map()
369 assert big['download_size']!.i64() == i64(6) * 1024 * 1024 * 1024
370 assert big['installed_size']!.i64() == i64(20) * 1024 * 1024 * 1024
371 // the packages event beside it has the same package shape
372 shown := json2.decode[json2.Any](json2.encode(PackagesEvent{
373 title: '1 packages to remove:'
374 packages: [TransPkg{
375 name: 'old'
376 version: '1.0-1'
377 }]
378 }))!.as_map()
379 assert shown['type']!.str() == 'packages'
380 assert shown['packages']!.as_array()[0].as_map().keys() == pkgs[0].keys()
381 // a provides event names its files only when it has some to name
382 assert json2.encode(ProvidesEvent{
383 path: '/usr/bin/x'
384 fields: ['name']
385 }) == '{"type":"provides","path":"/usr/bin/x","fields":["name"],"entries":[]}'
386 assert json2.encode(ProvidesEvent{
387 path: 'x'
388 fields: ['name']
389 entries: [ListEntry{
390 name: 'p'
391 values: ['p']
392 }]
393 files: [['usr/bin/x']]
394 }).ends_with(',"files":[["usr/bin/x"]]}')
395}
396