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