vpac / src / frontend_test.v
3568 lines · 3412 sloc · 134.78 KB · 701eb440a294d430492f3cd555ac6c4e0cfa6973
Raw
1module main
2
3import alpm
4import alpm.tests.archivefixtures
5import alpm.tests.httpfixtures
6import alpm.tests.signaturefixtures
7import crypto.sha256
8import encoding.base64
9import json2
10import net.http
11import net.urllib
12import os
13import testdb
14import time
15
16fn C.stat(&char, &C.stat) i32
17
18#include <dlfcn.h>
19#flag linux -ldl
20#flag linux -Wl,--export-dynamic-symbol=gpgme_new
21
22fn C.dlsym(voidptr, &char) voidptr
23
24type FrontendSignatureContext = fn (&&C.gpgme_context) u32
25
26struct FrontendSignatureFault {
27mut:
28 remaining int
29 failures int
30}
31
32const frontend_signature_fault = &FrontendSignatureFault{}
33
34@[export: 'gpgme_new']
35fn frontend_signature_new(context &&C.gpgme_context) u32 {
36 mut state := unsafe { frontend_signature_fault }
37 if state != unsafe { nil } && state.remaining > 0 {
38 state.remaining--
39 state.failures++
40 return u32(C.GPG_ERR_ENOMEM)
41 }
42 symbol := C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'gpgme_new')
43 if symbol == unsafe { nil } { return u32(C.GPG_ERR_GENERAL) }
44 real_new := unsafe { FrontendSignatureContext(symbol) }
45 return real_new(context)
46}
47
48fn test_prepare_conflict_keeps_its_error_kind_after_copying_names() ! {
49 s := fake_system('prepare_conflict_kind')!
50 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
51 testdb.write_local(s.path('db'), [testdb.Pkg{ name: 'old', conflicts: ['new'] }])!
52 s.publish([FakePkg{ name: 'new' }])!
53 handle := alpm.initialize(s.path('root'), s.path('db'))!
54 defer { handle.release() or { went_on('release the alpm handle', err) } }
55 db := handle.register_syncdb('core', 0)!
56 trans_begin(handle, .nolock)!
57 defer { trans_cleanup(handle) }
58 handle.add_pkg(db.get_pkg('new') or { return error('missing new package') })!
59 trans_prepare_checked(handle) or {
60 assert err.code() == int(alpm.Errno.conflicting_deps)
61 assert err.msg().contains('unresolvable package conflicts:')
62 assert err.msg().contains('new and old are in conflict')
63 return
64 }
65 assert false, 'the conflicting transaction was accepted'
66}
67
68#include <stdio_ext.h>
69
70fn C.__fpurge(stream &C.FILE)
71
72fn C.clearerr(stream &C.FILE)
73
74// the modes that commit a transaction, run whole under --ui ipc against a
75// system that lives in a temp dir: a root, a local db, a sync repo served
76// over file:// with real package archives, and a cache. libalpm does every
77// step for real — download, validation, extraction, db writes — and the
78// events the mode sends are read back line by line, as a frontend reads them
79
80// FakePkg is a package of the fake system: its files are paths under the
81// root with their content
82struct FakePkg {
83 name string
84 version string = '1.0-1'
85 reason int // installed ones: 0 explicit, 1 a dependency
86 depends []string
87 provides []string
88 groups []string
89 desc string
90 // changelog is the text the package carries as its changelog, if any
91 changelog string
92 files map[string]string
93}
94
95// FakeSystem is the temp dir a run's whole system lives in
96struct FakeSystem {
97 tmp string
98}
99
100fn fake_system(name string) !FakeSystem {
101 tmp := os.join_path(os.vtmp_dir(), 'vpac_test_frontend_${name}_${os.getpid()}')
102 os.rmdir_all(tmp) or {}
103 // pkgbuild is the build dir the runs point pkgbuild_dir at: it is there,
104 // empty, so a mode that lists the builds reads a dir and not an error
105 for d in ['root', 'db/local', 'db/sync', 'cache', 'repo', 'gpg', 'build', 'dbsrc', 'pkgbuild'] {
106 os.mkdir_all(os.join_path(tmp, d))!
107 }
108 os.write_file(os.join_path(tmp, 'db/local/ALPM_DB_VERSION'), '9\n')!
109 return FakeSystem{
110 tmp: tmp
111 }
112}
113
114fn (s FakeSystem) path(rel string) string {
115 return os.join_path(s.tmp, rel)
116}
117
118// file_list is a package's filelist the way libalpm keeps one: every
119// directory on the way, with its slash, then the files, sorted
120fn file_list(files map[string]string) []string {
121 mut set := map[string]bool{}
122 for f, _ in files {
123 parts := f.split('/')
124 for i in 1 .. parts.len {
125 set[parts[..i].join('/') + '/'] = true
126 }
127 set[f] = true
128 }
129 mut out := set.keys()
130 out.sort()
131 return out
132}
133
134// install_local puts p in the local db as installed, its files on the root
135fn (s FakeSystem) install_local(p FakePkg) ! {
136 // the db entry is the shared writer's; the changelog and the files on
137 // the root are this fake system's own
138 testdb.write_local(s.path('db'), [
139 testdb.Pkg{
140 name: p.name
141 version: p.version
142 reason: p.reason
143 depends: p.depends
144 provides: p.provides
145 groups: p.groups
146 files: file_list(p.files)
147 },
148 ])!
149 if p.changelog != '' {
150 os.write_file(s.path('db/local/${p.name}-${p.version}/changelog'), p.changelog)!
151 }
152 for f, content in p.files {
153 os.mkdir_all(os.dir(s.path('root/${f}')))!
154 os.write_file(s.path('root/${f}'), content)!
155 }
156}
157
158// publish builds an archive of each package into the repo, writes the repo's
159// core.db naming them with their checksums, and puts that db in the sync dir
160// fresh, so no mode asks to update it
161fn (s FakeSystem) publish(pkgs []FakePkg) ! {
162 for p in pkgs {
163 src := s.path('build/${p.name}-${p.version}')
164 os.mkdir_all(src)!
165 mut info := 'pkgname = ${p.name}\npkgbase = ${p.name}\npkgver = ${p.version}\npkgdesc = ${p.name} for a test\narch = any\nsize = 0\n'
166 for d in p.depends {
167 info += 'depend = ${d}\n'
168 }
169 for v in p.provides {
170 info += 'provides = ${v}\n'
171 }
172 for g in p.groups {
173 info += 'group = ${g}\n'
174 }
175 if p.changelog != '' {
176 os.write_file(os.join_path(src, '.CHANGELOG'), p.changelog)!
177 }
178 os.write_file(os.join_path(src, '.PKGINFO'), info)!
179 for f, content in p.files {
180 os.mkdir_all(os.dir(os.join_path(src, f)))!
181 os.write_file(os.join_path(src, f), content)!
182 }
183 file := '${p.name}-${p.version}-any.pkg.tar'
184 tar(s.path('repo/${file}'), src, os.ls(src)!)!
185 text := if p.desc != '' { p.desc } else { '${p.name} for a test' }
186 mut desc := '%FILENAME%\n${file}\n\n%NAME%\n${p.name}\n\n%VERSION%\n${p.version}\n\n%DESC%\n${text}\n\n'
187 desc += '%CSIZE%\n${os.file_size(s.path('repo/${file}'))}\n\n%ISIZE%\n0\n\n'
188 desc += '%SHA256SUM%\n${sha256.hexhash(os.read_file(s.path('repo/${file}'))!)}\n\n%ARCH%\nany\n\n'
189 if p.depends.len > 0 {
190 desc += '%DEPENDS%\n${p.depends.join('\n')}\n\n'
191 }
192 if p.provides.len > 0 {
193 desc += '%PROVIDES%\n${p.provides.join('\n')}\n\n'
194 }
195 if p.groups.len > 0 {
196 desc += '%GROUPS%\n${p.groups.join('\n')}\n\n'
197 }
198 os.mkdir_all(s.path('dbsrc/${p.name}-${p.version}'))!
199 os.write_file(s.path('dbsrc/${p.name}-${p.version}/desc'), desc)!
200 }
201 tar(s.path('repo/core.db'), s.path('dbsrc'), os.ls(s.path('dbsrc'))!)!
202 os.cp(s.path('repo/core.db'), s.path('db/sync/core.db'))!
203 // the file db beside it, the way a repo serves one: each entry's desc and
204 // its file list. it stays on the server until a find -y fetches it
205 for p in pkgs {
206 entry := s.path('filessrc/${p.name}-${p.version}')
207 os.mkdir_all(entry)!
208 os.cp(s.path('dbsrc/${p.name}-${p.version}/desc'), os.join_path(entry, 'desc'))!
209 os.write_file(os.join_path(entry, 'files'), '%FILES%\n${file_list(p.files).join('\n')}\n\n')!
210 }
211 tar(s.path('repo/core.files'), s.path('filessrc'), os.ls(s.path('filessrc'))!)!
212}
213
214fn tar(out string, dir string, entries []string) ! {
215 mut args := ['tar', '-cf', out, '-C', dir]
216 args << entries
217 res := os.exec(args)
218 if res.exit_code != 0 {
219 return error('tar failed: ${res.output}')
220 }
221}
222
223// installed is the local db's name to version, read the way the next
224// command would read it: a fresh handle
225fn (s FakeSystem) installed() !map[string]string {
226 handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
227 defer { handle.release() or {} }
228 // an empty db is no packages; one that cannot be read is an error, not
229 // 'nothing installed' (pkgcache_of tells the two apart by libalpm's errno)
230 mut cache := local_pkgcache(handle)!
231 mut out := map[string]string{}
232 for p in cache.pkgs() {
233 out[p.get_name()] = p.get_version()
234 }
235 return out
236}
237
238fn (s FakeSystem) reason_of(name string) !alpm.PackageReason {
239 handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
240 defer { handle.release() or {} }
241 return (handle.find_local_pkg(name) or { return error('${name} is not installed') }).get_reason()
242}
243
244// FrontendRun is what a mode sent on the channel, decoded, and the error it
245// returned ('' when it returned none)
246struct FrontendRun {
247 events []map[string]json2.Any
248 err string
249 // stdout is what reached fd 1 itself, beside the channel
250 stdout string
251 // failed is how many targets this run reported bad, main's exit status
252 // counting them
253 failed int
254}
255
256fn (r FrontendRun) of(kind string) []map[string]json2.Any {
257 return r.events.filter(it['type'] or { json2.Any('') }.str() == kind)
258}
259
260// done is the run's one done event; it fails when there is not exactly one
261fn (r FrontendRun) done() !map[string]json2.Any {
262 dones := r.of('done')
263 if dones.len != 1 {
264 return error('${dones.len} done events in ${r.events.map(it['type'] or { json2.Any('') }.str())}')
265 }
266 return dones[0]
267}
268
269fn sorted_strs(v json2.Any) []string {
270 mut out := v.as_array().map(it.str())
271 out.sort()
272 return out
273}
274
275// run runs a mode on the system the way a frontend runs vpac: --ui ipc, the
276// events on a channel (a file here), the answers on stdin. the config is
277// aimed at the system — its root and dbs, its cache, its keyring dir, its
278// repo over file:// — and put back at its defaults after, with the ui
279fn (s FakeSystem) run(stdin string, mode fn () !) !FrontendRun {
280 return s.run_ui('ipc', stdin, mode)
281}
282
283// run_ui is run with the ui kind given: 'tty' runs the mode as a terminal
284// sees it, with no channel, its output read back from fd 1
285fn (s FakeSystem) run_ui(kind string, stdin string, mode fn () !) !FrontendRun {
286 chan_path := s.path('channel')
287 out_path := s.path('stdout')
288 mut out_file := os.create(out_path)!
289 saved_out := C.dup(1)
290 if saved_out < 0 {
291 return error('could not save stdout')
292 }
293 in_path := s.path('stdin')
294 os.write_file(in_path, stdin)!
295 mut chan_file := os.create(chan_path)!
296 mut in_file := os.open(in_path)!
297 saved_in := C.dup(0)
298 if saved_in < 0 {
299 return error('could not save stdin')
300 }
301 saved_kind, saved_color, saved_fd := ui_kind, color_flag, ipc_fd
302 // a process-wide count, as main reads it at the end of its one run: each
303 // run here starts from none, and puts the count back after
304 saved_failed := failed_targets
305 failed_targets = 0
306 defer {
307 failed_targets = saved_failed
308 }
309 reset_config()
310 root_path = s.path('root') + '/'
311 db_path = s.path('db') + '/'
312 cfg_cachedirs = [s.path('cache') + '/']
313 cfg_gpgdir = s.path('gpg') + '/'
314 // the machine's own hooks stay out of a fake system's transactions
315 cfg_hookdirs = []string{}
316 // the sandbox user need not exist where the tests run
317 download_user = ''
318 // the pkgbuild builds are the system's own too: never the ones in the
319 // home of whoever runs the tests, which a clean would otherwise look at
320 pkgbuild_dir = s.path('pkgbuild')
321 cfg_repos = [CfgRepo{
322 name: 'core'
323 kind: 'sync'
324 servers: ['file://' + s.path('repo')]
325 }]
326 ui_kind = kind
327 color_flag = 'never'
328 ipc_fd = chan_file.fd
329 C.__fpurge(C.stdin)
330 C.clearerr(C.stdin)
331 C.dup2(in_file.fd, 0)
332 C.fflush(C.stdout)
333 C.dup2(out_file.fd, 1)
334
335 mut msg := ''
336 mode() or { msg = err.msg() }
337
338 C.fflush(C.stdout)
339 C.dup2(saved_out, 1)
340 C.close(saved_out)
341 out_file.close()
342 C.dup2(saved_in, 0)
343 C.close(saved_in)
344 C.__fpurge(C.stdin)
345 C.clearerr(C.stdin)
346 ui_kind, color_flag, ipc_fd = saved_kind, saved_color, saved_fd
347 reset_config()
348 in_file.close()
349 chan_file.close()
350 mut events := []map[string]json2.Any{}
351 for line in os.read_lines(chan_path)! {
352 // every line is one whole json object, or the channel is broken
353 events << json2.decode[json2.Any](line)!.as_map()
354 }
355 return FrontendRun{
356 events: events
357 err: msg
358 stdout: os.read_file(out_path)!
359 failed: failed_targets
360 }
361}
362
363fn (s FakeSystem) lock_left() bool {
364 return os.exists(s.path('db/db.lck'))
365}
366
367fn foo(version string, content string) FakePkg {
368 return FakePkg{
369 name: 'foo'
370 version: version
371 files: {
372 'usr/share/foo/hello': content
373 }
374 }
375}
376
377fn test_upgrade_ends_with_a_done_event() ! {
378 s := fake_system('upgrade')!
379 defer { os.rmdir_all(s.tmp) or {} }
380 s.install_local(foo('1.0-1', 'one'))!
381 s.publish([foo('2.0-1', 'two')])!
382
383 run := s.run('', fn () ! {
384 upgrade(ConfigUpgrade{ noconfirm: true })!
385 })!
386 assert run.err == ''
387 done := run.done()!
388 assert done['action']!.str() == 'upgraded'
389 assert sorted_strs(done['packages']!) == ['foo']
390 // the listing and the go-ahead came first, the done last of them
391 assert run.of('transaction').len == 1
392 assert run.of('question').len == 1
393 // and it happened: the new version is on the root and in the local db
394 assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'two'
395 assert s.installed()! == {
396 'foo': '2.0-1'
397 }
398 assert !s.lock_left()
399}
400
401fn test_upgrade_with_nothing_to_do_sends_no_done() ! {
402 s := fake_system('uptodate')!
403 defer { os.rmdir_all(s.tmp) or {} }
404 s.install_local(foo('1.0-1', 'one'))!
405 s.publish([foo('1.0-1', 'one')])!
406 run := s.run('', fn () ! {
407 upgrade(ConfigUpgrade{ noconfirm: true })!
408 })!
409 assert run.err == ''
410 assert run.of('done').len == 0
411 assert run.of('message').any(it['text']!.str() == 'nothing to upgrade.')
412}
413
414fn test_install_ends_with_a_done_event() ! {
415 s := fake_system('install')!
416 defer { os.rmdir_all(s.tmp) or {} }
417 s.publish([
418 FakePkg{
419 name: 'bar'
420 depends: ['baz']
421 files: {
422 'usr/bin/bar': 'bar'
423 }
424 },
425 FakePkg{
426 name: 'baz'
427 files: {
428 'usr/lib/libbaz': 'baz'
429 }
430 },
431 ])!
432 run := s.run('', fn () ! {
433 install(ConfigInstall{ noconfirm: true, query: ['bar'] })!
434 })!
435 assert run.err == ''
436 done := run.done()!
437 assert done['action']!.str() == 'installed'
438 // the targets: the dependency comes along, but is not one
439 assert sorted_strs(done['packages']!) == ['bar']
440 assert s.installed()! == {
441 'bar': '1.0-1'
442 'baz': '1.0-1'
443 }
444 assert s.reason_of('bar')! == .explicit
445 assert s.reason_of('baz')! == .depend
446 assert os.read_file(s.path('root/usr/bin/bar'))! == 'bar'
447 assert !s.lock_left()
448}
449
450fn test_remove_ends_with_a_done_event() ! {
451 s := fake_system('remove')!
452 defer { os.rmdir_all(s.tmp) or {} }
453 s.install_local(foo('1.0-1', 'one'))!
454 run := s.run('', fn () ! {
455 remove(ConfigRemove{ noconfirm: true, query: ['foo'] })!
456 })!
457 assert run.err == ''
458 done := run.done()!
459 assert done['action']!.str() == 'removed'
460 assert sorted_strs(done['packages']!) == ['foo']
461 assert s.installed()!.len == 0
462 assert !os.exists(s.path('root/usr/share/foo/hello'))
463 assert !s.lock_left()
464}
465
466fn test_autoremove_ends_with_a_done_event() ! {
467 s := fake_system('autoremove')!
468 defer { os.rmdir_all(s.tmp) or {} }
469 s.install_local(FakePkg{
470 name: 'app'
471 depends: ['lib']
472 })!
473 s.install_local(FakePkg{
474 name: 'lib'
475 reason: 1
476 })!
477 s.install_local(FakePkg{
478 name: 'orphan'
479 reason: 1
480 })!
481 // an orphan whose own dependency becomes unneeded with it: the recurse
482 // takes it along, and the done event names it with the rest
483 s.install_local(FakePkg{
484 name: 'stray'
485 reason: 1
486 depends: ['leaf']
487 })!
488 s.install_local(FakePkg{
489 name: 'leaf'
490 reason: 1
491 })!
492 run := s.run('', fn () ! {
493 autoremove(ConfigAutoRemove{ noconfirm: true })!
494 })!
495 assert run.err == ''
496 done := run.done()!
497 assert done['action']!.str() == 'removed'
498 assert sorted_strs(done['packages']!) == ['leaf', 'orphan', 'stray']
499 // the text line of a terminal is not sent beside it
500 assert !run.of('message').any(it['text']!.str().contains('orphaned packages'))
501 mut left := s.installed()!.keys()
502 left.sort()
503 assert left == ['app', 'lib']
504 assert !s.lock_left()
505}
506
507fn test_mark_ends_with_a_done_event() ! {
508 s := fake_system('mark')!
509 defer { os.rmdir_all(s.tmp) or {} }
510 s.install_local(foo('1.0-1', 'one'))!
511 run := s.run('', fn () ! {
512 mark(ConfigMark{ reason: 'd', query: ['foo'] })!
513 })!
514 assert run.err == ''
515 done := run.done()!
516 assert done['action']!.str() == 'marked'
517 assert done['reason']!.str() == 'depend'
518 assert sorted_strs(done['packages']!) == ['foo']
519 assert s.reason_of('foo')! == .depend
520 assert !s.lock_left()
521}
522
523fn test_mark_preserves_legacy_md5_verification_history() ! {
524 s := fake_system('mark_legacy_md5')!
525 defer { os.rmdir_all(s.tmp) or { went_on('remove test root', err) } }
526 s.install_local(foo('1.0-1', 'one'))!
527 desc := s.path('db/local/foo-1.0-1/desc')
528 os.write_file(desc, os.read_file(desc)! + '%VALIDATION%\nmd5\nsha256\npgp\n\n')!
529 run := s.run('', fn () ! {
530 mark(ConfigMark{ reason: 'd', query: ['foo'] })!
531 })!
532 assert run.err == '', run.err
533 assert s.reason_of('foo')! == .depend
534 recorded := os.read_file(desc)!
535 assert recorded.contains('\nmd5\n')
536 assert recorded.contains('\nsha256\n')
537 assert recorded.contains('\npgp\n')
538 assert !s.lock_left()
539}
540
541fn test_declined_transaction_sends_no_done() ! {
542 s := fake_system('decline')!
543 defer { os.rmdir_all(s.tmp) or {} }
544 s.install_local(foo('1.0-1', 'one'))!
545 // the frontend says no to the go-ahead, question 1
546 run := s.run('{"id": 1, "answer": false}\n', fn () ! {
547 remove(ConfigRemove{ query: ['foo'] })!
548 })!
549 assert run.err == ''
550 questions := run.of('question')
551 assert questions.len == 1
552 assert questions[0]['question']!.str() == 'proceed'
553 assert run.of('done').len == 0
554 // nothing changed, and the transaction let go of the lock
555 assert s.installed()! == {
556 'foo': '1.0-1'
557 }
558 assert os.exists(s.path('root/usr/share/foo/hello'))
559 assert !s.lock_left()
560}
561
562fn test_print_preview_sends_no_done() ! {
563 s := fake_system('preview')!
564 defer { os.rmdir_all(s.tmp) or {} }
565 s.install_local(foo('1.0-1', 'one'))!
566 s.publish([foo('2.0-1', 'two')])!
567 run := s.run('', fn () ! {
568 upgrade(ConfigUpgrade{ print_only: true })!
569 })!
570 assert run.err == ''
571 listing := run.of('transaction')
572 assert listing.len == 1
573 assert listing[0]['preview']!.bool()
574 assert run.of('done').len == 0
575 assert run.of('question').len == 0
576 assert s.installed()! == {
577 'foo': '1.0-1'
578 }
579 assert !s.lock_left()
580}
581
582fn test_prepare_failure_sends_no_done_and_lets_go_of_the_lock() ! {
583 s := fake_system('prepare')!
584 defer { os.rmdir_all(s.tmp) or {} }
585 // a dependency no repo has: prepare fails, and says on what
586 s.publish([FakePkg{
587 name: 'needy'
588 depends: ['nowhere']
589 }])!
590 run := s.run('', fn () ! {
591 install(ConfigInstall{ noconfirm: true, query: ['needy'] })!
592 })!
593 assert run.err != ''
594 assert run.err.contains('nowhere'), run.err
595 assert run.of('done').len == 0
596 assert s.installed()!.len == 0
597 assert !s.lock_left()
598}
599
600// an empty local db is a db with no packages, not a broken one: the modes
601// that read it answer nothing found, as pacman does on a fresh root (the
602// install above runs on one too)
603fn test_an_empty_system_is_no_error() ! {
604 s := fake_system('empty')!
605 defer { os.rmdir_all(s.tmp) or {} }
606 s.publish([foo('1.0-1', 'one')])!
607 orphaned := s.run('', fn () ! {
608 orphans(ConfigOrphans{})!
609 })!
610 assert orphaned.err == ''
611 verified := s.run('', fn () ! {
612 verify(ConfigVerify{})!
613 })!
614 assert verified.err == ''
615 searched := s.run('', fn () ! {
616 search(ConfigSearch{ local: true, query: ['foo'] })!
617 })!
618 assert searched.err == ''
619 // a name to act on is unknown, said so, not a database failure: mark
620 // and remove report it as the bad target it is
621 marked := s.run('', fn () ! {
622 mark(ConfigMark{ reason: 'd', query: ['foo'] })!
623 })!
624 assert marked.err == '' && marked.failed == 1
625 assert marked.of('error')[0]['msg']!.str().contains('unknown package')
626 assert !s.lock_left()
627 removed := s.run('', fn () ! {
628 remove(ConfigRemove{ noconfirm: true, query: ['foo'] })!
629 })!
630 assert removed.err == '' && removed.failed == 1
631 assert removed.of('error')[0]['msg']!.str().contains('unknown package')
632 assert !s.lock_left()
633}
634
635fn test_pkgcache_of() ! {
636 s := fake_system('pkgcache')!
637 defer { os.rmdir_all(s.tmp) or {} }
638 handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
639 // empty: a nil list, which reads as no packages
640 mut empty := local_pkgcache(handle)!
641 assert empty == unsafe { nil }
642 assert empty.pkgs().len == 0
643 assert empty.pkg_find('foo') == none
644 handle.release()!
645
646 s.install_local(foo('1.0-1', 'one'))!
647 full_handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
648 mut full := local_pkgcache(full_handle)!
649 assert full.pkgs().map(it.get_name()) == ['foo']
650 full_handle.release()!
651
652 if os.geteuid() == 0 {
653 // root reads the unreadable dir below anyway
654 return
655 }
656 // a db libalpm cannot read is still an error, with libalpm's reason. the
657 // handle opens first: libalpm reads the packages only when asked
658 broken := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
659 defer { broken.release() or {} }
660 os.chmod(s.path('db/local'), 0)!
661 defer { os.chmod(s.path('db/local'), 0o755) or {} }
662 if mut got := local_pkgcache(broken) {
663 assert false, 'an unreadable local db read as ${got.pkgs().len} packages'
664 } else {
665 assert err.msg().starts_with('could not read the packages of local: '), err.msg()
666 }
667}
668
669fn test_url_install_through_the_install_handle() ! {
670 s := fake_system('url')!
671 defer { os.rmdir_all(s.tmp) or {} }
672 s.publish([foo('1.0-1', 'one')])!
673 url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar')
674 run := s.run('', fn [url] () ! {
675 install(ConfigInstall{ noconfirm: true, query: [url] })!
676 })!
677 assert run.err == ''
678 done := run.done()!
679 assert done['action']!.str() == 'installed'
680 assert sorted_strs(done['packages']!) == ['foo']
681 assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'one'
682 // the trust warning is a warning to a frontend, and comes before the
683 // download it is about, which comes before the transaction
684 kinds := run.events.map(it['type']!.str())
685 warned := run.events.filter(it['type']!.str() == 'message'
686 && it['text']!.str().contains('signature'))
687 assert warned.len == 1
688 assert warned[0]['warning']!.bool()
689 first_warning := run.events.index(warned[0])
690 first_download := kinds.index('download')
691 assert first_download > first_warning
692 assert kinds.index('transaction') > first_download
693 assert run.of('download').any(it['file']!.str().starts_with('foo-1.0-1-any.pkg.tar'))
694 // the archive was fetched into the cache, as libalpm fetches one
695 assert os.exists(s.path('cache/foo-1.0-1-any.pkg.tar'))
696 assert !s.lock_left()
697}
698
699fn test_url_install_refuses_a_bad_signature_beside_it() ! {
700 s := fake_system('urlsig')!
701 defer { os.rmdir_all(s.tmp) or {} }
702 s.publish([foo('1.0-1', 'one')])!
703 // the server offers a signature that does not hold: libalpm fetches it
704 // with the archive, and the load at the remote level reads it
705 os.write_file(s.path('repo/foo-1.0-1-any.pkg.tar.sig'), 'not a signature')!
706 url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar')
707 run := s.run('', fn [url] () ! {
708 install(ConfigInstall{ noconfirm: true, query: [url] })!
709 })!
710 assert run.err.contains('signature'), run.err
711 assert run.of('done').len == 0
712 assert s.installed()!.len == 0
713 assert !os.exists(s.path('root/usr/share/foo/hello'))
714 assert !s.lock_left()
715}
716
717fn test_url_install_uses_the_next_cache_after_a_file_and_reports_warnings() ! {
718 s := fake_system('url_cache_file')!
719 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
720 s.publish([foo('1.0-1', 'one')])!
721 bad_cache := s.path('bad-cache')
722 good_cache := s.path('cache')
723 os.write_file(bad_cache, 'keep this file')!
724 url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar')
725 run := s.run('', fn [url, bad_cache, good_cache] () ! {
726 cfg_cachedirs = [bad_cache, good_cache]
727 install(ConfigInstall{ noconfirm: true, query: [url] })!
728 })!
729 assert run.err == '', run.err
730 assert run.done()!['action']!.str() == 'installed'
731 assert os.read_file(bad_cache)! == 'keep this file'
732 assert os.exists(s.path('cache/foo-1.0-1-any.pkg.tar'))
733 assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'one'
734 created := run.events.filter(it['type']!.str() == 'message' && it['text']!.str().contains('cache exists, creating'))
735 assert created.len > 0
736 assert created.all(it['warning']!.bool())
737 lookups := run.events.filter(it['type']!.str() == 'message' && it['text']!.str().contains("could not open '${bad_cache}/"))
738 assert lookups.len > 0
739 assert lookups.all(it['warning']!.bool())
740 kinds := run.events.map(it['type']!.str())
741 assert kinds.index('download') > run.events.index(created[0])
742 assert !s.lock_left()
743}
744
745fn test_find_refresh_takes_the_full_handle() ! {
746 s := fake_system('findhandle')!
747 defer { os.rmdir_all(s.tmp) or {} }
748 run := s.run('', fn () ! {
749 // a sandbox user that exists wherever the test runs: this one
750 download_user = current_user()!
751 mut ui := new_trans_ui()
752 refresh := find_handle(mut ui, true)!
753 defer { refresh.release() or {} }
754 // the refresh downloads as the sandbox user, from the file dbs
755 if refresh.option_get_sandboxuser() != download_user {
756 return error('a refresh downloads as "${refresh.option_get_sandboxuser()}"')
757 }
758 if refresh.option_get_dbext() != '.files' {
759 return error('a refresh reads ${refresh.option_get_dbext()}')
760 }
761 read := find_handle(mut ui, false)!
762 defer { read.release() or {} }
763 if read.option_get_dbext() != '.files' {
764 return error('a lookup reads ${read.option_get_dbext()}')
765 }
766 })!
767 assert run.err == ''
768}
769
770fn test_find_refresh_fetches_the_file_dbs() ! {
771 s := fake_system('findrefresh')!
772 defer { os.rmdir_all(s.tmp) or {} }
773 s.publish([FakePkg{
774 name: 'bar'
775 files: {
776 'usr/bin/bar': 'bar'
777 }
778 }])!
779 assert !os.exists(s.path('db/sync/core.files'))
780 run := s.run('', fn () ! {
781 find(ConfigFind{ refresh: true, query: ['/usr/bin/bar'] })!
782 })!
783 assert run.err == ''
784 // fetched through the full handle: its progress reached the frontend
785 assert run.of('download').any(it['file']!.str().starts_with('core.files'))
786 assert os.exists(s.path('db/sync/core.files'))
787 // and read: the repo package that provides the path
788 provides := run.of('provides')
789 assert provides.len == 1
790 entries := provides[0]['entries']!.as_array()
791 assert entries.len == 1
792 assert entries[0].as_map()['name']!.str() == 'bar'
793}
794
795// verify_lines runs the fast check on the system, with the NoExtract globs
796// given, and returns its report: the lines, and how many packages are bad
797fn (s FakeSystem) verify_lines(noextract []string) !([]string, int) {
798 run := s.run('', fn [noextract] () ! {
799 cfg_noextract = noextract.clone()
800 verify(ConfigVerify{})!
801 })!
802 if run.err != '' {
803 return error(run.err)
804 }
805 events := run.of('verify')
806 if events.len != 1 {
807 return error('${events.len} verify events')
808 }
809 lines := events[0]['lines']!.as_array().map(it.as_map()['text']!.str())
810 return lines, events[0]['bad']!.int()
811}
812
813fn test_verify_fast_check_as_pacman() ! {
814 s := fake_system('verify')!
815 defer { os.rmdir_all(s.tmp) or {} }
816 s.install_local(FakePkg{
817 name: 'docs'
818 files: {
819 'usr/bin/docs': 'docs'
820 'usr/share/man/man1/docs.1': 'man'
821 'usr/share/doc/docs/README.md': 'readme'
822 }
823 })!
824 s.install_local(FakePkg{
825 name: 'dirs'
826 files: {
827 'usr/share/dirs/a': 'a'
828 }
829 })!
830 s.install_local(FakePkg{
831 name: 'intact'
832 files: {
833 'usr/lib/intact': 'ok'
834 }
835 })!
836 // a man page NoExtract kept off the disk, and a binary that is gone
837 os.rm(s.path('root/usr/share/man/man1/docs.1'))!
838 os.rm(s.path('root/usr/bin/docs'))!
839 // a directory the db lists, now a link to one elsewhere: the file in it
840 // is still reached through the link
841 os.mkdir_all(s.path('root/usr/share/elsewhere'))!
842 os.write_file(s.path('root/usr/share/elsewhere/a'), 'a')!
843 os.rmdir_all(s.path('root/usr/share/dirs'))!
844 os.symlink('elsewhere', s.path('root/usr/share/dirs'))!
845
846 lines, bad := s.verify_lines(['usr/share/man/*'])!
847 root := s.path('root')
848 assert bad == 2, lines.str()
849 assert 'docs: missing ${root}/usr/bin/docs' in lines
850 assert 'dirs: ${root}/usr/share/dirs/ is a link, the db says a directory' in lines
851 // NoExtract's file is not missing, and not said at all, as in pacman
852 assert !lines.any(it.contains('docs.1')), lines.str()
853 assert !lines.any(it.starts_with('intact')), lines.str()
854 assert lines.len == 2, lines.str()
855
856 // without the NoExtract glob, the man page is missing like any file
857 lines2, bad2 := s.verify_lines([])!
858 assert bad2 == 2
859 assert 'docs: missing ${root}/usr/share/man/man1/docs.1' in lines2
860}
861
862fn test_verify_fast_check_lets_links_be() ! {
863 s := fake_system('verifylinks')!
864 defer { os.rmdir_all(s.tmp) or {} }
865 s.install_local(FakePkg{
866 name: 'linked'
867 files: {
868 'usr/lib/libx.so.1': 'lib'
869 'usr/lib/libx.so': ''
870 'usr/lib/dangling': ''
871 }
872 })!
873 // a package's file may be a link, to its neighbour or to nothing at all
874 os.rm(s.path('root/usr/lib/libx.so'))!
875 os.symlink('libx.so.1', s.path('root/usr/lib/libx.so'))!
876 os.rm(s.path('root/usr/lib/dangling'))!
877 os.symlink('nowhere', s.path('root/usr/lib/dangling'))!
878 lines, bad := s.verify_lines([])!
879 assert bad == 0, lines.str()
880 assert lines.len == 0
881}
882
883// fake_pkg is a FakePkg with no files, at a version, with its dependencies
884fn fake_pkg(name string, version string, depends []string) FakePkg {
885 return FakePkg{
886 name: name
887 version: version
888 depends: depends
889 }
890}
891
892fn test_install_upgrades_the_whole_outdated_closure() ! {
893 // app needs mid, mid needs low: both installed, both outdated. the walk
894 // is the dependency closure, not one level of it
895 s := fake_system('closure')!
896 defer { os.rmdir_all(s.tmp) or {} }
897 s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })!
898 s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })!
899 s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']),
900 fake_pkg('low', '2.0-1', [])])!
901 run := s.run('', fn () ! {
902 install(ConfigInstall{ noconfirm: true, query: ['app'] })!
903 })!
904 assert run.err == ''
905 assert s.installed()! == {
906 'app': '1.0-1'
907 'mid': '2.0-1'
908 'low': '2.0-1'
909 }
910 // what came along is still a dependency
911 assert s.reason_of('mid')! == .depend
912}
913
914fn test_install_no_upgrade_deps_leaves_the_closure() ! {
915 s := fake_system('noclosure')!
916 defer { os.rmdir_all(s.tmp) or {} }
917 s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })!
918 s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })!
919 s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']),
920 fake_pkg('low', '2.0-1', [])])!
921 run := s.run('', fn () ! {
922 install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })!
923 })!
924 assert run.err == ''
925 assert s.installed()! == {
926 'app': '1.0-1'
927 'mid': '1.0-1'
928 'low': '1.0-1'
929 }
930}
931
932fn test_install_brings_along_what_it_would_break() ! {
933 // user needs lib below 2.0; installing lib 2.0 breaks it, so the repo's
934 // user, which takes the new lib, comes along in the same transaction
935 s := fake_system('broken')!
936 defer { os.rmdir_all(s.tmp) or {} }
937 s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))!
938 s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
939 s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])!
940 run := s.run('', fn () ! {
941 install(ConfigInstall{ noconfirm: true, query: ['lib'] })!
942 })!
943 assert run.err == ''
944 assert s.installed()! == {
945 'lib': '2.0-1'
946 'user': '2.0-1'
947 }
948 // the transaction listed it before the go-ahead
949 listing := run.of('transaction')
950 assert listing.len == 1
951}
952
953fn test_no_upgrade_deps_failure_says_what_breaks() ! {
954 // --no-upgrade-deps keeps an installed package that needs the old lib at
955 // its version: prepare fails on it, and the hint names the cause
956 s := fake_system('noupbreak')!
957 defer { os.rmdir_all(s.tmp) or {} }
958 s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))!
959 s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
960 s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])!
961 run := s.run('', fn () ! {
962 install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['lib'] })!
963 })!
964 lines := run.err.split('\n')
965 assert lines[0] == 'could not satisfy dependencies:', run.err
966 assert lines[1] == " lib breaks dependency 'lib<2.0' required by user", run.err
967 assert lines[2].starts_with('without --no-upgrade-deps, the installed packages this breaks are upgraded along'), run.err
968 assert s.installed()!['lib']! == '1.0-1'
969 assert !s.lock_left()
970}
971
972fn test_no_upgrade_deps_still_takes_a_newer_dependency() ! {
973 // a target that needs a newer dependency than is installed gets it even
974 // under --no-upgrade-deps: libalpm's prepare pulls it in, which is why
975 // the hint never blames this case
976 s := fake_system('noupnewer')!
977 defer { os.rmdir_all(s.tmp) or {} }
978 s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
979 s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('app', '1.0-1', ['lib>=2.0'])])!
980 run := s.run('', fn () ! {
981 install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })!
982 })!
983 assert run.err == ''
984 assert s.installed()! == {
985 'app': '1.0-1'
986 'lib': '2.0-1'
987 }
988}
989
990fn test_mark_failure_names_what_was_set() ! {
991 if os.geteuid() == 0 {
992 // root writes the read-only desc below anyway
993 return
994 }
995 s := fake_system('markfail')!
996 defer { os.rmdir_all(s.tmp) or {} }
997 for name in ['aa', 'bb', 'cc'] {
998 s.install_local(fake_pkg(name, '1.0-1', []))!
999 }
1000 // bb's db entry cannot be written: its reason cannot change
1001 os.chmod(s.path('db/local/bb-1.0-1/desc'), 0o444)!
1002 run := s.run('', fn () ! {
1003 mark(ConfigMark{ reason: 'd', query: ['aa', 'bb', 'cc'] })!
1004 })!
1005 assert run.err.starts_with('could not set the install reason of bb: '), run.err
1006 assert run.err.ends_with(' (already set: aa)'), run.err
1007 assert run.of('done').len == 0
1008 // what the error says is what the db holds
1009 assert s.reason_of('aa')! == .depend
1010 assert s.reason_of('bb')! == .explicit
1011 assert s.reason_of('cc')! == .explicit
1012 assert !s.lock_left()
1013}
1014
1015fn test_provider_question_under_a_frontend() ! {
1016 // app needs a shell two repo packages provide: libalpm asks which, the
1017 // frontend gets the providers as the choices, and the answer is what is
1018 // installed
1019 s := fake_system('provider')!
1020 defer { os.rmdir_all(s.tmp) or {} }
1021 s.publish([fake_pkg('app', '1.0-1', ['shell']),
1022 FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['shell'] },
1023 FakePkg{ ...fake_pkg('dash', '1.0-1', []), provides: ['shell'] }])!
1024 // the frontend picks the second provider of question 1
1025 run := s.run('{"id": 1, "answer": 1}\n{"id": 2, "answer": true}\n', fn () ! {
1026 install(ConfigInstall{ query: ['app'] })!
1027 })!
1028 assert run.err == ''
1029 questions := run.of('question')
1030 assert questions.len == 2
1031 assert questions[0]['question']!.str() == 'choose'
1032 assert questions[0]['msg']!.str() == '2 providers for shell'
1033 choices := questions[0]['choices']!.as_array().map(it.str())
1034 assert choices.len == 2
1035 assert choices.all(it.starts_with('core/') && it.ends_with(' 1.0-1'))
1036 chosen := choices[1].all_after('/').all_before(' ')
1037 assert questions[1]['question']!.str() == 'proceed'
1038 installed := s.installed()!
1039 assert chosen in installed && installed.len == 2, installed.str()
1040 assert 'app' in installed
1041}
1042
1043fn test_provider_rows_number_the_choices() ! {
1044 s := fake_system('providerrows')!
1045 defer { os.rmdir_all(s.tmp) or {} }
1046 s.publish([fake_pkg('bash', '1.0-1', []), fake_pkg('dash', '2.0-1', [])])!
1047 run := s.run('', fn () ! {
1048 mut handle := init_handle(new_trans_ui())!
1049 defer { handle.release() or {} }
1050 dbs := init_repos(mut handle)!
1051 bash := dbs[0].get_pkg('bash') or { return error('no bash') }
1052 dash := dbs[0].get_pkg('dash') or { return error('no dash') }
1053 if provider_choice(dash) != 'core/dash 2.0-1' {
1054 return error('choice ${provider_choice(dash)}')
1055 }
1056 text := table_text(provider_rows([bash, dash]), '', ' ')
1057 if text.split('\n').map(it.trim_space()) != ['1) core/bash 1.0-1', '2) core/dash 2.0-1'] {
1058 return error('rows ${text}')
1059 }
1060 })!
1061 assert run.err == ''
1062}
1063
1064fn test_fuzzy_search_lists_name_matches_then_desc_matches_once() ! {
1065 s := fake_system('fuzzy')!
1066 defer { os.rmdir_all(s.tmp) or {} }
1067 s.publish([FakePkg{
1068 ...fake_pkg('zsh', '1.0-1', [])
1069 desc: 'zsh is the z shell'
1070 }, FakePkg{
1071 ...fake_pkg('fish', '1.0-1', [])
1072 desc: 'a friendly shell, much like zsh'
1073 }, FakePkg{
1074 ...fake_pkg('bash', '1.0-1', [])
1075 desc: 'the gnu bourne again shell'
1076 }, FakePkg{
1077 ...fake_pkg('zsh-doc', '1.0-1', [])
1078 desc: 'documentation'
1079 }])!
1080 run := s.run('', fn () ! {
1081 mut handle := init_handle(new_trans_ui())!
1082 defer { handle.release() or {} }
1083 dbs := init_repos(mut handle)!
1084 mut cache := pkgcache_of(handle, dbs[0])!
1085 got := build_matches(cache.pkgs(), ConfigSearch{
1086 fuzzy: true
1087 thold: 0.9
1088 query: ['zsh']
1089 }).map(it.get_name())
1090 // zsh by its name (and not again for its desc), then fish by its desc;
1091 // bash matches neither, and zsh-doc's name is too far at this threshold
1092 if got != ['zsh', 'fish'] {
1093 return error('matched ${got}')
1094 }
1095 })!
1096 assert run.err == ''
1097}
1098
1099// with_file_dbs publishes the packages with their file db already synced,
1100// as a find without -y reads it
1101fn with_file_dbs(name string, pkgs []FakePkg) !FakeSystem {
1102 s := fake_system(name)!
1103 s.publish(pkgs)!
1104 os.cp(s.path('repo/core.files'), s.path('db/sync/core.files'))!
1105 return s
1106}
1107
1108// providers_of maps each path a find answered to the packages it named
1109fn providers_of(run FrontendRun) map[string][]string {
1110 mut out := map[string][]string{}
1111 for e in run.of('provides') {
1112 mut names := e['entries']!.as_array().map(it.as_map()['name']!.str())
1113 names.sort()
1114 out[e['path']!.str()] = names
1115 }
1116 return out
1117}
1118
1119fn test_find_owner_index_answers_as_the_walk() ! {
1120 s := with_file_dbs('findowner', [
1121 FakePkg{
1122 name: 'bar'
1123 files: {
1124 'usr/bin/bar': 'bar'
1125 }
1126 },
1127 FakePkg{
1128 name: 'baz'
1129 files: {
1130 'usr/bin/baz': 'baz'
1131 'usr/lib/libbaz': 'lib'
1132 }
1133 },
1134 ])!
1135 defer { os.rmdir_all(s.tmp) or {} }
1136 paths := ['/usr/bin/bar', 'usr/lib/libbaz', '/usr/bin/', '/usr/bin', '/nope']
1137 // several paths at once go through the index
1138 many := s.run('', fn [paths] () ! {
1139 find(ConfigFind{ query: paths })!
1140 })!
1141 got := providers_of(many)
1142 assert got['/usr/bin/bar']! == ['bar']
1143 assert got['usr/lib/libbaz']! == ['baz']
1144 // a directory is every package's that carries it, with or without its slash
1145 assert got['/usr/bin/']! == ['bar', 'baz']
1146 assert got['/usr/bin']! == ['bar', 'baz']
1147 // the miss is named, as a target error, and counted
1148 misses := many.of('error').filter(it['target']!.bool())
1149 assert misses.len == 1
1150 assert misses[0]['msg']!.str() == 'no package provides /nope'
1151 // one path at a time walks the filelists: the same answers
1152 for p in paths {
1153 one := s.run('', fn [p] () ! {
1154 find(ConfigFind{ query: [p] })!
1155 })!
1156 assert providers_of(one)[p] or { []string{} } == got[p] or { []string{} }, p
1157 }
1158}
1159
1160fn test_find_list_names_its_misses() ! {
1161 s := with_file_dbs('findlist', [FakePkg{
1162 name: 'bar'
1163 files: {
1164 'usr/bin/bar': 'bar'
1165 }
1166 }])!
1167 defer { os.rmdir_all(s.tmp) or {} }
1168 run := s.run('', fn () ! {
1169 find(ConfigFind{ list: true, query: ['bar', 'nothere'] })!
1170 })!
1171 lists := run.of('files')
1172 assert lists.len == 1
1173 assert lists[0]['package']!.str() == 'bar'
1174 assert lists[0]['repo']!.str() == 'core'
1175 assert lists[0]['paths']!.as_array().map(it.str()) == ['usr/', 'usr/bin/', 'usr/bin/bar']
1176 misses := run.of('error').filter(it['target']!.bool())
1177 assert misses.len == 1
1178 assert misses[0]['msg']!.str().contains('nothere')
1179}
1180
1181// stale_after_update updates the sync dbs over file:// and answers what
1182// the freshness check then calls stale
1183fn (s FakeSystem) stale_after_update() !FrontendRun {
1184 return s.run('', fn () ! {
1185 mut handle := init_handle(new_trans_ui())!
1186 defer { handle.release() or {} }
1187 init_repos(mut handle)!
1188 update_repos(mut handle, false)!
1189 stale := stale_sync_dbs(handle)
1190 report('stale: ${stale.join(',')}')
1191 })!
1192}
1193
1194fn test_sync_stamp_keeps_an_old_server_time_fresh() ! {
1195 s := fake_system('stamp')!
1196 defer { os.rmdir_all(s.tmp) or {} }
1197 s.publish([foo('1.0-1', 'one')])!
1198 // the server's db has not changed in two days: libalpm gives the copy
1199 // it downloads the server's time, so only vpac's stamp says it is current
1200 two_days_ago := time.now().unix() - 2 * sync_max_age
1201 os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)!
1202 os.rm(s.path('db/sync/core.db'))!
1203 run := s.stale_after_update()!
1204 assert run.err == ''
1205 assert os.file_last_mod_unix(s.path('db/sync/core.db')) <= two_days_ago + 1
1206 assert os.exists(s.path('db/sync/vpac.synced'))
1207 assert run.of('message').any(it['text']!.str() == 'stale: ')
1208}
1209
1210fn test_sync_stamp_that_cannot_be_written_is_said() ! {
1211 s := fake_system('stampfail')!
1212 defer { os.rmdir_all(s.tmp) or {} }
1213 s.publish([foo('1.0-1', 'one')])!
1214 two_days_ago := time.now().unix() - 2 * sync_max_age
1215 os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)!
1216 os.rm(s.path('db/sync/core.db'))!
1217 // the stamp's path leads nowhere writable: its write fails, and no stamp
1218 // is there after it (a link into a directory that does not exist)
1219 os.symlink(s.path('nowhere/vpac.synced'), s.path('db/sync/vpac.synced'))!
1220 run := s.stale_after_update()!
1221 assert run.err == ''
1222 // said, as a warning naming the stamp, and the db counts stale again —
1223 // touching the db instead would feed libalpm's If-Modified-Since a lie
1224 warned := run.of('message').filter(it['warning'] or { json2.Any(false) }.bool())
1225 assert warned.len == 1
1226 assert warned[0]['text']!.str().starts_with('could not write the sync stamp ${s.path('db/sync/vpac.synced')}')
1227 assert run.of('message').any(it['text']!.str() == 'stale: core')
1228}
1229
1230fn test_libalpm_warnings_reach_the_frontend() ! {
1231 // installing what is installed already: libalpm says so at warning level,
1232 // through its log callback alone, as pacman prints it
1233 s := fake_system('alpmwarn')!
1234 defer { os.rmdir_all(s.tmp) or {} }
1235 s.install_local(foo('1.0-1', 'one'))!
1236 s.publish([foo('1.0-1', 'one')])!
1237 run := s.run('', fn () ! {
1238 install(ConfigInstall{ noconfirm: true, query: ['foo'] })!
1239 })!
1240 assert run.err == ''
1241 said := run.of('message').filter(it['text']!.str() == 'foo-1.0-1 is up to date -- reinstalling')
1242 assert said.len == 1, run.of('message').str()
1243 assert said[0]['warning']!.bool()
1244 assert 'error' !in said[0]
1245}
1246
1247fn test_libalpm_errors_reach_the_frontend() ! {
1248 // a corrupt mtree: libalpm's error names the file and libarchive's reason
1249 s := fake_system('alpmerror')!
1250 defer { os.rmdir_all(s.tmp) or {} }
1251 s.install_local(foo('1.0-1', 'one'))!
1252 res := os.exec(['sh', '-c', 'printf "#mtree\\n./a type=file\\n" | gzip | head -c 15 > "\$0"',
1253 s.path('db/local/foo-1.0-1/mtree')])
1254 assert res.exit_code == 0, res.output
1255 run := s.run('', fn () ! {
1256 verify(ConfigVerify{
1257 checksums_level: 2
1258 })!
1259 })!
1260 assert run.err == ''
1261 errors := run.of('message').filter(it['error'] or { json2.Any(false) }.bool())
1262 assert errors.len == 1, run.of('message').str()
1263 assert errors[0]['text']!.str() == 'error while reading file ${s.path('db/local/foo-1.0-1/mtree')}: truncated gzip input'
1264 assert errors[0]['warning']!.bool()
1265}
1266
1267fn test_mark_and_verify_skip_what_names_nothing() ! {
1268 s := fake_system('skiptargets')!
1269 defer { os.rmdir_all(s.tmp) or {} }
1270 s.install_local(foo('1.0-1', 'one'))!
1271 s.install_local(FakePkg{
1272 ...fake_pkg('impl', '1.0-1', [])
1273 provides: ['virt=2']
1274 })!
1275 // a bad target is reported and counted; the good ones are still marked
1276 marked := s.run('', fn () ! {
1277 mark(ConfigMark{ reason: 'd', query: ['nope', 'foo'] })!
1278 })!
1279 assert marked.err == '' && marked.failed == 1
1280 assert marked.of('done')[0]['packages']!.as_array().map(it.str()) == ['foo']
1281 // verify resolves a versioned name and a provision, as pacman's -Qk
1282 // does, and names the target nothing answers
1283 checked := s.run('', fn () ! {
1284 verify(ConfigVerify{ query: ['foo>=1.0', 'virt', 'ghost'] })!
1285 })!
1286 assert checked.err == '', checked.err
1287 assert checked.failed == 1
1288 assert target_errors(checked) == ['package "ghost" was not found']
1289 none_there := s.run('', fn () ! {
1290 verify(ConfigVerify{ query: ['ghost'] })!
1291 })!
1292 assert none_there.err.contains('no one of the named packages'), none_there.err
1293}
1294
1295fn test_tree_of_several_targets_under_a_frontend() ! {
1296 s := fake_system('tree')!
1297 defer { os.rmdir_all(s.tmp) or {} }
1298 s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])!
1299 run := s.run('', fn () ! {
1300 tree(ConfigTree{ query: ['app', 'lib', 'nope'] })!
1301 })!
1302 assert run.err == ''
1303 // each tree is its own event, every channel line one json object, and
1304 // nothing at all reaches stdout — the blank line between trees is a
1305 // terminal's frame
1306 trees := run.of('tree')
1307 assert trees.len == 2
1308 assert trees[0]['root']!.as_map()['name']!.str() == 'app'
1309 children := trees[0]['root']!.as_map()['children']!.as_array()
1310 assert children.len == 1 && children[0].as_map()['name']!.str() == 'lib'
1311 assert trees[1]['root']!.as_map()['name']!.str() == 'lib'
1312 assert run.of('error').filter(it['target']!.bool()).len == 1
1313 assert run.stdout == '', run.stdout
1314}
1315
1316fn test_tree_leaves_the_sync_dbs_alone_until_needed() ! {
1317 // no sync db was ever fetched here, so setting them up warns that they
1318 // are not synced: a tree among installed packages never gets that far,
1319 // one that has to look past them does
1320 s := fake_system('treelazy')!
1321 defer { os.rmdir_all(s.tmp) or {} }
1322 s.install_local(fake_pkg('app', '1.0-1', ['lib']))!
1323 s.install_local(fake_pkg('lib', '1.0-1', []))!
1324 s.install_local(fake_pkg('broken', '1.0-1', ['gone']))!
1325 stale := fn (run FrontendRun) int {
1326 return run.of('message').filter(it['text'] or { json2.Any('') }.str().contains('not synced')).len
1327 }
1328 for query in [['app'], ['local/app', 'lib'], ['lib']] {
1329 local := s.run('', fn [query] () ! {
1330 tree(ConfigTree{ query: query })!
1331 })!
1332 assert local.err == '', local.err
1333 assert local.of('tree').len == query.len
1334 assert stale(local) == 0, '${query}: ${local.of('message')}'
1335 }
1336 // the reverse tree reads the installed packages alone, too
1337 reverse := s.run('', fn () ! {
1338 tree(ConfigTree{ reverse: true, query: ['lib'] })!
1339 })!
1340 assert reverse.of('tree').len == 1 && stale(reverse) == 0
1341 // a target that is not installed, and a dependency nothing installed
1342 // answers, each reach for the sync dbs — once, however many ask
1343 for query in [['nowhere'], ['broken'], ['broken', 'nowhere', 'core/x']] {
1344 past := s.run('', fn [query] () ! {
1345 tree(ConfigTree{ query: query })!
1346 })!
1347 assert stale(past) == 1, '${query}: ${past.of('message')}'
1348 }
1349 // what nothing provides is still drawn, as not found
1350 broken := s.run('', fn () ! {
1351 tree(ConfigTree{ query: ['broken'] })!
1352 })!
1353 child := broken.of('tree')[0]['root']!.as_map()['children']!.as_array()[0].as_map()
1354 assert child['name']!.str() == 'gone' && !(child['found'] or { json2.Any(false) }.bool())
1355}
1356
1357fn test_tree_of_several_targets_on_a_terminal() ! {
1358 s := fake_system('treetty')!
1359 defer { os.rmdir_all(s.tmp) or {} }
1360 s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])!
1361 run := s.run_ui('tty', '', fn () ! {
1362 tree(ConfigTree{ query: ['app', 'lib'] })!
1363 })!
1364 assert run.err == ''
1365 // the terminal gets the trees on stdout, a blank line between them
1366 trees := run.stdout.split('\n\n')
1367 assert trees.len == 2, run.stdout
1368 assert trees[0].starts_with('app'), run.stdout
1369 assert trees[1].starts_with('lib'), run.stdout
1370 assert run.events.len == 0
1371}
1372
1373fn test_failed_targets_count_per_run() ! {
1374 // one run's bad targets are its own: the next run in the same process
1375 // starts from none, as each vpac process does
1376 s := with_file_dbs('failedcount', [FakePkg{
1377 name: 'bar'
1378 files: {
1379 'usr/bin/bar': 'bar'
1380 }
1381 }])!
1382 defer { os.rmdir_all(s.tmp) or {} }
1383 misses := s.run('', fn () ! {
1384 find(ConfigFind{ query: ['/nope', '/usr/bin/bar', '/neither'] })!
1385 })!
1386 assert misses.failed == 2
1387 clean := s.run('', fn () ! {
1388 find(ConfigFind{ query: ['/usr/bin/bar'] })!
1389 })!
1390 assert clean.failed == 0
1391 // and a run leaves the count of whoever called it as it found it: the
1392 // run's own is in its result, not in the global after it
1393 failed_targets = 7
1394 defer { failed_targets = 0 }
1395 again := s.run('', fn () ! {
1396 find(ConfigFind{ query: ['/nope'] })!
1397 })!
1398 assert again.failed == 1
1399 assert failed_targets == 7
1400}
1401
1402fn test_install_of_several_archives_is_one_transaction() ! {
1403 // what a split build hands install: its archives, as local files, which
1404 // go in together — one listing, one go-ahead, one done event
1405 s := fake_system('archives')!
1406 defer { os.rmdir_all(s.tmp) or {} }
1407 s.publish([FakePkg{
1408 name: 'split-a'
1409 files: {
1410 'usr/share/split/a': 'a'
1411 }
1412 }, FakePkg{
1413 name: 'split-b'
1414 files: {
1415 'usr/share/split/b': 'b'
1416 }
1417 }])!
1418 archives := ['split-a', 'split-b'].map(s.path('repo/${it}-1.0-1-any.pkg.tar'))
1419 run := s.run('', fn [archives] () ! {
1420 install(ConfigInstall{ noconfirm: true, query: archives })!
1421 })!
1422 assert run.err == ''
1423 assert run.of('transaction').len == 1
1424 assert run.of('question').len == 1
1425 done := run.done()!
1426 assert sorted_strs(done['packages']!) == ['split-a', 'split-b']
1427 assert s.installed()! == {
1428 'split-a': '1.0-1'
1429 'split-b': '1.0-1'
1430 }
1431 assert os.read_file(s.path('root/usr/share/split/b'))! == 'b'
1432}
1433
1434// FakeRpc answers the pkgbuild rpc's info and search requests from a set of
1435// packages, or every request with raw when it is set
1436struct FakeRpc {
1437 pkgs map[string]PackagePkgbuild
1438 raw string
1439}
1440
1441fn (mut h FakeRpc) handle(req http.Request) http.Response {
1442 if h.raw != '' {
1443 return http.new_response(body: h.raw)
1444 }
1445 u := urllib.parse(req.url) or { return http.new_response(status: .bad_request) }
1446 mut results := []PackagePkgbuild{}
1447 if u.path == '/rpc/v5/info' {
1448 q := urllib.parse_query(u.raw_query) or { urllib.new_values() }
1449 for name in q.get_all('arg[]') {
1450 if p := h.pkgs[name] {
1451 results << p
1452 }
1453 }
1454 } else if u.path.starts_with('/rpc/v5/search/') {
1455 needle := u.path.all_after('/rpc/v5/search/')
1456 // by name, so several results come in an order a test can name
1457 mut names := h.pkgs.keys().filter(it.contains(needle))
1458 names.sort()
1459 for name in names {
1460 results << h.pkgs[name]
1461 }
1462 }
1463 return http.new_response(
1464 body: json2.encode(PackagesPkgbuild{
1465 count: results.len
1466 results: results
1467 type: 'multiinfo'
1468 version: 5
1469 })
1470 )
1471}
1472
1473// aur_pkg is a pkgbuild repo package of the fake rpc
1474fn aur_pkg(name string, depends []string, make_depends []string) PackagePkgbuild {
1475 return PackagePkgbuild{
1476 name: name
1477 package_base: name
1478 version: '1.0-1'
1479 depends: depends
1480 make_depends: make_depends
1481 }
1482}
1483
1484// fake_rpc serves h on a free localhost port until the returned server is
1485// stopped, and answers its base url
1486fn fake_rpc(h FakeRpc) !(&http.Server, string) {
1487 mut server := &http.Server{
1488 addr: '127.0.0.1:0'
1489 handler: h
1490 show_startup_message: false
1491 worker_num: 1
1492 }
1493 spawn server.listen_and_serve()
1494 server.wait_till_running()!
1495 return server, 'http://${server.addr}'
1496}
1497
1498fn test_pkgbuild_info_from_the_rpc() ! {
1499 mut server, base := fake_rpc(FakeRpc{
1500 pkgs: {
1501 'yay-bin': aur_pkg('yay-bin', ['pacman'], [])
1502 }
1503 })!
1504 defer { server.stop() }
1505 got := get_pkgbuild_info(base, ['yay-bin', 'nothere'])!
1506 assert got.map(it.name) == ['yay-bin']
1507 assert got[0].depends == ['pacman']
1508 found := get_pkgbuild_packages(base, 'yay')!
1509 assert found.map(it.name) == ['yay-bin']
1510 // no names asks for nothing, without a request
1511 assert get_pkgbuild_info(base, [])!.len == 0
1512}
1513
1514fn test_pkgbuild_rpc_short_garbage_is_an_error() ! {
1515 // a 200 whose body is no json and shorter than the quote of it: an error
1516 // naming what came, not a panic
1517 mut server, base := fake_rpc(FakeRpc{
1518 raw: 'oops'
1519 })!
1520 defer { server.stop() }
1521 get_pkgbuild_info(base, ['x']) or {
1522 assert err.msg().starts_with('failed to decode package info'), err.msg()
1523 assert err.msg().ends_with('(the answer begins: oops)'), err.msg()
1524 get_pkgbuild_packages(base, 'x') or {
1525 assert err.msg().ends_with('(the answer begins: oops)'), err.msg()
1526 return
1527 }
1528 assert false, 'the search took garbage'
1529 }
1530 assert false, 'the info lookup took garbage'
1531}
1532
1533// resolve walks name through the fake system's local and sync dbs and the
1534// fake rpc, as pkgbuild_install does, and answers the build plan
1535fn resolve(s FakeSystem, base string, name string) ![]PkgbuildNode {
1536 // the closure captures by value: the plan comes out through the heap
1537 mut plan := &Plan{}
1538 run := s.run('', fn [base, name, mut plan] () ! {
1539 cfg_repos << CfgRepo{
1540 name: 'aur'
1541 kind: 'pkgbuild'
1542 servers: [base]
1543 }
1544 mut handle := init_handle(new_trans_ui())!
1545 defer { handle.release() or {} }
1546 init_repos(mut handle)!
1547 plan.nodes << pkgbuild_plan(handle, name)!
1548 })!
1549 if run.err != '' {
1550 return error(run.err)
1551 }
1552 return plan.nodes
1553}
1554
1555@[heap]
1556struct Plan {
1557mut:
1558 nodes []PkgbuildNode
1559}
1560
1561fn test_pkgbuild_resolver_orders_the_build() ! {
1562 s := fake_system('resolver')!
1563 defer { os.rmdir_all(s.tmp) or {} }
1564 // glibc installed, lib in the repos, the rest only in the pkgbuild repo
1565 s.install_local(fake_pkg('glibc', '1.0-1', []))!
1566 s.publish([fake_pkg('lib', '1.0-1', [])])!
1567 mut server, base := fake_rpc(FakeRpc{
1568 pkgs: {
1569 'top': PackagePkgbuild{
1570 ...aur_pkg('top', ['mid', 'lib', 'glibc>=1.0', 'shared'], ['tool'])
1571 check_depends: ['checker']
1572 }
1573 'checker': aur_pkg('checker', [], [])
1574 'mid': aur_pkg('mid', ['leaf', 'shared'], [])
1575 'leaf': aur_pkg('leaf', [], [])
1576 'shared': aur_pkg('shared', [], [])
1577 'tool': aur_pkg('tool', [], [])
1578 }
1579 })!
1580 defer { server.stop() }
1581 plan := resolve(s, base, 'top')!
1582 // dependencies first, each once (shared is reached twice), the target last
1583 // what check() needs is planned as what the build needs is
1584 assert plan.map(it.info.name) == ['leaf', 'shared', 'mid', 'tool', 'checker', 'top']
1585 // a repo package is installed before the build that needs it; an
1586 // installed one is not touched; the site is the pkgbuild repo it came from
1587 top := plan.last()
1588 assert top.repo_deps == ['lib']
1589 assert plan.all(it.site == base)
1590 assert plan.filter(it.info.name != 'top').all(it.repo_deps.len == 0)
1591 // every node carries what wanted it, as the dependents spelled it: the
1592 // target nothing, a node wanted twice both spellings once each
1593 wanted := fn [plan] (name string) []string {
1594 return plan.filter(it.info.name == name)[0].wanted
1595 }
1596 assert wanted('top') == []
1597 assert wanted('mid') == ['mid'] && wanted('leaf') == ['leaf']
1598 assert wanted('shared') == ['shared']
1599 assert wanted('checker') == ['checker']
1600 // a site the config spells with a trailing slash joins a clone url with
1601 // one slash all the same
1602 slashed := resolve(s, base + '/', 'leaf')!
1603 assert slashed[0].site == base
1604}
1605
1606fn test_pkgbuild_resolver_refuses_cycles_and_unknowns() ! {
1607 s := fake_system('resolverbad')!
1608 defer { os.rmdir_all(s.tmp) or {} }
1609 s.publish([fake_pkg('lib', '1.0-1', [])])!
1610 mut server, base := fake_rpc(FakeRpc{
1611 pkgs: {
1612 'c1': aur_pkg('c1', ['c2'], [])
1613 'c2': aur_pkg('c2', ['c1'], [])
1614 'needy': aur_pkg('needy', ['ghost>=2'], [])
1615 }
1616 })!
1617 defer { server.stop() }
1618 resolve(s, base, 'c1') or {
1619 assert err.msg() == 'circular pkgbuild dependency: c1 is walked as its own dependency', err.msg()
1620 resolve(s, base, 'needy') or {
1621 assert err.msg() == '"ghost" is not in the repos or the pkgbuild repo', err.msg()
1622 return
1623 }
1624 assert false, 'a dependency nowhere was planned'
1625 }
1626 assert false, 'a cycle was planned'
1627}
1628
1629// target_errors are the messages of the target errors a run reported
1630fn target_errors(run FrontendRun) []string {
1631 return run.of('error').filter(it['target'] or { json2.Any(false) }.bool()).map(it['msg'] or {
1632 json2.Any('')
1633 }.str())
1634}
1635
1636fn test_install_scopes_a_target_to_its_repo() ! {
1637 s := fake_system('scope')!
1638 defer { os.rmdir_all(s.tmp) or {} }
1639 s.publish([fake_pkg('foo', '1.0-1', [])])!
1640 // a repo the config does not carry is an error, not a prefix to drop
1641 bad := s.run('', fn () ! {
1642 install(ConfigInstall{ noconfirm: true, query: ['nope/foo'] })!
1643 })!
1644 assert target_errors(bad) == ['database not found: nope']
1645 assert s.installed()!.len == 0
1646 // a name the repo named does not hold is not looked up anywhere else
1647 miss := s.run('', fn () ! {
1648 install(ConfigInstall{ noconfirm: true, query: ['core/nothere'] })!
1649 })!
1650 assert target_errors(miss) == ['target not found in core: nothere']
1651 good := s.run('', fn () ! {
1652 install(ConfigInstall{ noconfirm: true, query: ['core/foo'] })!
1653 })!
1654 assert good.err == '' && good.failed == 0
1655 assert s.installed()! == {
1656 'foo': '1.0-1'
1657 }
1658}
1659
1660fn test_install_resolves_constraints_and_providers() ! {
1661 s := fake_system('satisfier')!
1662 defer { os.rmdir_all(s.tmp) or {} }
1663 s.publish([fake_pkg('foo', '2.0-1', []),
1664 FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] }])!
1665 run := s.run('', fn () ! {
1666 install(ConfigInstall{ noconfirm: true, query: ['foo>=2', 'sh'] })!
1667 })!
1668 assert run.err == '' && run.failed == 0, run.err
1669 assert s.installed()! == {
1670 'foo': '2.0-1'
1671 'bash': '1.0-1'
1672 }
1673 // a version nothing has is a miss like any other
1674 old := s.run('', fn () ! {
1675 install(ConfigInstall{ noconfirm: true, query: ['core/foo>=3'] })!
1676 })!
1677 assert target_errors(old) == ['target not found in core: foo>=3']
1678}
1679
1680fn test_install_names_every_bad_target_and_installs_nothing() ! {
1681 s := fake_system('badtargets')!
1682 defer { os.rmdir_all(s.tmp) or {} }
1683 s.publish([fake_pkg('foo', '1.0-1', [])])!
1684 run := s.run('', fn () ! {
1685 install(ConfigInstall{ noconfirm: true, query: ['zzzzzz', 'foo', 'qqqqqq'] })!
1686 })!
1687 // both misses are told, not only the first, and the good one waits
1688 assert run.err == ''
1689 assert run.failed == 2
1690 assert target_errors(run).len == 2
1691 assert run.of('done').len == 0
1692 assert s.installed()!.len == 0
1693 assert !s.lock_left()
1694}
1695
1696fn tool(name string) FakePkg {
1697 return FakePkg{
1698 ...fake_pkg(name, '1.0-1', [])
1699 groups: ['tools']
1700 }
1701}
1702
1703fn test_install_asks_which_members_of_a_group() ! {
1704 s := fake_system('groupselect')!
1705 defer { os.rmdir_all(s.tmp) or {} }
1706 s.publish([tool('aa'), tool('bb'), tool('cc')])!
1707 // the frontend picks the first and the third, then lets it go
1708 run := s.run('{"id": 1, "answer": [0, 2]}\n{"id": 2, "answer": true}\n', fn () ! {
1709 install(ConfigInstall{ query: ['tools'] })!
1710 })!
1711 assert run.err == '', run.err
1712 // the members go out as a listing, each naming its group, then the question
1713 lists := run.of('listing')
1714 assert lists.len == 1
1715 members := lists[0]['entries']!.as_array().map(it.as_map())
1716 assert members.map(it['name'] or { json2.Any('') }.str()) == ['aa', 'bb', 'cc']
1717 assert members.all(it['group'] or { json2.Any('') }.str() == 'tools')
1718 questions := run.of('question')
1719 assert questions[0]['question']!.str() == 'select'
1720 assert questions[0]['preset']!.as_array().len == 3
1721 assert s.installed()! == {
1722 'aa': '1.0-1'
1723 'cc': '1.0-1'
1724 }
1725 // --noconfirm takes every member left; the installed ones are not offered
1726 rest := s.run('', fn () ! {
1727 install(ConfigInstall{ noconfirm: true, query: ['tools'] })!
1728 })!
1729 assert rest.err == ''
1730 assert rest.of('listing')[0]['entries']!.as_array().len == 1
1731 assert s.installed()!.len == 3
1732 // nothing left: said, and no failure
1733 done := s.run('', fn () ! {
1734 install(ConfigInstall{ noconfirm: true, query: ['tools'] })!
1735 })!
1736 assert done.err == '' && done.failed == 0
1737 assert done.of('message').any(it['text'] or { json2.Any('') }.str().contains('every member'))
1738}
1739
1740fn test_needed_group_queries_deliver_skip_warnings() ! {
1741 s := fake_system('needed_group')!
1742 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
1743 s.install_local(tool('aa'))!
1744 s.publish([tool('aa'), tool('bb')])!
1745 run := s.run('', fn () ! {
1746 mut ui := new_trans_ui()
1747 defer { ui.stop() }
1748 mut handle := init_handle(ui)!
1749 defer { handle.release() or { went_on('release the alpm handle', err) } }
1750 init_repos(mut handle)!
1751 handle.trans_init(.needed | .nolock)!
1752 defer { handle.trans_release() or { went_on('release the test transaction', err) } }
1753 dbs := handle.get_syncdbs()!
1754 mut members := dbs.find_group_pkgs('tools')
1755 defer { members.free() }
1756 check(members.pkgs().map(it.get_name()) == ['bb'], 'needed group queries skip installed members')!
1757 })!
1758 assert run.err == '' && run.failed == 0 && run.stdout == '', run.err
1759 messages := run.of('message')
1760 assert messages.len == 1, messages.str()
1761 assert messages[0]['text']!.str() == 'aa-1.0-1 is up to date -- skipping'
1762 assert messages[0]['warning']!.bool()
1763 assert !(messages[0]['error'] or { json2.Any(false) }).bool()
1764 assert run.of('question').len == 0
1765 assert s.installed()! == {
1766 'aa': '1.0-1'
1767 }
1768 assert !s.lock_left()
1769}
1770
1771fn test_group_selection_on_a_terminal() ! {
1772 s := fake_system('groupselecttty')!
1773 defer { os.rmdir_all(s.tmp) or {} }
1774 s.publish([tool('aa'), tool('bb'), tool('cc')])!
1775 // all but the second, then the go-ahead
1776 run := s.run_ui('tty', '^2\ny\n', fn () ! {
1777 install(ConfigInstall{ query: ['tools'] })!
1778 })!
1779 assert run.err == '', run.err
1780 assert s.installed()! == {
1781 'aa': '1.0-1'
1782 'cc': '1.0-1'
1783 }
1784 // --print lists every member and asks nothing
1785 preview := s.run_ui('tty', '', fn () ! {
1786 install(ConfigInstall{ print_only: true, query: ['tools'] })!
1787 })!
1788 assert preview.stdout.trim_space() == 'bb-1.0-1-any.pkg.tar', preview.stdout
1789}
1790
1791fn test_remove_takes_a_group_and_names_every_bad_target() ! {
1792 s := fake_system('removegroup')!
1793 defer { os.rmdir_all(s.tmp) or {} }
1794 s.install_local(tool('aa'))!
1795 s.install_local(tool('bb'))!
1796 s.install_local(fake_pkg('keep', '1.0-1', []))!
1797 // one unknown target stops the removal, after every one is named
1798 bad := s.run('', fn () ! {
1799 remove(ConfigRemove{ noconfirm: true, query: ['zzzzzz', 'tools', 'qqqqqq'] })!
1800 })!
1801 assert bad.failed == 2
1802 assert s.installed()!.len == 3
1803 assert !s.lock_left()
1804 run := s.run('', fn () ! {
1805 remove(ConfigRemove{ noconfirm: true, query: ['tools'] })!
1806 })!
1807 assert run.err == '', run.err
1808 assert sorted_strs(run.done()!['packages']!) == ['aa', 'bb']
1809 assert s.installed()! == {
1810 'keep': '1.0-1'
1811 }
1812}
1813
1814fn test_remove_unneeded_and_recursive_levels() ! {
1815 s := fake_system('removelevels')!
1816 defer { os.rmdir_all(s.tmp) or {} }
1817 s.install_local(fake_pkg('app', '1.0-1', ['lib', 'tool']))!
1818 s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
1819 // tool was installed explicitly, though app needs it
1820 s.install_local(fake_pkg('tool', '1.0-1', []))!
1821 s.install_local(fake_pkg('other', '1.0-1', []))!
1822 // -u: lib stays where app needs it, other goes, and that is no failure
1823 u := s.run('', fn () ! {
1824 remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib', 'other'] })!
1825 })!
1826 assert u.err == '', u.err
1827 assert sorted_strs(u.done()!['packages']!) == ['other']
1828 assert 'lib' in s.installed()!
1829 none_left := s.run('', fn () ! {
1830 remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib'] })!
1831 })!
1832 assert none_left.err == '' && none_left.of('done').len == 0
1833 // a version constraint names what satisfies it
1834 // -s takes lib, a dependency; tool was asked for by name and stays
1835 one := s.run('', fn () ! {
1836 remove(ConfigRemove{ print_only: true, recursive_level: 1, query: ['app>=1'] })!
1837 })!
1838 assert one.err == '', one.err
1839 assert sorted_strs(one.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or {
1840 json2.Any('')
1841 })) == ['app', 'lib']
1842 // -ss takes the explicitly installed dependency too
1843 two := s.run('', fn () ! {
1844 remove(ConfigRemove{ print_only: true, recursive_level: 2, query: ['app'] })!
1845 })!
1846 assert sorted_strs(two.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or {
1847 json2.Any('')
1848 })) == ['app', 'lib', 'tool']
1849}
1850
1851fn test_upgrade_downgrades_only_when_asked() ! {
1852 s := fake_system('downgrade')!
1853 defer { os.rmdir_all(s.tmp) or {} }
1854 s.install_local(foo('2.0-1', 'two'))!
1855 s.publish([foo('1.0-1', 'one')])!
1856 plain := s.run('', fn () ! {
1857 upgrade(ConfigUpgrade{ noconfirm: true })!
1858 })!
1859 assert plain.err == ''
1860 assert s.installed()!['foo']! == '2.0-1'
1861 down := s.run('', fn () ! {
1862 upgrade(ConfigUpgrade{ noconfirm: true, sysupgrade_level: 2 })!
1863 })!
1864 assert down.err == '', down.err
1865 assert s.installed()!['foo']! == '1.0-1'
1866}
1867
1868fn test_info_changelog_and_package_files() ! {
1869 s := fake_system('changelog')!
1870 defer { os.rmdir_all(s.tmp) or {} }
1871 s.install_local(FakePkg{ ...fake_pkg('logged', '1.0-1', []), changelog: 'first release\n' })!
1872 s.install_local(fake_pkg('silent', '1.0-1', []))!
1873 s.publish([
1874 FakePkg{ ...fake_pkg('filed', '1.0-1', []), changelog: 'from the archive\n' },
1875 fake_pkg('other', '2.0-1', []),
1876 ])!
1877 run := s.run('', fn () ! {
1878 info(ConfigInfo{ changelog: true, query: ['logged', 'silent'] })!
1879 })!
1880 assert run.err == '' && run.failed == 0
1881 logs := run.of('changelog')
1882 assert logs.len == 1
1883 assert logs[0]['package']!.str() == 'logged'
1884 assert logs[0]['text']!.str() == 'first release\n'
1885 // the one without is said, and is no failure, as in pacman
1886 assert run.of('message').any(it['text'] or { json2.Any('') }.str().contains('no changelog available for silent'))
1887
1888 // -p: every target is a package file, and one that does not load is its
1889 // own error
1890 archives := ['filed-1.0-1', 'other-2.0-1'].map(s.path('repo/${it}-any.pkg.tar'))
1891 mut targets := archives.clone()
1892 targets << s.path('repo/nothere.pkg.tar')
1893 files := s.run('', fn [targets] () ! {
1894 info(ConfigInfo{ file: true, fields: 'name,version', query: targets })!
1895 })!
1896 infos := files.of('info')
1897 assert infos.len == 2
1898 assert files.failed == 1
1899 first := archives[0]
1900 log := s.run('', fn [first] () ! {
1901 info(ConfigInfo{ file: true, changelog: true, query: [first] })!
1902 })!
1903 assert log.of('changelog')[0]['text']!.str() == 'from the archive\n'
1904 tty := s.run_ui('tty', '', fn () ! {
1905 info(ConfigInfo{ changelog: true, query: ['logged'] })!
1906 })!
1907 assert tty.stdout == 'changelog for logged:\nfirst release\n', tty.stdout
1908}
1909
1910fn test_info_directory_changelog_is_an_empty_stream() ! {
1911 $if !linux {
1912 return
1913 }
1914 s := fake_system('changelog_directory')!
1915 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
1916 s.install_local(fake_pkg('logged', '1.0-1', []))!
1917 // fopen accepts a directory; fread reaches its error with no bytes.
1918 os.mkdir(s.path('db/local/logged-1.0-1/changelog'))!
1919 run := s.run('', fn () ! {
1920 info(ConfigInfo{ changelog: true, query: ['logged'] })!
1921 })!
1922 assert run.err == '' && run.failed == 0, run.err
1923 logs := run.of('changelog')
1924 assert logs.len == 1, run.events.str()
1925 assert logs[0]['package']!.str() == 'logged'
1926 assert logs[0]['text']!.str() == ''
1927 assert !run.of('message').any(it['text']!.str().contains('no changelog available'))
1928}
1929
1930fn test_verify_without_mtree_sends_no_library_error() ! {
1931 s := fake_system('missing_mtree')!
1932 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
1933 s.install_local(fake_pkg('old', '1.0-1', []))!
1934 run := s.run('', fn () ! {
1935 verify(ConfigVerify{ checksums_level: 2 })!
1936 })!
1937 assert run.err == '' && run.failed == 0, run.err
1938 assert !run.of('message').any(it['error'] or { json2.Any(false) }.bool()), run.events.str()
1939 reports := run.of('verify')
1940 assert reports.len == 1
1941 lines := reports[0]['lines']!.as_array().map(it.as_map()['text']!.str())
1942 assert lines == ['old: no mtree file'], lines.str()
1943 assert reports[0]['bad']!.int() == 0
1944}
1945
1946fn test_package_info_delivers_metadata_warnings_without_losing_the_package() ! {
1947 s := fake_system('package_metadata_warning')!
1948 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
1949 path := s.path('repo/app.pkg.tar')
1950 bytes := archivefixtures.tar_bytes([
1951 archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\nfuture = value\npkgdesc = a description\n' },
1952 archivefixtures.Entry{ name: 'usr/app', text: 'payload' },
1953 ])
1954 os.write_file_array(path, bytes)!
1955 run := s.run('', fn [path] () ! {
1956 info(ConfigInfo{ file: true, fields: 'name,version,description', query: [path] })!
1957 })!
1958 assert run.err == '' && run.failed == 0, run.err
1959 assert run.of('info').len == 1
1960 messages := run.of('message').filter(it['text']!.str() == "app: unknown key 'future' in package description")
1961 assert messages.len == 1
1962 assert messages[0]['warning']!.bool()
1963 assert !(messages[0]['error'] or { json2.Any(false) }).bool()
1964 assert os.read_bytes(path)! == bytes
1965 assert !s.lock_left()
1966}
1967
1968fn test_package_info_preserves_metadata_and_archive_read_failure_kinds() ! {
1969 s := fake_system('package_read_errors')!
1970 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
1971 missing := s.path('repo/no-metadata.pkg.tar')
1972 truncated := s.path('repo/truncated.pkg.tar')
1973 valid := s.path('repo/valid.pkg.tar')
1974 without_info := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'usr/file', text: 'payload' }])
1975 good := archivefixtures.tar_bytes([
1976 archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' },
1977 archivefixtures.Entry{ name: 'usr/file', text: 'payload' },
1978 ])
1979 os.write_file_array(missing, without_info)!
1980 os.write_file_array(truncated, good[..1124])!
1981 os.write_file_array(valid, good)!
1982 run := s.run('', fn [missing, truncated, valid] () ! {
1983 info(ConfigInfo{ file: true, fields: 'name,version', query: [missing, truncated, valid] })!
1984 })!
1985 assert run.err == '' && run.failed == 2, run.err
1986 assert run.of('info').len == 1
1987 errors := target_errors(run)
1988 assert errors.len == 2
1989 assert errors[0].contains(alpm.Errno.pkg_invalid.strerror())
1990 assert errors[1].contains(alpm.Errno.libarchive.strerror())
1991 messages := run.of('message').filter(it['text']!.str().starts_with('missing package metadata in ') || it['text']!.str().starts_with('error while reading package '))
1992 assert messages.len == 2
1993 assert messages[0]['text']!.str() == 'missing package metadata in ${missing}'
1994 assert messages[1]['text']!.str().starts_with('error while reading package ${truncated}:')
1995 assert messages.all(it['warning']!.bool() && it['error']!.bool())
1996 assert os.read_bytes(missing)! == without_info
1997 assert os.read_bytes(truncated)! == good[..1124]
1998 assert os.read_bytes(valid)! == good
1999 assert !s.lock_left()
2000}
2001
2002fn test_bad_package_mtree_falls_back_without_rejecting_the_archive() ! {
2003 s := fake_system('package_mtree_fallback')!
2004 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2005 path := s.path('repo/app.pkg.tar')
2006 bytes := archivefixtures.tar_bytes([
2007 archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' },
2008 archivefixtures.Entry{ name: '.MTREE', text: 'invalid mtree' },
2009 archivefixtures.Entry{ name: 'usr/file', text: 'payload' },
2010 ])
2011 os.write_file_array(path, bytes)!
2012 run := s.run('', fn [path] () ! {
2013 mut ui := new_trans_ui()
2014 handle := init_handle(ui)!
2015 defer { handle.release() or { went_on('release the alpm handle', err) } }
2016 defer { ui.stop() }
2017 pkg := handle.pkg_load(path, 1, 0)!
2018 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
2019 check(handle.errno() == .libarchive, 'mtree fallback preserves the source error state')!
2020 check(pkg.get_files().names() == ['usr/file'], 'archive scan recovers the payload list')!
2021 })!
2022 assert run.err == '' && run.failed == 0, run.err
2023 assert os.read_bytes(path)! == bytes
2024 assert !s.lock_left()
2025}
2026
2027fn test_raw_signature_failure_reaches_the_frontend_before_its_target_error() ! {
2028 s := fake_system('raw_signature_error')!
2029 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2030 defer { signaturefixtures.cleanup(s.path('gpg')) or { went_on('remove the test keyring', err) } }
2031 path := s.path('repo/app.pkg.tar')
2032 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }])
2033 os.write_file_array(path, bytes)!
2034 os.write_file(path + '.sig', '')!
2035 run := s.run('', fn [path] () ! {
2036 mut ui := new_trans_ui()
2037 handle := init_handle(ui)!
2038 defer { handle.release() or { went_on('release the alpm handle', err) } }
2039 defer { ui.stop() }
2040 pkg := handle.pkg_load(path, 0, 0)!
2041 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
2042 if result := pkg.check_pgp_signature() {
2043 result.cleanup()!
2044 return error('accepted an empty signature')
2045 }
2046 check(handle.errno() == .gpgme, 'raw signature failure retains its error kind')!
2047 target_error('signature check failed: ' + handle.errno().strerror())
2048 })!
2049 assert run.err == '' && run.failed == 1, run.err
2050 messages := run.of('message').filter(it['text']!.str().starts_with('GPGME error:'))
2051 assert messages.len == 1
2052 assert messages[0]['warning']!.bool() && messages[0]['error']!.bool()
2053 ordered := run.events.filter(it['type']!.str() in ['message', 'error'])
2054 assert ordered.len == 3
2055 assert ordered[0]['type']!.str() == 'message'
2056 assert ordered[0]['text']!.str() == "Public keyring not found; have you run 'pacman-key --init'?"
2057 assert ordered[0]['warning']!.bool() && !(ordered[0]['error'] or { json2.Any(false) }).bool()
2058 assert ordered[1]['type']!.str() == 'message'
2059 assert ordered[2]['type']!.str() == 'error'
2060 assert target_errors(run) == ['signature check failed: ' + alpm.Errno.gpgme.strerror()]
2061 assert os.read_bytes(path)! == bytes
2062 assert os.read_file(path + '.sig')! == ''
2063 assert !s.lock_left()
2064}
2065
2066fn test_signature_context_allocation_error_reaches_frontends_and_allows_a_retry() ! {
2067 s := fake_system('signature_context_allocation')!
2068 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2069 ring := signaturefixtures.create(s.path('gpg'))!
2070 defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } }
2071 path := s.path('repo/app.pkg.tar')
2072 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }])
2073 os.write_file_array(path, bytes)!
2074 ring.sign(path, [ring.fingerprint], false)!
2075 sig := os.read_bytes(path + '.sig')!
2076 run := s.run('', fn [path] () ! {
2077 mut ui := new_trans_ui()
2078 handle := init_handle(ui)!
2079 defer { handle.release() or { went_on('release the alpm handle', err) } }
2080 defer { ui.stop() }
2081 pkg := handle.pkg_load(path, 0, 0)!
2082 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
2083 mut state := unsafe { frontend_signature_fault }
2084 saved_remaining, saved_failures := state.remaining, state.failures
2085 state.remaining = 1
2086 state.failures = 0
2087 defer {
2088 state.remaining = saved_remaining
2089 state.failures = saved_failures
2090 }
2091 if result := pkg.check_pgp_signature() {
2092 result.cleanup()!
2093 return error('accepted the failed context allocation')
2094 }
2095 check(state.failures == 1 && handle.errno() == .gpgme, 'the context allocation failure retains the GPGME error')!
2096 target_error('signature check failed: ' + handle.errno().strerror())
2097 result := pkg.check_pgp_signature() or { return error('signature verification did not recover') }
2098 defer { result.cleanup() or { went_on('clean up the signature result', err) } }
2099 check(handle.errno() == .ok && result.count == 1, 'retry verifies the signature')!
2100 check(unsafe { result.results[0].status == .valid && result.results[0].key.data != nil }, 'retry retains the real verification key')!
2101 })!
2102 assert run.err == '' && run.failed == 1 && run.stdout == '', run.err
2103 messages := run.of('message')
2104 assert messages.len == 1 && messages[0]['text']!.str().starts_with('GPGME error: ')
2105 assert messages[0]['text']!.str().contains('allocate memory')
2106 assert messages[0]['warning']!.bool() && messages[0]['error']!.bool()
2107 ordered := run.events.filter(it['type']!.str() in ['message', 'error'])
2108 assert ordered.map(it['type']!.str()) == ['message', 'error']
2109 assert target_errors(run) == ['signature check failed: ' + alpm.Errno.gpgme.strerror()]
2110 assert os.read_bytes(path)! == bytes
2111 assert os.read_bytes(path + '.sig')! == sig
2112 assert !s.lock_left()
2113}
2114
2115fn test_package_load_still_verifies_after_a_failed_preliminary_key_lookup() ! {
2116 s := fake_system('signature_preliminary_lookup')!
2117 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2118 ring := signaturefixtures.create(s.path('gpg'))!
2119 defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } }
2120 path := s.path('repo/app.pkg.tar')
2121 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }])
2122 os.write_file_array(path, bytes)!
2123 ring.sign(path, [ring.fingerprint], false)!
2124 sig := os.read_bytes(path + '.sig')!
2125 for tampered in [false, true] {
2126 mut content := bytes.clone()
2127 if tampered { content[512 + 'pkgname = '.len] = 'b'[0] }
2128 os.write_file_array(path, content)!
2129 run := s.run('', fn [path, tampered] () ! {
2130 mut ui := new_trans_ui()
2131 handle := init_handle(ui)!
2132 defer { handle.release() or { went_on('release the alpm handle', err) } }
2133 defer { ui.stop() }
2134 mut state := unsafe { frontend_signature_fault }
2135 saved_remaining, saved_failures := state.remaining, state.failures
2136 state.remaining = 1
2137 state.failures = 0
2138 defer {
2139 state.remaining = saved_remaining
2140 state.failures = saved_failures
2141 }
2142 if pkg := handle.pkg_load(path, 1, 9) {
2143 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
2144 check(!tampered && handle.errno() == .ok, 'valid package survives the advisory lookup failure')!
2145 check(pkg.get_name() == 'app' && pkg.get_validation() == .signature, 'package loading performed signature verification')!
2146 } else {
2147 check(tampered && handle.errno() == .pkg_invalid_sig, 'final verification rejects the tampered package')!
2148 target_error('package signature rejected: ' + handle.errno().strerror())
2149 }
2150 check(state.failures == 1, 'the preliminary key lookup allocation failed exactly once')!
2151 })!
2152 assert run.err == '' && run.stdout == '', run.err
2153 assert run.failed == if tampered { 1 } else { 0 }
2154 assert run.of('message').all(!it['text']!.str().contains('allocate memory'))
2155 assert run.of('question').len == 0
2156 if !tampered {
2157 assert run.of('message').len == 0 && run.of('error').len == 0
2158 }
2159 assert os.read_bytes(path)! == content
2160 assert os.read_bytes(path + '.sig')! == sig
2161 assert !s.lock_left()
2162 }
2163}
2164
2165fn test_missing_keyring_warns_frontends_once_across_repeated_signature_checks() ! {
2166 s := fake_system('signature_initialization_warning')!
2167 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2168 defer { signaturefixtures.cleanup(s.path('gpg')) or { went_on('remove the test keyring', err) } }
2169 signer := signaturefixtures.create(s.path('signer'))!
2170 defer { signaturefixtures.cleanup(signer.path) or { went_on('remove the signing keyring', err) } }
2171 path := s.path('repo/app.pkg.tar')
2172 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }])
2173 os.write_file_array(path, bytes)!
2174 signer.sign(path, [signer.fingerprint], false)!
2175 sig := os.read_bytes(path + '.sig')!
2176 run := s.run('', fn [path] () ! {
2177 mut ui := new_trans_ui()
2178 handle := init_handle(ui)!
2179 defer { handle.release() or { went_on('release the alpm handle', err) } }
2180 defer { ui.stop() }
2181 pkg := handle.pkg_load(path, 0, 0)!
2182 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
2183 for attempt in 0 .. 2 {
2184 result := pkg.check_pgp_signature() or { return error('could not inspect the unknown-key signature') }
2185 defer { result.cleanup() or { went_on('clean up the signature result', err) } }
2186 check(handle.errno() == if attempt == 0 { alpm.Errno.not_a_file } else { alpm.Errno.ok }, 'keyring warning retains the source error state')!
2187 check(result.count == 1 && unsafe { result.results[0].status == .key_unknown }, 'missing key is reported without importing it')!
2188 }
2189 })!
2190 assert run.err == '' && run.failed == 0 && run.stdout == '', run.err
2191 messages := run.of('message')
2192 assert messages.len == 1
2193 assert messages[0]['text']!.str() == "Public keyring not found; have you run 'pacman-key --init'?"
2194 assert messages[0]['warning']!.bool() && !(messages[0]['error'] or { json2.Any(false) }).bool()
2195 assert run.of('question').len == 0
2196 assert os.read_bytes(path)! == bytes
2197 assert os.read_bytes(path + '.sig')! == sig
2198 assert !s.lock_left()
2199}
2200
2201fn test_modern_keybox_verifies_without_a_false_missing_keyring_warning() ! {
2202 s := fake_system('signature_modern_keybox')!
2203 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2204 ring := signaturefixtures.create(s.path('gpg'))!
2205 defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } }
2206 assert os.exists(os.join_path(ring.path, 'pubring.kbx'))
2207 assert !os.exists(os.join_path(ring.path, 'pubring.gpg'))
2208 path := s.path('repo/app.pkg.tar')
2209 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }])
2210 os.write_file_array(path, bytes)!
2211 ring.sign(path, [ring.fingerprint], false)!
2212 sig := os.read_bytes(path + '.sig')!
2213 run := s.run('', fn [path] () ! {
2214 mut ui := new_trans_ui()
2215 handle := init_handle(ui)!
2216 defer { handle.release() or { went_on('release the alpm handle', err) } }
2217 defer { ui.stop() }
2218 pkg := handle.pkg_load(path, 0, 0)!
2219 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
2220 for _ in 0 .. 2 {
2221 result := pkg.check_pgp_signature() or { return error('could not verify with the modern keybox') }
2222 defer { result.cleanup() or { went_on('clean up the signature result', err) } }
2223 check(handle.errno() == .ok && result.count == 1, 'modern keybox verification has no stale error')!
2224 check(unsafe { result.results[0].status == .valid && result.results[0].key.data != nil }, 'modern keybox supplies the retained verification key')!
2225 }
2226 })!
2227 assert run.err == '' && run.failed == 0 && run.stdout == '', run.err
2228 assert run.of('message').len == 0
2229 assert run.of('question').len == 0
2230 assert os.read_bytes(path)! == bytes
2231 assert os.read_bytes(path + '.sig')! == sig
2232 assert !s.lock_left()
2233}
2234
2235fn test_issuer_extraction_errors_reach_frontends_and_preserve_the_previous_errno() ! {
2236 s := fake_system('signature_issuer_errors')!
2237 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2238 for prior in [false, true] {
2239 for unsupported in [false, true] {
2240 data := if unsupported {
2241 [u8(0xc2), 10, 3, 0, 1, 8, 0, 0, 0, 0, 0, 0]
2242 } else {
2243 [u8(0)]
2244 }
2245 identifier := if prior { 'fixture.pkg.tar\x00ignored' } else { 'fixture.pkg.tar' }
2246 run := s.run('', fn [prior, data, identifier] () ! {
2247 mut ui := new_trans_ui()
2248 handle := init_handle(ui)!
2249 defer { handle.release() or { went_on('release the alpm handle', err) } }
2250 defer { ui.stop() }
2251 if prior {
2252 if _ := handle.register_syncdb('', 0) {
2253 return error('accepted an empty repository name')
2254 }
2255 }
2256 previous := handle.errno()
2257 if keys := handle.extract_keyid(identifier, data.data, uint(data.len)) {
2258 keys.free_inner(C.free)
2259 keys.free()
2260 return error('accepted malformed issuer data')
2261 } else {
2262 check(err.code() == int(previous), 'issuer parser failure retains the previous error code')!
2263 }
2264 check(handle.errno() == previous, 'issuer parser failure leaves the handle error state unchanged')!
2265 target_error('could not extract signature issuers')
2266 })!
2267 assert run.err == '' && run.failed == 1 && run.stdout == '', run.err
2268 messages := run.of('message')
2269 assert messages.len == 1
2270 detail := if unsupported {
2271 'unsupported signature format'
2272 } else {
2273 'signature format error'
2274 }
2275 assert messages[0]['text']!.str() == 'fixture.pkg.tar: ${detail}'
2276 assert messages[0]['warning']!.bool() && messages[0]['error']!.bool()
2277 ordered := run.events.filter(it['type']!.str() in ['message', 'error'])
2278 assert ordered.len == 2 && ordered[0]['type']!.str() == 'message' && ordered[1]['type']!.str() == 'error'
2279 assert target_errors(run) == ['could not extract signature issuers']
2280 assert !s.lock_left()
2281 }
2282 }
2283}
2284
2285fn test_embedded_signature_verifies_the_recorded_file_without_a_package_cache() ! {
2286 s := fake_system('embedded_signature_no_cache')!
2287 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2288 ring := signaturefixtures.create(s.path('verification-keys'))!
2289 defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } }
2290 path := s.path('signed.pkg.tar')
2291 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }])
2292 os.write_file_array(path, bytes)!
2293 ring.sign(path, [ring.fingerprint], false)!
2294 signature := os.read_bytes(path + '.sig')!
2295 archivefixtures.write(s.path('db/sync/metadata.db'), [archivefixtures.Entry{ name: 'app-1-1/desc', text: '%FILENAME%\nsigned.pkg.tar\n\n%PGPSIG%\n${base64.encode(signature)}\n\n' }], false)!
2296 root := s.tmp
2297 home := ring.path
2298 fingerprint := ring.fingerprint
2299 run := s.run('', fn [root, home, fingerprint] () ! {
2300 previous := os.getwd()
2301 os.chdir(root)!
2302 defer { os.chdir(previous) or { went_on('restore the test directory', err) } }
2303 mut ui := new_trans_ui()
2304 handle := init_handle(ui)!
2305 defer { handle.release() or { went_on('release the alpm handle', err) } }
2306 defer { ui.stop() }
2307 handle.option_set_gpgdir(home)!
2308 handle.option_set_cachedirs(unsafe { nil })!
2309 db := handle.register_syncdb('metadata', 0)!
2310 pkg := db.get_pkg('app') or { return error('missing repository package') }
2311 result := pkg.check_pgp_signature() or { return error('could not verify the recorded package file') }
2312 defer { result.cleanup() or { went_on('clean up the signature result', err) } }
2313 check(handle.errno() == .ok && result.count == 1, 'embedded signature is verified')!
2314 check(unsafe { cstring_to_vstring(result.results[0].key.fingerprint) } == fingerprint, 'signature belongs to the fixture key')!
2315 check(unsafe { result.results[0].key.data != nil }, 'signature retains the actual key data')!
2316 })!
2317 assert run.err == '' && run.failed == 0, run.err
2318 assert os.ls(s.path('cache'))!.len == 0
2319 assert os.read_bytes(path)! == bytes
2320 assert os.read_bytes(path + '.sig')! == signature
2321 assert !s.lock_left()
2322}
2323
2324fn test_database_signature_requirement_reaches_frontends() ! {
2325 s := fake_system('database_signature_requirement')!
2326 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2327 path := s.path('db/sync/core.db')
2328 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'app-1-1/desc', text: '%DESC%\napp\n\n' }])
2329 os.write_file_array(path, bytes)!
2330 for level in [1024, 3072] {
2331 run := s.run('', fn [level] () ! {
2332 mut ui := new_trans_ui()
2333 handle := init_handle(ui)!
2334 defer { handle.release() or { went_on('release the alpm handle', err) } }
2335 defer { ui.stop() }
2336 db := handle.register_syncdb('core', level)!
2337 if level == 1024 {
2338 if _ := db.get_valid() {
2339 return error('accepted a missing required database signature')
2340 }
2341 check(handle.errno() == .db_invalid_sig, 'required signature keeps its failure kind')!
2342 target_error('database signature rejected: ' + handle.errno().strerror())
2343 } else {
2344 check(db.get_valid()!, 'optional database signature may be absent')!
2345 }
2346 })!
2347 assert run.err == '', run.err
2348 assert run.failed == if level == 1024 { 1 } else { 0 }
2349 messages := run.of('message').filter(it['text']!.str() == 'core: missing required signature')
2350 assert messages.len == if level == 1024 { 1 } else { 0 }
2351 if messages.len > 0 {
2352 assert messages[0]['warning']!.bool() && messages[0]['error']!.bool()
2353 }
2354 assert run.of('question').len == 0
2355 }
2356 assert os.read_bytes(path)! == bytes
2357 assert !os.exists(path + '.sig')
2358 assert !s.lock_left()
2359}
2360
2361fn test_database_marginal_trust_policy_reports_its_reason() ! {
2362 s := fake_system('database_signature_trust')!
2363 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2364 ring := signaturefixtures.create(s.path('verification-keys'))!
2365 defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } }
2366 path := s.path('db/sync/core.db')
2367 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'app-1-1/desc', text: '%DESC%\napp\n\n' }])
2368 os.write_file_array(path, bytes)!
2369 ring.sign(path, [ring.fingerprint], false)!
2370 ring.trust(ring.fingerprint, 4)!
2371 signature := os.read_bytes(path + '.sig')!
2372 home := ring.path
2373 for level in [1024, 5120] {
2374 run := s.run('', fn [home, level] () ! {
2375 mut ui := new_trans_ui()
2376 handle := init_handle(ui)!
2377 defer { handle.release() or { went_on('release the alpm handle', err) } }
2378 defer { ui.stop() }
2379 handle.option_set_gpgdir(home)!
2380 db := handle.register_syncdb('core', level)!
2381 if level == 1024 {
2382 if _ := db.get_valid() { return error('accepted disallowed marginal trust') }
2383 target_error('database signature rejected: ' + handle.errno().strerror())
2384 } else {
2385 check(db.get_valid()!, 'configured marginal trust is accepted')!
2386 }
2387 })!
2388 assert run.err == '', run.err
2389 assert run.failed == if level == 1024 { 1 } else { 0 }
2390 messages := run.of('message').filter(it['text']!.str() == 'core: signature from "Native ALPM Fixture <alpm-fixture@example.invalid>" is marginal trust')
2391 assert messages.len == if level == 1024 { 1 } else { 0 }
2392 assert run.of('question').len == 0
2393 }
2394 assert os.read_bytes(path)! == bytes
2395 assert os.read_bytes(path + '.sig')! == signature
2396 assert !s.lock_left()
2397}
2398
2399fn test_declined_database_key_import_is_reported_without_importing_the_key() ! {
2400 s := fake_system('database_key_decline')!
2401 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2402 signer := signaturefixtures.create(s.path('signer-keys'))!
2403 defer { signaturefixtures.cleanup(signer.path) or { went_on('remove the signing keyring', err) } }
2404 verifier := signaturefixtures.empty(s.path('verification-keys'))!
2405 defer { signaturefixtures.cleanup(verifier.path) or { went_on('remove the verification keyring', err) } }
2406 path := s.path('db/sync/core.db')
2407 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'app-1-1/desc', text: '%DESC%\napp\n\n' }])
2408 os.write_file_array(path, bytes)!
2409 signer.sign(path, [signer.fingerprint], false)!
2410 signature := os.read_bytes(path + '.sig')!
2411 home := verifier.path
2412 run := s.run('{"id": 1, "answer": false}\n', fn [home] () ! {
2413 mut ui := new_trans_ui()
2414 handle := init_handle(ui)!
2415 defer { handle.release() or { went_on('release the alpm handle', err) } }
2416 defer { ui.stop() }
2417 handle.option_set_gpgdir(home)!
2418 db := handle.register_syncdb('core', 1024)!
2419 if _ := db.get_valid() {
2420 return error('accepted a signature after key import was declined')
2421 }
2422 target_error('database signature rejected: ' + handle.errno().strerror())
2423 })!
2424 assert run.err == '' && run.failed == 1, run.err
2425 questions := run.of('question')
2426 assert questions.len == 1
2427 assert questions[0]['question']!.str() == 'confirm'
2428 assert questions[0]['msg']!.str().starts_with('import pgp key ')
2429 assert questions[0]['msg']!.str().contains(signer.fingerprint[signer.fingerprint.len - 16..])
2430 messages := run.of('message').filter(it['text']!.str().starts_with('core: key "') && it['text']!.str().ends_with('" is unknown'))
2431 assert messages.len == 1
2432 ordered := run.events.filter(it['type']!.str() in ['message', 'question', 'error'])
2433 assert ordered.map(it['type']!.str()) == ['message', 'question', 'error']
2434 assert !verifier.gpg(['--with-colons', '--list-keys'])!.contains(signer.fingerprint)
2435 assert os.read_bytes(path)! == bytes
2436 assert os.read_bytes(path + '.sig')! == signature
2437 assert !s.lock_left()
2438}
2439
2440fn missing_import_key(_ voidptr, _ httpfixtures.Request) httpfixtures.Response {
2441 return httpfixtures.Response{
2442 body: 'info:1:0\n'
2443 headers: {
2444 'Content-Type': 'text/plain'
2445 }
2446 }
2447}
2448
2449fn test_failed_remote_key_lookup_reaches_frontends_after_the_import_question() ! {
2450 s := fake_system('database_remote_key_missing')!
2451 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2452 signer := signaturefixtures.create(s.path('signer-keys'))!
2453 defer { signaturefixtures.cleanup(signer.path) or { went_on('remove the signing keyring', err) } }
2454 verifier := signaturefixtures.empty(s.path('verification-keys'))!
2455 defer { signaturefixtures.cleanup(verifier.path) or { went_on('remove the verification keyring', err) } }
2456 environment := httpfixtures.local_only()!
2457 defer { environment.restore() or { went_on('restore the test proxy settings', err) } }
2458 mut server := httpfixtures.start(missing_import_key, unsafe { nil })!
2459 defer { server.close() or { went_on('close the test keyserver', err) } }
2460 config := os.join_path(verifier.path, 'gpg.conf')
2461 os.write_file(config, os.read_file(config)! + 'keyserver ${server.url.replace('http://', 'hkp://')}\n')!
2462 os.write_file(os.join_path(verifier.path, 'dirmngr.conf'), 'no-use-tor\nconnect-timeout 2\nconnect-quick-timeout 2\n')!
2463 path := s.path('db/sync/core.db')
2464 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'app-1-1/desc', text: '%DESC%\napp\n\n' }])
2465 os.write_file_array(path, bytes)!
2466 signer.sign(path, [signer.fingerprint], false)!
2467 sig := os.read_bytes(path + '.sig')!
2468 home := verifier.path
2469 run := s.run('{"id": 1, "answer": true}\n', fn [home] () ! {
2470 mut ui := new_trans_ui()
2471 handle := init_handle(ui)!
2472 defer { handle.release() or { went_on('release the alpm handle', err) } }
2473 defer { ui.stop() }
2474 handle.option_set_gpgdir(home)!
2475 db := handle.register_syncdb('core', 1024)!
2476 if _ := db.get_valid() { return error('accepted a signature without its remote key') }
2477 check(handle.errno() == .db_invalid_sig, 'missing remote key preserves the database signature error')!
2478 target_error('database signature rejected: ' + handle.errno().strerror())
2479 })!
2480 assert run.err == '' && run.failed == 1 && run.stdout == '', run.err
2481 assert run.of('question').len == 1
2482 messages := run.of('message')
2483 assert messages.len == 2
2484 assert messages[0]['text']!.str() == 'core: key "${signer.fingerprint}" is unknown'
2485 assert messages[1]['text']!.str() == 'key "${signer.fingerprint}" could not be looked up remotely'
2486 assert messages.all(it['warning']!.bool() && it['error']!.bool())
2487 ordered := run.events.filter(it['type']!.str() in ['message', 'question', 'error'])
2488 assert ordered.map(it['type']!.str()) == ['message', 'question', 'message', 'error']
2489 requests := server.snapshot()
2490 assert requests.len == 2 && requests.all(it.path.contains('op=index'))
2491 assert requests[0].path.contains(signer.fingerprint)
2492 assert requests[1].path.contains(signer.fingerprint[signer.fingerprint.len - 8..])
2493 assert !verifier.gpg(['--with-colons', '--list-keys'])!.contains(signer.fingerprint)
2494 assert os.read_bytes(path)! == bytes
2495 assert os.read_bytes(path + '.sig')! == sig
2496 assert !s.lock_left()
2497}
2498
2499fn test_package_info_preserves_metadata_at_the_source_archive_block_boundary() ! {
2500 s := fake_system('package_metadata_block_boundary')!
2501 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2502 path := s.path('repo/app.pkg.tar')
2503 os.write_file(path, '')!
2504 mut stat := C.stat{}
2505 assert C.stat(unsafe { &char(path.str) }, &stat) == 0
2506 block_size := if stat.st_blksize > u64(C.BUFSIZ) { int(stat.st_blksize) } else { int(C.BUFSIZ) }
2507 prefix := 'pkgname = app\npkgver = 1-1\npkgdesc = '
2508 text := prefix + 'x'.repeat(block_size - 512 - 10 - prefix.len) + '\x00pkgname = changed\n'
2509 bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: text }])
2510 os.write_file_array(path, bytes)!
2511 run := s.run('', fn [path] () ! {
2512 info(ConfigInfo{ file: true, fields: 'name,version', query: [path] })!
2513 })!
2514 assert run.err == '' && run.failed == 0, run.err
2515 assert run.of('info').len == 1
2516 mut fields := map[string]string{}
2517 for raw in run.of('info')[0]['fields']!.as_array() {
2518 field := raw.as_map()
2519 fields[field['field']!.str()] = field['value']!.str()
2520 }
2521 assert fields['name'] == 'changed'
2522 assert fields['version'] == '1-1'
2523 assert os.read_bytes(path)! == bytes
2524 assert !s.lock_left()
2525}
2526
2527fn test_info_preserves_partial_metadata_and_delivers_its_warning() ! {
2528 s := fake_system('info_partial_metadata')!
2529 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2530 s.install_local(fake_pkg('app', '1.0-1', []))!
2531 path := s.path('db/local/app-1.0-1/desc')
2532 text := '%NAME%\napp\n\n%VERSION%\n1.0-1\n\n%DESC%\nkept\n\n%REASON%\n1\n\n%FUTURE%\nignored\n\n%XDATA%\na=b\ninvalid\n\n'
2533 os.write_file(path, text)!
2534 run := s.run('', fn () ! {
2535 info(ConfigInfo{ fields: 'name,description,install_reason', query: ['local/app'] })!
2536 })!
2537 assert run.err == '' && run.failed == 0, run.err
2538 infos := run.of('info')
2539 assert infos.len == 1
2540 mut values := map[string]string{}
2541 for raw in infos[0]['fields']!.as_array() {
2542 field := raw.as_map()
2543 values[field['field']!.str()] = field['value']!.str()
2544 }
2545 assert values['name'] == 'app'
2546 assert values['description'] == 'kept'
2547 assert values['install_reason'] == reason_to_str(.depend)
2548 messages := run.of('message').filter(it['text']!.str().contains("unknown key '%FUTURE%' in local database"))
2549 assert messages.len == 1
2550 assert messages[0]['warning']!.bool()
2551 assert !(messages[0]['error'] or { json2.Any(false) }).bool()
2552 assert os.read_file(path)! == text
2553 assert !s.lock_left()
2554}
2555
2556fn test_info_delivers_a_missing_metadata_file_error_without_writing_the_db() ! {
2557 s := fake_system('info_missing_metadata')!
2558 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2559 s.install_local(fake_pkg('app', '1.0-1', []))!
2560 path := s.path('db/local/app-1.0-1/desc')
2561 os.rm(path)!
2562 run := s.run('', fn () ! {
2563 info(ConfigInfo{ fields: 'name,description', query: ['local/app'] })!
2564 })!
2565 assert run.err == '' && run.failed == 0, run.err
2566 assert run.of('info').len == 1
2567 messages := run.of('message').filter(it['text']!.str().contains('could not open file ' + path + ':'))
2568 assert messages.len == 1
2569 assert messages[0]['warning']!.bool()
2570 assert messages[0]['error']!.bool()
2571 assert !os.exists(path)
2572 assert os.is_dir(os.dir(path))
2573 assert !s.lock_left()
2574}
2575
2576fn test_info_reports_invalid_and_duplicate_local_entries() ! {
2577 s := fake_system('info_local_entries')!
2578 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2579 s.install_local(fake_pkg('app', '1.0-1', []))!
2580 os.mkdir(s.path('db/local/broken'))!
2581 os.mkdir(s.path('db/local/app-2.0-1'))!
2582 before := os.read_file(s.path('db/local/app-1.0-1/desc'))!
2583 run := s.run('', fn () ! {
2584 info(ConfigInfo{ fields: 'name,version', query: ['local/app'] })!
2585 })!
2586 assert run.err == '' && run.failed == 0, run.err
2587 assert run.of('info').len == 1
2588 for text in ["invalid name for database entry 'broken'", "duplicated database entry 'app'"] {
2589 messages := run.of('message').filter(it['text']!.str() == text)
2590 assert messages.len == 1, text
2591 assert messages[0]['warning']!.bool()
2592 assert messages[0]['error']!.bool()
2593 }
2594 assert os.read_file(s.path('db/local/app-1.0-1/desc'))! == before
2595 assert os.is_dir(s.path('db/local/broken'))
2596 assert os.is_dir(s.path('db/local/app-2.0-1'))
2597 assert !os.exists(s.path('db/local/app-2.0-1/desc'))
2598 assert !s.lock_left()
2599}
2600
2601struct LocalCacheReadFault {
2602 path string
2603mut:
2604 closed bool
2605}
2606
2607fn local_cache_read_fault_log(context voidptr, level alpm.LogLevel, message &u8) {
2608 mut fault := unsafe { &LocalCacheReadFault(context) }
2609 if fault.closed || !level.has(.function) { return }
2610 if unsafe { cstring_to_vstring(message) } != 'loading package data for app : level=0x1\n' {
2611 return
2612 }
2613 for name in os.ls('/proc/self/fd') or {
2614 assert false, err.msg()
2615 []string{}
2616 } {
2617 actual := os.readlink('/proc/self/fd/' + name) or { continue }
2618 if actual == fault.path {
2619 assert C.close(i32(name.int())) == 0
2620 fault.closed = true
2621 break
2622 }
2623 }
2624 assert fault.closed
2625}
2626
2627fn test_local_cache_read_failure_is_reported_and_can_be_retried() ! {
2628 s := fake_system('local_cache_read_fault')!
2629 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2630 s.install_local(fake_pkg('app', '1.0-1', []))!
2631 before := os.read_file(s.path('db/local/app-1.0-1/desc'))!
2632 mut fault := &LocalCacheReadFault{ path: s.path('db/local') }
2633 run := s.run('', fn [fault] () ! {
2634 mut ui := new_trans_ui()
2635 handle := init_handle(ui)!
2636 defer { handle.release() or { went_on('release the alpm handle', err) } }
2637 defer { ui.stop() }
2638 handle.option_set_logcb_line(local_cache_read_fault_log, fault)!
2639 mut failed := false
2640 if _ := local_pkgcache(handle) {
2641 return error('accepted an incomplete local cache')
2642 } else {
2643 target_error(err.msg())
2644 failed = true
2645 }
2646 check(failed, 'the failed cache was reported')!
2647 recovered := local_pkgcache(handle)!
2648 check(recovered.pkgs().len == 1, 'retry recovered the installed package')!
2649 })!
2650 assert fault.closed
2651 assert run.err == '' && run.failed == 1, run.err
2652 messages := target_errors(run).filter(it.starts_with('could not read the packages of local:'))
2653 assert messages.len == 1
2654 assert os.read_file(s.path('db/local/app-1.0-1/desc'))! == before
2655 assert !s.lock_left()
2656}
2657
2658fn test_local_database_file_reports_an_open_error_without_replacing_it() ! {
2659 s := fake_system('local_db_file')!
2660 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2661 path := s.path('db/local')
2662 os.rmdir_all(path)!
2663 os.write_file(path, 'keep this file')!
2664 run := s.run('', fn () ! {
2665 info(ConfigInfo{ fields: 'name', query: ['local/app'] }) or {
2666 check(err.code() == int(alpm.Errno.db_open), 'initialization error kind is preserved')!
2667 return err
2668 }
2669 })!
2670 assert run.err.contains(alpm.Errno.db_open.strerror()), run.err
2671 assert run.of('info').len == 0
2672 assert os.read_file(path)! == 'keep this file'
2673 assert !s.lock_left()
2674}
2675
2676fn test_empty_database_creation_does_not_reopen_a_write_only_version_file() ! {
2677 s := fake_system('local_db_umask')!
2678 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2679 version := s.path('db/local/ALPM_DB_VERSION')
2680 os.rm(version)!
2681 run := s.run('', fn () ! {
2682 prior := C.umask(0o444)
2683 defer { C.umask(prior) }
2684 mut ui := new_trans_ui()
2685 handle := init_handle(ui)!
2686 defer { handle.release() or { went_on('release the alpm handle', err) } }
2687 defer { ui.stop() }
2688 packages := local_pkgcache(handle)!
2689 check(packages.pkgs().len == 0, 'new local database is empty')!
2690 })!
2691 assert run.err == '' && run.failed == 0, run.err
2692 assert os.stat(version)!.mode & 0o777 == 0o222
2693 os.chmod(version, 0o644)!
2694 assert os.read_file(version)! == '9\n'
2695 assert !s.lock_left()
2696}
2697
2698fn test_info_accepts_the_source_unsigned_local_version_format() ! {
2699 s := fake_system('local_db_numeric_version')!
2700 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2701 s.install_local(fake_pkg('app', '1.0-1', []))!
2702 path := s.path('db/local/ALPM_DB_VERSION')
2703 text := '-${u64(C.SIZE_MAX) - 8} trailing\n'
2704 os.write_file(path, text)!
2705 run := s.run('', fn () ! {
2706 info(ConfigInfo{ fields: 'name,version', query: ['local/app'] })!
2707 })!
2708 assert run.err == '' && run.failed == 0, run.err
2709 assert run.of('info').len == 1
2710 assert os.read_file(path)! == text
2711 assert !s.lock_left()
2712}
2713
2714fn test_repository_cache_preserves_initial_and_cached_failure_kinds() ! {
2715 s := fake_system('repo_cache_kinds')!
2716 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2717 path := s.path('db/sync/core.db')
2718 text := '\xff\x00not-an-archive'
2719 os.write_file(path, text)!
2720 run := s.run('', fn () ! {
2721 mut ui := new_trans_ui()
2722 handle := init_handle(ui)!
2723 defer { handle.release() or { went_on('release the alpm handle', err) } }
2724 defer { ui.stop() }
2725 db := handle.register_syncdb('core', 0)!
2726 for kind in [alpm.Errno.db_open, .db_invalid] {
2727 if _ := pkgcache_of(handle, db) {
2728 return error('accepted a corrupt repository')
2729 } else {
2730 check(handle.errno() == kind, 'repository cache failure kind is preserved')!
2731 target_error(err.msg())
2732 }
2733 }
2734 })!
2735 assert run.err == '' && run.failed == 2, run.err
2736 errors := target_errors(run)
2737 assert errors.len == 2
2738 assert errors[0].contains(alpm.Errno.db_open.strerror())
2739 assert errors[1].contains(alpm.Errno.db_invalid.strerror())
2740 assert !errors[1].contains(alpm.Errno.db_invalid_sig.strerror())
2741 assert run.of('message').any(it['text']!.str().starts_with('could not open file ' + path + ':'))
2742 assert os.read_file(path)! == text
2743 assert !s.lock_left()
2744}
2745
2746fn test_repository_read_retry_recovers_packages_and_groups() ! {
2747 s := fake_system('repo_cache_retry')!
2748 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2749 path := s.path('db/sync/core.db')
2750 good := archivefixtures.tar_bytes([
2751 archivefixtures.Entry{ name: 'app-1.0-1/desc', text: '%FILENAME%\napp.pkg.tar\n\n%GROUPS%\ntools\n\n' },
2752 archivefixtures.Entry{ name: 'next-1.0-1/desc', text: '%FILENAME%\nnext.pkg.tar\n\n' },
2753 ])
2754 os.write_file_array(path, good[..1124])!
2755 run := s.run('', fn [path, good] () ! {
2756 mut ui := new_trans_ui()
2757 handle := init_handle(ui)!
2758 defer { handle.release() or { went_on('release the alpm handle', err) } }
2759 defer { ui.stop() }
2760 db := handle.register_syncdb('core', 0)!
2761 if _ := pkgcache_of(handle, db) {
2762 return error('accepted a truncated repository')
2763 } else {
2764 check(handle.errno() == .libarchive, 'archive read failure is preserved')!
2765 target_error(err.msg())
2766 }
2767 check(db.get_valid()!, 'header-read failure permits retry')!
2768 if _ := db.get_group('tools') {
2769 return error('accepted groups from a truncated repository')
2770 }
2771 check(handle.errno() == .libarchive, 'failed group load preserves the read error')!
2772 os.write_file_array(path, good)!
2773 recovered := pkgcache_of(handle, db)!
2774 check(recovered.pkgs().len == 2, 'retry recovered both packages')!
2775 group := db.get_group('tools') or { return error('retry hid the package group') }
2776 check(group.get_name() == 'tools', 'retry recovered the group')!
2777 })!
2778 assert run.err == '' && run.failed == 1, run.err
2779 assert target_errors(run).len == 1
2780 assert os.read_bytes(path)! == good
2781 assert !s.lock_left()
2782}
2783
2784fn test_sync_metadata_warnings_and_final_newline_reach_frontends() ! {
2785 s := fake_system('sync_metadata_warnings')!
2786 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2787 path := s.path('db/sync/core.db')
2788 bytes := archivefixtures.tar_bytes([
2789 archivefixtures.Entry{ name: 'app-1.0-1/desc', text: '%NAME%\nwrong\n\n%FUTURE%\nignored\n\n%DESC%\na description\n\n%GROUPS%\ntools\n' },
2790 archivefixtures.Entry{ name: 'loose-1.0-1', text: 'ignored' },
2791 ])
2792 os.write_file_array(path, bytes)!
2793 run := s.run('', fn () ! {
2794 mut ui := new_trans_ui()
2795 handle := init_handle(ui)!
2796 defer { handle.release() or { went_on('release the alpm handle', err) } }
2797 defer { ui.stop() }
2798 db := handle.register_syncdb('core', 0)!
2799 packages := pkgcache_of(handle, db)!
2800 check(packages.pkgs().len == 2, 'both archive entries remain available')!
2801 pkg := db.get_pkg('app') or { return error('missing repository package') }
2802 check(pkg.get_desc() == 'a description', 'warning does not hide package metadata')!
2803 check(pkg.get_groups().strs() == ['tools'], 'final newline terminates a metadata list')!
2804 })!
2805 assert run.err == '' && run.failed == 0, run.err
2806 wanted := ['core database is inconsistent: name mismatch on package app',
2807 "app: unknown key '%FUTURE%' in sync database", 'unknown database file: loose-1.0-1']
2808 messages := run.of('message').filter(it['text']!.str() in wanted)
2809 assert messages.map(it['text']!.str()) == wanted
2810 assert messages.all(it['warning']!.bool())
2811 assert messages[0]['error']!.bool()
2812 assert !(messages[1]['error'] or { json2.Any(false) }).bool()
2813 assert !(messages[2]['error'] or { json2.Any(false) }).bool()
2814 assert os.read_bytes(path)! == bytes
2815 assert !s.lock_left()
2816}
2817
2818fn test_sync_metadata_errors_report_each_bad_entry_without_a_partial_cache() ! {
2819 s := fake_system('sync_metadata_errors')!
2820 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
2821 path := s.path('db/sync/core.db')
2822 bytes := archivefixtures.tar_bytes([
2823 archivefixtures.Entry{ name: 'app-1.0-1/desc', text: '%FILENAME%\n/illegal\n\n' },
2824 archivefixtures.Entry{ name: 'next-1.0-1/desc', text: '%VERSION%\nwrong\n\n%DATA%\ninvalid\n\n' },
2825 archivefixtures.Entry{ name: 'last-1.0-1/desc', text: '%DESC%\nlast package\n\n' },
2826 ])
2827 os.write_file_array(path, bytes)!
2828 run := s.run('', fn () ! {
2829 mut ui := new_trans_ui()
2830 handle := init_handle(ui)!
2831 defer { handle.release() or { went_on('release the alpm handle', err) } }
2832 defer { ui.stop() }
2833 db := handle.register_syncdb('core', 0)!
2834 if _ := pkgcache_of(handle, db) {
2835 return error('accepted malformed metadata')
2836 } else {
2837 target_error(err.msg())
2838 }
2839 if _ := db.get_pkgcache() { return error('retained a partial repository cache') }
2840 check(handle.errno() == .db_invalid, 'malformed metadata keeps the database invalid')!
2841 })!
2842 assert run.err == '' && run.failed == 1, run.err
2843 wanted := ['core database is inconsistent: filename of package app is illegal',
2844 "could not parse package description file 'app-1.0-1/desc' from db 'core'",
2845 'core database is inconsistent: version mismatch on package next',
2846 "could not parse package description file 'next-1.0-1/desc' from db 'core'"]
2847 messages := run.of('message').filter(it['text']!.str() in wanted)
2848 assert messages.map(it['text']!.str()) == wanted
2849 assert messages.all(it['warning']!.bool() && it['error']!.bool())
2850 assert target_errors(run).len == 1
2851 assert os.read_bytes(path)! == bytes
2852 assert !s.lock_left()
2853}
2854
2855fn test_info_scopes_and_satisfiers() ! {
2856 s := fake_system('infoscope')!
2857 defer { os.rmdir_all(s.tmp) or {} }
2858 s.install_local(FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] })!
2859 s.publish([fake_pkg('bash', '2.0-1', []), fake_pkg('zsh', '1.0-1', [])])!
2860 version_of := fn (run FrontendRun) string {
2861 for f in run.of('info')[0]['fields'] or { json2.Any([]json2.Any{}) }.as_array() {
2862 m := f.as_map()
2863 if m['field'] or { json2.Any('') }.str() == 'version' {
2864 return m['value'] or { json2.Any('') }.str()
2865 }
2866 }
2867 return ''
2868 }
2869 // bare: the installed one; core/: the repo's; a provider resolves
2870 for target, version in {
2871 'bash': '1.0-1'
2872 'local/bash': '1.0-1'
2873 'core/bash': '2.0-1'
2874 'sh': '1.0-1'
2875 'bash>=2': '2.0-1'
2876 } {
2877 run := s.run('', fn [target] () ! {
2878 info(ConfigInfo{ noconfirm: true, query: [target] })!
2879 })!
2880 assert run.failed == 0, target
2881 assert version_of(run) == version, target
2882 }
2883 // local/ never reaches the sync dbs, and an unknown repo is an error
2884 for target, msg in {
2885 'local/zsh': 'unknown package: "zsh"'
2886 'nope/bash': 'database not found: nope'
2887 } {
2888 run := s.run('', fn [target] () ! {
2889 info(ConfigInfo{ noconfirm: true, query: [target] })!
2890 })!
2891 assert target_errors(run) == [msg], target
2892 }
2893}
2894
2895fn test_search_local_groups_and_all_members() ! {
2896 s := fake_system('localgroups')!
2897 defer { os.rmdir_all(s.tmp) or {} }
2898 s.install_local(tool('aa'))!
2899 s.install_local(fake_pkg('plain', '1.0-1', []))!
2900 s.publish([tool('aa'), tool('bb'), FakePkg{
2901 ...fake_pkg('cc', '1.0-1', [])
2902 groups: [
2903 'extras',
2904 ]
2905 }])!
2906 names := fn (run FrontendRun) []string {
2907 return run.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().map('${it.as_map()['group'] or {
2908 json2.Any('')
2909 }.str()} ${it.as_map()['name'] or { json2.Any('') }.str()}')
2910 }
2911 // -l -g: the local db's groups, the installed members alone
2912 local := s.run('', fn () ! {
2913 search(ConfigSearch{ local: true, groups: true, query: ['tools'] })!
2914 })!
2915 assert local.err == '', local.err
2916 assert names(local) == ['tools aa']
2917 bare := s.run('', fn () ! {
2918 search(ConfigSearch{ local: true, groups: true })!
2919 })!
2920 groups := bare.of('groups')[0]['groups']!.as_array().map(it.as_map())
2921 assert groups.len == 1
2922 assert groups[0]['repo']!.str() == 'local' && groups[0]['name']!.str() == 'tools'
2923 // -gg: every group of the sync dbs with its members
2924 all := s.run('', fn () ! {
2925 search(ConfigSearch{ remote: true, groups: true, groups_level: 2 })!
2926 })!
2927 mut got := names(all)
2928 got.sort()
2929 assert got == ['extras cc', 'tools aa', 'tools bb']
2930 tty := s.run_ui('tty', '', fn () ! {
2931 search(ConfigSearch{ local: true, groups: true, groups_level: 2 })!
2932 })!
2933 assert tty.stdout == 'tools aa\n', tty.stdout
2934 // a sync-comparing filter on the sync groups: the dbs are registered
2935 // once, and only the installed member can pass
2936 native := s.run('', fn () ! {
2937 search(ConfigSearch{ remote: true, groups: true, native: true, query: ['tools'] })!
2938 })!
2939 assert native.err == '', native.err
2940 assert names(native) == ['tools aa']
2941 // the terminal's table leads with the group, as the ipc entries carry it
2942 named := s.run_ui('tty', '', fn () ! {
2943 search(ConfigSearch{ remote: true, groups: true, fields: 'name', query: ['tools'] })!
2944 })!
2945 assert named.err == '', named.err
2946 assert named.stdout.split_into_lines().map(it.fields().join(' ')) == ['tools aa', 'tools bb'], named.stdout
2947}
2948
2949fn test_owner_quiet_names_the_package_alone() ! {
2950 s := fake_system('ownerquiet')!
2951 defer { os.rmdir_all(s.tmp) or {} }
2952 s.install_local(foo('1.0-1', 'one'))!
2953 path := s.path('root/usr/share/foo/hello')
2954 run := s.run_ui('tty', '', fn [path] () ! {
2955 owner(ConfigOwner{ quiet: true, query: [path] })!
2956 })!
2957 assert run.err == ''
2958 assert run.stdout == 'foo\n', run.stdout
2959}
2960
2961fn test_find_regex_and_machinereadable() ! {
2962 s := with_file_dbs('findregex', [
2963 FakePkg{
2964 name: 'bar'
2965 files: {
2966 'usr/bin/bar': 'bar'
2967 'usr/share/bar/x': 'x'
2968 }
2969 },
2970 FakePkg{
2971 name: 'baz'
2972 files: {
2973 'usr/bin/baz': 'baz'
2974 }
2975 },
2976 ])!
2977 defer { os.rmdir_all(s.tmp) or {} }
2978 // without a slash the expression is tried on file names, case ignored
2979 names := s.run('', fn () ! {
2980 find(ConfigFind{ regex: true, query: ['^BA.$'] })!
2981 })!
2982 assert providers_of(names)['^BA.$']! == ['bar', 'baz']
2983 // with one, on whole paths
2984 paths := s.run('', fn () ! {
2985 find(ConfigFind{ regex: true, query: ['share/.*x$', '/usr/bin/ba[rz]'] })!
2986 })!
2987 got := providers_of(paths)
2988 assert got['share/.*x$']! == ['bar']
2989 assert got['/usr/bin/ba[rz]']! == ['bar', 'baz']
2990 // a bad expression is named and nothing is searched
2991 bad := s.run('', fn () ! {
2992 find(ConfigFind{ regex: true, query: ['(', 'bar'] })!
2993 })!
2994 assert target_errors(bad) == ["invalid regular expression '('"]
2995 assert bad.of('provides').len == 0
2996 // pacman's --machinereadable: repo, package, version, path, NUL parted
2997 machine := s.run_ui('tty', '', fn () ! {
2998 find(ConfigFind{ regex: true, machinereadable: true, query: ['usr/bin/ba.'] })!
2999 })!
3000 assert machine.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\ncore\0baz\x001.0-1\0usr/bin/baz\n', machine.stdout.bytes().str()
3001 exact := s.run_ui('tty', '', fn () ! {
3002 find(ConfigFind{ machinereadable: true, query: ['/usr/bin/bar'] })!
3003 })!
3004 assert exact.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\n', exact.stdout.bytes().str()
3005 list := s.run_ui('tty', '', fn () ! {
3006 find(ConfigFind{ list: true, machinereadable: true, query: ['baz'] })!
3007 })!
3008 assert list.stdout.split('\n')[2] == 'core\0baz\x001.0-1\0usr/bin/baz', list.stdout.bytes().str()
3009 // an expression's event names the files it matched, one list a package
3010 matched := paths.of('provides').filter(it['path']!.str() == 'share/.*x$')
3011 assert matched[0]['files']!.as_array().map(it.as_array().map(it.str())) == [
3012 ['usr/share/bar/x'],
3013 ]
3014}
3015
3016fn test_find_names_slashes_and_scoped_lists() ! {
3017 s := with_file_dbs('findnames', [
3018 FakePkg{
3019 name: 'bar'
3020 files: {
3021 'usr/bin/bar': 'bar'
3022 'usr/share/bar/x': 'x'
3023 }
3024 },
3025 FakePkg{
3026 name: 'baz'
3027 files: {
3028 'usr/bin/baz': 'baz'
3029 }
3030 },
3031 ])!
3032 defer { os.rmdir_all(s.tmp) or {} }
3033 // a target with no slash is a file name: the directory usr/share/bar/
3034 // has none, the file usr/bin/bar does
3035 name := s.run('', fn () ! {
3036 find(ConfigFind{ query: ['bar'] })!
3037 })!
3038 assert providers_of(name)['bar']! == ['bar']
3039 assert name.of('provides')[0]['files']!.as_array().map(it.as_array().map(it.str())) == [
3040 ['usr/bin/bar'],
3041 ]
3042 // a trailing slash on a file's path answers the same alone as among
3043 // others: the walk and the index match it the same way
3044 alone := s.run('', fn () ! {
3045 find(ConfigFind{ query: ['/usr/bin/bar/'] })!
3046 })!
3047 among := s.run('', fn () ! {
3048 find(ConfigFind{ query: ['/usr/bin/bar/', '/usr/bin/baz'] })!
3049 })!
3050 assert providers_of(alone)['/usr/bin/bar/']! == ['bar']
3051 assert providers_of(among)['/usr/bin/bar/']! == ['bar']
3052 // slashes alone never become the empty expression
3053 assert find_rel('//') == '/' && find_rel('/usr/bin') == 'usr/bin' && find_rel('x') == 'x'
3054 // -l takes repo/package, and lists the package before the path
3055 scoped := s.run_ui('tty', '', fn () ! {
3056 find(ConfigFind{ list: true, query: ['core/baz'] })!
3057 })!
3058 assert scoped.err == '', scoped.err
3059 assert scoped.stdout.split_into_lines().map(it.fields().join(' ')) == ['baz usr/', 'baz usr/bin/',
3060 'baz usr/bin/baz'], scoped.stdout
3061 other := s.run('', fn () ! {
3062 find(ConfigFind{ list: true, query: ['nope/baz', 'core/'] })!
3063 })!
3064 assert other.of('files').len == 0
3065 assert target_errors(other).len == 2
3066}
3067
3068fn test_clean_levels_and_unused_sync_dbs() ! {
3069 s := fake_system('cleandbs')!
3070 defer { os.rmdir_all(s.tmp) or {} }
3071 s.install_local(foo('1.0-1', 'one'))!
3072 for f in ['foo-1.0-1-any.pkg.tar.zst', 'gone-1.0-1-any.pkg.tar.zst'] {
3073 os.write_file(s.path('cache/${f}'), 'x')!
3074 }
3075 // core is configured; old is a repo the config dropped
3076 for f in ['core.db', 'core.files', 'old.db', 'old.db.sig', 'old.files', 'vpac.synced'] {
3077 os.write_file(s.path('db/sync/${f}'), 'x')!
3078 }
3079 preview := s.run('', fn () ! {
3080 clean(ConfigClean{ print_only: true })!
3081 })!
3082 assert preview.err == '', preview.err
3083 ev := preview.of('clean')[0].clone()
3084 assert ev['files']!.as_array().map(os.base(it.str())) == ['gone-1.0-1-any.pkg.tar.zst']
3085 assert ev['dbs']!.as_array().map(os.base(it.str())) == ['old.db', 'old.db.sig', 'old.files']
3086 // -cc is every cached package, the installed one too
3087 all := s.run('', fn () ! {
3088 clean(ConfigClean{ print_only: true, level: 2 })!
3089 })!
3090 assert all.of('clean')[0]['files']!.as_array().len == 2
3091 run := s.run('', fn () ! {
3092 clean(ConfigClean{ noconfirm: true, level: 1 })!
3093 })!
3094 assert run.err == '', run.err
3095 mut left := os.ls(s.path('db/sync'))!
3096 left.sort()
3097 assert left == ['core.db', 'core.files', 'vpac.synced']
3098 assert os.ls(s.path('cache'))! == ['foo-1.0-1-any.pkg.tar.zst']
3099}
3100
3101// dead_mirror aims the repo at a server that has nothing: every refresh
3102// against it fails
3103fn (s FakeSystem) dead_mirror() {
3104 cfg_repos = [CfgRepo{
3105 name: 'core'
3106 kind: 'sync'
3107 servers: ['file://' + s.path('nowhere')]
3108 }]
3109}
3110
3111fn test_a_failed_refresh_is_an_error() ! {
3112 s := fake_system('deadmirror')!
3113 defer { os.rmdir_all(s.tmp) or {} }
3114 s.install_local(foo('1.0-1', 'one'))!
3115 s.publish([foo('2.0-1', 'two')])!
3116 up := s.run_ui('tty', '', fn [s] () ! {
3117 s.dead_mirror()
3118 upgrade(ConfigUpgrade{ noconfirm: true, sync_dbs: true })!
3119 })!
3120 se := s.run('', fn [s] () ! {
3121 s.dead_mirror()
3122 search(ConfigSearch{ remote: true, sync_dbs: true, query: ['foo'] })!
3123 })!
3124 fy := s.run('', fn [s] () ! {
3125 s.dead_mirror()
3126 find(ConfigFind{ refresh: true, query: ['/usr/share/foo/hello'] })!
3127 })!
3128 assert up.err != ''
3129 assert se.err != ''
3130 assert fy.err != ''
3131 assert s.installed()!['foo']! == '1.0-1'
3132 // no server left to fall through to: the held 404 is said, an error
3133 said := se.of('message').filter(it['text'] or { json2.Any('') }.str().contains('failed retrieving'))
3134 assert said.len == 1
3135 assert said[0]['error'] or { json2.Any(false) }.bool()
3136}
3137
3138// --pkgbuild on an upgrade: the candidates are the locally installed
3139// packages the sync dbs do not carry, the held and ignored ones left out,
3140// and only a pkgbuild version the installed one does not come up to is one
3141fn test_pkgbuild_upgrade_pass_picks_the_foreign_newer_ones() ! {
3142 s := fake_system('pkgbuildupgrade')!
3143 defer { os.rmdir_all(s.tmp) or {} }
3144 s.install_local(foo('1.0-1', 'one')) or { return error('at install_local: ${err.msg()}') }
3145 s.install_local(FakePkg{
3146 name: 'aurpkg'
3147 version: '1.0-1'
3148 files: {
3149 'usr/share/aurpkg/hello': 'one'
3150 }
3151 }) or { return error('at install_local aurpkg: ${err.msg()}') }
3152 s.publish([foo('2.0-1', 'two')]) or { return error('at publish: ${err.msg()}') }
3153 mut handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/') or {
3154 return error('at initialize: ${err.msg()}')
3155 }
3156 defer { handle.release() or { went_on('release the alpm handle', err) } }
3157 cfg_repos = [CfgRepo{
3158 name: 'core'
3159 kind: 'sync'
3160 servers: ['file://' + s.path('repo')]
3161 }]
3162 init_repos(mut handle) or { return error('at init_repos: ${err.msg()}') }
3163 // foo is the sync db's to upgrade; aurpkg the repos do not carry
3164 mut foreign := foreign_pkgs(handle) or { return error('at foreign_pkgs: ${err.msg()}') }
3165 assert foreign.map(it.get_name()) == ['aurpkg']
3166 // the config's held packages stay out, libalpm's own ignore check
3167 handle.option_add_ignore_pkg('aurpkg') or { return error('at add_ignore: ${err.msg()}') }
3168 assert foreign_pkgs(handle)!.len == 0
3169 handle.option_remove_ignore_pkg('aurpkg') or { return error('at remove_ignore: ${err.msg()}') }
3170 foreign = foreign_pkgs(handle) or { return error('at foreign_pkgs2: ${err.msg()}') }
3171 assert foreign.map(it.get_name()) == ['aurpkg']
3172 // a newer record is the upgrade; the same and an older are not offered,
3173 // and a name the sync dbs carry is no candidate whatever its record says
3174 found := {
3175 'aurpkg': PackagePkgbuild{ name: 'aurpkg', version: '1.1-1' }
3176 'foo': PackagePkgbuild{ name: 'foo', version: '9.9-1' }
3177 }
3178 up := foreign_upgrades(foreign, found)
3179 assert up.map(it.info.name) == ['aurpkg']
3180 for v in ['0.9-1', '1.0-1'] {
3181 assert foreign_upgrades(foreign, {
3182 'aurpkg': PackagePkgbuild{ name: 'aurpkg', version: v }
3183 }).len == 0
3184 }
3185}
3186
3187// a build installs what it makes, so download-only refuses the pkgbuild pass
3188// before any of the run's work, as install's does
3189fn test_upgrade_refuses_download_only_pkgbuild() ! {
3190 s := fake_system('pkgupgdownonly')!
3191 defer { os.rmdir_all(s.tmp) or {} }
3192 s.install_local(foo('1.0-1', 'one'))!
3193 s.publish([foo('2.0-1', 'two')])!
3194 up := s.run('', fn () ! {
3195 upgrade(ConfigUpgrade{ noconfirm: false, download_only: true, pkgbuild: true })!
3196 })!
3197 assert up.err.contains('download-only does not build pkgbuild packages'), up.err
3198 // nothing of the run went ahead: the upgrade is not half-done
3199 assert s.installed()!['foo']! == '1.0-1'
3200}
3201
3202// --noconfirm would skip the per-package verification a pkgbuild build
3203// needs — makepkg runs what the PKGBUILD says — so the pass is refused
3204// before any of the run's work, naming the way to have it anyway
3205fn test_upgrade_refuses_noconfirm_pkgbuild() ! {
3206 s := fake_system('pkgupgnoconfirm')!
3207 defer { os.rmdir_all(s.tmp) or {} }
3208 s.install_local(foo('1.0-1', 'one'))!
3209 s.publish([foo('2.0-1', 'two')])!
3210 up := s.run('', fn () ! {
3211 upgrade(ConfigUpgrade{ noconfirm: true, pkgbuild: true })!
3212 })!
3213 assert up.err.contains('the pkgbuild upgrades are asked about'), up.err
3214 assert up.err.contains('--nopkgbuildconfirm'), up.err
3215 // the refusal is said before the sync upgrade, not after it
3216 assert s.installed()!['foo']! == '1.0-1'
3217}
3218
3219// a mirror that lacks the package falls through to the next server: libalpm
3220// tries a repo's servers in order, and a file the first one does not have
3221// moves it on — the way a mirror that has not synced the archive yet is met.
3222// the first server here serves the db alone, the way a lagging mirror does,
3223// and the archive lives on the second
3224fn test_a_mirror_without_the_package_falls_through_to_the_next() ! {
3225 s := fake_system('fallback')!
3226 defer { os.rmdir_all(s.tmp) or {} }
3227 s.install_local(foo('1.0-1', 'one'))!
3228 s.publish([foo('2.0-1', 'two')])!
3229 // the lagging mirror: the db the primary serves, none of the archives
3230 lag := s.path('lag')
3231 os.mkdir_all(lag)!
3232 os.cp(s.path('repo/core.db'), os.join_path(lag, 'core.db'))!
3233 os.cp(s.path('repo/core.files'), os.join_path(lag, 'core.files'))!
3234 up := s.run('', fn [s, lag] () ! {
3235 cfg_repos = [CfgRepo{
3236 name: 'core'
3237 kind: 'sync'
3238 servers: ['file://' + lag, 'file://' + s.path('repo')]
3239 }]
3240 upgrade(ConfigUpgrade{ noconfirm: true })!
3241 })!
3242 assert up.err == '', up.err
3243 assert s.installed()!['foo']! == '2.0-1'
3244 // the fallback is an event a frontend sees: the archive's download says
3245 // retry, then completes
3246 retries := up.of('download').filter(it['retry'] or { json2.Any(false) }.bool())
3247 assert retries.len == 1
3248 assert (retries[0]['file'] or { json2.Any('') }).str() == 'foo-2.0-1-any.pkg.tar'
3249 // the 404 the lagging mirror got is not said: a mirror served the file
3250 said := up.of('message').filter(it['text'] or { json2.Any('') }.str().contains('failed retrieving'))
3251 assert said.len == 0
3252}
3253
3254// --verbose says the mirror's 404 as it comes, even when the fallback finds
3255// the file on the next mirror: the verbose log tells a run's whole story
3256fn test_verbose_says_the_fallback_error() ! {
3257 s := fake_system('fallbackverbose')!
3258 defer { os.rmdir_all(s.tmp) or {} }
3259 s.install_local(foo('1.0-1', 'one'))!
3260 s.publish([foo('2.0-1', 'two')])!
3261 lag := s.path('lag')
3262 os.mkdir_all(lag)!
3263 os.cp(s.path('repo/core.db'), os.join_path(lag, 'core.db'))!
3264 os.cp(s.path('repo/core.files'), os.join_path(lag, 'core.files'))!
3265 saved_verbose := verbose_flag
3266 defer {
3267 verbose_flag = saved_verbose
3268 }
3269 up := s.run('', fn [s, lag] () ! {
3270 verbose_flag = true
3271 cfg_repos = [CfgRepo{
3272 name: 'core'
3273 kind: 'sync'
3274 servers: ['file://' + lag, 'file://' + s.path('repo')]
3275 }]
3276 upgrade(ConfigUpgrade{ noconfirm: true })!
3277 })!
3278 assert up.err == '', up.err
3279 assert s.installed()!['foo']! == '2.0-1'
3280 said := up.of('message').filter(it['text'] or { json2.Any('') }.str().contains('failed retrieving'))
3281 assert said.len == 1
3282 assert (said[0]['text'] or { json2.Any('') }).str().contains('from disk')
3283}
3284
3285// check is an assertion inside a run's closure, where a failed assert would
3286// leave the fake system's redirected fds behind: it fails the run instead
3287fn check(ok bool, what string) ! {
3288 if !ok {
3289 return error('check failed: ${what}')
3290 }
3291}
3292
3293fn test_targets_resolve_by_scope_version_and_provision() ! {
3294 s := fake_system('targets')!
3295 defer { os.rmdir_all(s.tmp) or {} }
3296 s.install_local(fake_pkg('app', '1.0-1', ['lib']))!
3297 s.install_local(FakePkg{
3298 ...fake_pkg('impl', '1.0-1', [])
3299 provides: ['virt=2']
3300 })!
3301 s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []), FakePkg{
3302 ...fake_pkg('simpl', '1.0-1', [])
3303 provides: ['svirt=3']
3304 }])!
3305 run := s.run('', fn () ! {
3306 mut ui := new_trans_ui()
3307 mut handle := init_handle(ui)!
3308 defer { handle.release() or {} }
3309 dbs := init_repos(mut handle)!
3310 local := local_pkgcache(handle)!
3311 // the scope is all the dbs, or the one named; an unknown name is an
3312 // error and never a search of everything
3313 check(scope_dbs(dbs, '')!.len == 1, 'no scope keeps every db')!
3314 check(scope_dbs(dbs, 'core')!.map(it.get_name()) == ['core'], 'core scopes to core')!
3315 if _ := scope_dbs(dbs, 'extra') {
3316 return error('an unknown repo scoped')
3317 } else {
3318 check(err.msg() == 'database not found: extra', err.msg())!
3319 }
3320 if _ := scope_dbs([], 'core') {
3321 return error('a repo was found among no dbs')
3322 }
3323 // installed: by name, by a constraint it meets, and by provision
3324 // only where the caller takes providers
3325 check(find_local_target(local, 'app', false) != none, 'app by name')!
3326 check(find_local_target(local, 'app>=1.0', false) != none, 'app by a met constraint')!
3327 check(find_local_target(local, 'app>=2', false) == none, 'app by an unmet constraint')!
3328 check(find_local_target(local, 'virt', false) == none, 'a provision without providers')!
3329 check(find_local_target(local, 'virt', true) != none, 'a provision with providers')!
3330 check(find_local_target(local, 'virt>=3', true) == none, 'a provision too old')!
3331 check(find_local_target(local, '', true) == none, 'the empty name')!
3332 check(find_local_target(local, 'ap', true) == none, 'a prefix of a name')!
3333 // sync: by name, constraint and provision; the empty name is nothing
3334 check(find_sync_target(handle, dbs, 'app', false) != none, 'sync app')!
3335 check(find_sync_target(handle, dbs, 'app>=2.0', false) != none, 'sync app>=2.0')!
3336 check(find_sync_target(handle, dbs, 'app>2.0', false) == none, 'sync app>2.0')!
3337 check(find_sync_target(handle, dbs, 'svirt', false) != none, 'sync provision')!
3338 check(find_sync_target(handle, dbs, 'svirt=4', false) == none, 'sync provision, wrong version')!
3339 check(find_sync_target(handle, dbs, '', false) == none, 'sync empty name')!
3340 check(find_sync_target(handle, []&alpm.DB{}, 'app', false) == none, 'no dbs')!
3341 // a db not for installing answers a provision only when it was
3342 // named with the target, and its usage is put back after
3343 dbs[0].set_usage(.sync | .search)!
3344 check(find_sync_target(handle, dbs, 'svirt', false) == none, 'usage without install')!
3345 check(find_sync_target(handle, dbs, 'svirt', true) != none, 'named db, usage lifted')!
3346 usage := dbs[0].get_usage() or { return error('no usage') }
3347 check(!usage.has(.install), 'the usage was put back')!
3348 // by name it is found either way: the name is asked of the db itself
3349 check(find_sync_target(handle, dbs, 'app', false) != none, 'by name whatever the usage')!
3350 })!
3351 assert run.err == '', run.err
3352}
3353
3354fn test_filters_combine_as_pacmans_query_filters() ! {
3355 s := fake_system('filters')!
3356 defer { os.rmdir_all(s.tmp) or {} }
3357 // app: explicit, in the repos, newer there. lib: a dependency app needs.
3358 // own: explicit, in no repo. loose: a dependency nothing needs, older in
3359 // the repos than installed. opt-only would need optdepends, which the
3360 // level-2 unrequired check is covered with in orphans_test
3361 s.install_local(fake_pkg('app', '1.0-1', ['lib']))!
3362 s.install_local(FakePkg{
3363 ...fake_pkg('lib', '1.0-1', [])
3364 reason: 1
3365 })!
3366 s.install_local(fake_pkg('own', '1.0-1', []))!
3367 s.install_local(FakePkg{
3368 ...fake_pkg('loose', '2.0-1', [])
3369 reason: 1
3370 })!
3371 s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []),
3372 fake_pkg('loose', '1.0-1', [])])!
3373 run := s.run('', fn () ! {
3374 mut ui := new_trans_ui()
3375 mut handle := init_handle(ui)!
3376 defer { handle.release() or {} }
3377 dbs := init_repos(mut handle)!
3378 mut local := local_pkgcache(handle)!
3379 pass := fn [mut local, dbs] (c ConfigSearch) []string {
3380 mut names := local.pkgs().filter(pkg_matches_filter(it, c, dbs)).map(it.get_name())
3381 names.sort()
3382 return names
3383 }
3384 check(pass(ConfigSearch{}) == ['app', 'lib', 'loose', 'own'], 'no filter passes all')!
3385 check(pass(ConfigSearch{ explicit: true }) == ['app', 'own'], 'explicit')!
3386 check(pass(ConfigSearch{ deps: true }) == ['lib', 'loose'], 'deps')!
3387 // the two reasons together pass nothing: no package is both
3388 check(pass(ConfigSearch{ deps: true, explicit: true }) == [], 'deps and explicit')!
3389 check(pass(ConfigSearch{ unrequired: true, unrequired_level: 1 }) == ['app', 'loose', 'own'], 'unrequired')!
3390 check(pass(ConfigSearch{ deps: true, unrequired: true, unrequired_level: 1 }) == ['loose'], 'unrequired deps')!
3391 check(pass(ConfigSearch{ foreign: true }) == ['own'], 'foreign')!
3392 check(pass(ConfigSearch{ native: true }) == ['app', 'lib', 'loose'], 'native')!
3393 check(pass(ConfigSearch{ native: true, foreign: true }) == [], 'native and foreign')!
3394 // an upgrade is a strictly newer sync version: an equal one, an
3395 // older one (loose) and a package in no repo are not
3396 check(pass(ConfigSearch{ upgrades: true }) == ['app'], 'upgrades')!
3397 check(pass(ConfigSearch{ upgrades: true, deps: true }) == [], 'upgrades among deps')!
3398 check(pass(ConfigSearch{ upgrades: true, foreign: true }) == [], 'upgrades of foreign')!
3399 // with no sync dbs to compare with, everything is foreign
3400 none_synced := local.pkgs().filter(pkg_matches_filter(it, ConfigSearch{ native: true },
3401 []&alpm.DB{}))
3402 check(none_synced.len == 0, 'native with no sync dbs')!
3403 // the filters that need no sync data never load it
3404 check(filter_sync_dbs(mut ui, mut handle, ConfigSearch{ explicit: true, unrequired: true })!.len == 0,
3405 'no sync dbs for local-only filters')!
3406 })!
3407 assert run.err == '', run.err
3408}
3409
3410fn test_search_groups_take_one_side_and_fuzzy_keeps_its_order() ! {
3411 s := fake_system('searchedges')!
3412 defer { os.rmdir_all(s.tmp) or {} }
3413 s.install_local(tool('aa'))!
3414 s.publish([tool('aa'), FakePkg{
3415 ...fake_pkg('zeditor', '1.0-1', [])
3416 desc: 'an editor'
3417 }, FakePkg{
3418 ...fake_pkg('notes', '1.0-1', [])
3419 desc: 'a small editor for notes'
3420 }, FakePkg{
3421 ...fake_pkg('editor', '1.0-1', [])
3422 desc: 'the editor'
3423 }])!
3424 // -g with both sides named would drop one of them: refused, before any
3425 // db is opened, with or without a group named
3426 for query in [[]string{}, ['tools']] {
3427 both := s.run('', fn [query] () ! {
3428 search(ConfigSearch{ local: true, remote: true, groups: true, query: query })!
3429 })!
3430 assert both.err.contains('not both at once'), both.err
3431 assert both.of('listing').len == 0 && both.of('groups').len == 0
3432 }
3433 // each side alone still answers
3434 for local in [true, false] {
3435 one := s.run('', fn [local] () ! {
3436 search(ConfigSearch{ local: local, remote: !local, groups: true, query: ['tools'] })!
3437 })!
3438 assert one.err == '', one.err
3439 assert one.of('listing').len == 1
3440 }
3441 // fuzzy: the names that match lead, best first, and a package matched
3442 // by its description alone trails them, listed once
3443 fuzzy := s.run('', fn () ! {
3444 search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, fields: 'name', query: ['editor'] })!
3445 })!
3446 assert fuzzy.err == '', fuzzy.err
3447 names := fuzzy.of('listing')[0]['entries']!.as_array().map(it.as_map()['name']!.str())
3448 assert names == ['editor', 'zeditor', 'notes'], names.str()
3449 // a term nothing is near matches nothing, and is no error
3450 none_near := s.run('', fn () ! {
3451 search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, query: ['qqqqqqqq'] })!
3452 })!
3453 assert none_near.err == ''
3454 assert none_near.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().len == 0
3455}
3456
3457fn test_info_fields_and_listing_on_real_packages() ! {
3458 s := fake_system('formatreal')!
3459 defer { os.rmdir_all(s.tmp) or {} }
3460 s.install_local(FakePkg{
3461 ...fake_pkg('app', '1.0-1', ['lib>=1', 'glibc'])
3462 provides: ['virt=2']
3463 groups: ['tools']
3464 })!
3465 s.install_local(fake_pkg('bare', '2.0-1', []))!
3466 run := s.run_ui('tty', '', fn () ! {
3467 mut ui := new_trans_ui()
3468 mut handle := init_handle(ui)!
3469 defer { handle.release() or {} }
3470 local := local_pkgcache(handle)!
3471 app := local.pkg_find('app') or { return error('no app') }
3472 bare := local.pkg_find('bare') or { return error('no bare') }
3473 // asked for by default, an empty field is left out; named on the
3474 // command line it is shown, empty
3475 fields := ['name', 'version', 'depends', 'provides', 'groups', 'url']
3476 quiet := info_fields(bare, fields, false)
3477 check(quiet.map(it.field) == ['name', 'version'], 'empty fields left out: ${quiet.map(it.field)}')!
3478 named := info_fields(bare, fields, true)
3479 check(named.map(it.field) == fields, 'named fields all shown')!
3480 check(named.filter(it.field == 'depends')[0].value == '', 'an empty value stays empty')!
3481 check(named.filter(it.field == 'depends')[0].items.len == 0, 'and has no items')!
3482 // a list field carries its items one by one, a plain one none
3483 full := info_fields(app, fields, false)
3484 check(full.map(it.field) == ['name', 'version', 'depends', 'provides', 'groups'], 'app fields: ${full.map(it.field)}')!
3485 deps := full.filter(it.field == 'depends')[0]
3486 check(deps.items == ['lib>=1', 'glibc'] && deps.value == 'lib>=1, glibc', 'depends items: ${deps}')!
3487 check(full.filter(it.field == 'name')[0].items.len == 0, 'a plain field has no items')!
3488 check(full.filter(it.field == 'provides')[0].items == ['virt=2'], 'provides items')!
3489 // no fields asked for is nothing to show, not a crash
3490 check(info_fields(app, [], true).len == 0, 'no fields')!
3491 check(info_table([]) == '', 'an empty table is no text')!
3492 // a listing: the default mode holds a value per field, the quiet one
3493 // the name alone, and a member carries its group
3494 mut l := Listing{
3495 fields: ['name', 'version', 'groups']
3496 }
3497 l.add_pkg(app, 'local')
3498 l.add_pkg(bare, 'local')
3499 check(l.entries[0].values == ['app', '1.0-1', 'tools'], 'values: ${l.entries[0].values}')!
3500 check(l.entries[1].values == ['bare', '2.0-1', ''], 'an empty value is kept in its place')!
3501 mut q := Listing{
3502 mode: .minimal
3503 fields: ['name', 'version']
3504 }
3505 q.add_pkg(app, 'local')
3506 q.add_member(bare, 'local', 'tools')
3507 check(q.entries.all(it.values.len == 0), 'quiet entries hold no values')!
3508 check(q.entries[1].group == 'tools' && q.entries[0].group == '', 'the member has its group')!
3509 // what the terminal gets: a table with '-' for the empty value, the
3510 // names alone for the quiet one, nothing at all for an empty listing
3511 l.print()
3512 println('--')
3513 q.print()
3514 println('--')
3515 Listing{
3516 fields: ['name']
3517 }.print()
3518 println('--')
3519 // a collection that failed part way shows what a quiet listing
3520 // found, and nothing of a table
3521 l.print_found()
3522 q.print_found()
3523 })!
3524 assert run.err == '', run.err
3525 parts := run.stdout.split('--\n')
3526 assert parts.len == 4, run.stdout
3527 assert parts[0].split_into_lines().map(it.fields().join(' ')) == ['app 1.0-1 tools', 'bare 2.0-1 -'], parts[0]
3528 assert parts[1] == 'app\nbare\n'
3529 assert parts[2] == ''
3530 assert parts[3] == 'app\nbare\n'
3531}
3532
3533fn test_pkgbuild_plan_gathers_every_spelling_that_wanted_a_node() ! {
3534 s := fake_system('wanted')!
3535 defer { os.rmdir_all(s.tmp) or {} }
3536 // dep 1.0 is installed, and too old for everything that asks for it
3537 s.install_local(fake_pkg('dep', '1.0-1', []))!
3538 s.publish([fake_pkg('lib', '1.0-1', [])])!
3539 mut server, base := fake_rpc(FakeRpc{
3540 pkgs: {
3541 'top': aur_pkg('top', ['a', 'b', 'dep>=2'], [])
3542 'a': aur_pkg('a', ['dep>=2', 'dep>=3'], [])
3543 'b': aur_pkg('b', ['dep>=3'], ['dep>=2'])
3544 'dep': aur_pkg('dep', [], [])
3545 }
3546 })!
3547 defer { server.stop() }
3548 plan := resolve(s, base, 'top')!
3549 assert plan.map(it.info.name) == ['dep', 'a', 'b', 'top']
3550 // the node is planned once, and holds each spelling once, in the order
3551 // they were met, those that came after it was planned too
3552 assert plan[0].wanted == ['dep>=2', 'dep>=3']
3553 assert plan[1].wanted == ['a'] && plan[2].wanted == ['b'] && plan[3].wanted == []
3554 // the plan is made on the local db of this moment: with dep new enough
3555 // for everyone installed since, it is planned by nobody
3556 os.rmdir_all(s.path('db/local/dep-1.0-1'))!
3557 s.install_local(fake_pkg('dep', '3.0-1', []))!
3558 again := resolve(s, base, 'top')!
3559 assert again.map(it.info.name) == ['a', 'b', 'top']
3560 // new enough for some and not for all, it is still planned, and wanted
3561 // by the one spelling it does not meet: a spelling that is met already
3562 // plans nothing and is not held
3563 os.rmdir_all(s.path('db/local/dep-3.0-1'))!
3564 s.install_local(fake_pkg('dep', '2.0-1', []))!
3565 partly := resolve(s, base, 'top')!
3566 assert partly.map(it.info.name) == ['dep', 'a', 'b', 'top']
3567 assert partly[0].wanted == ['dep>=3']
3568}
3569