vpac / src / frontend_test.v
2409 lines · 2298 sloc · 84.05 KB · cac7fba11c6fd315eb54fc6843c1705666133c24
Raw
1module main
2
3import alpm
4import crypto.sha256
5import json2
6import net.http
7import net.urllib
8import os
9import testdb
10import time
11
12#include <stdio_ext.h>
13
14fn C.__fpurge(stream &C.FILE)
15
16fn C.clearerr(stream &C.FILE)
17
18// the modes that commit a transaction, run whole under --ui ipc against a
19// system that lives in a temp dir: a root, a local db, a sync repo served
20// over file:// with real package archives, and a cache. libalpm does every
21// step for real — download, validation, extraction, db writes — and the
22// events the mode sends are read back line by line, as a frontend reads them
23
24// FakePkg is a package of the fake system: its files are paths under the
25// root with their content
26struct FakePkg {
27 name string
28 version string = '1.0-1'
29 reason int // installed ones: 0 explicit, 1 a dependency
30 depends []string
31 provides []string
32 groups []string
33 desc string
34 // changelog is the text the package carries as its changelog, if any
35 changelog string
36 files map[string]string
37}
38
39// FakeSystem is the temp dir a run's whole system lives in
40struct FakeSystem {
41 tmp string
42}
43
44fn fake_system(name string) !FakeSystem {
45 tmp := os.join_path(os.vtmp_dir(), 'vpac_test_frontend_${name}_${os.getpid()}')
46 os.rmdir_all(tmp) or {}
47 // pkgbuild is the build dir the runs point pkgbuild_dir at: it is there,
48 // empty, so a mode that lists the builds reads a dir and not an error
49 for d in ['root', 'db/local', 'db/sync', 'cache', 'repo', 'gpg', 'build', 'dbsrc', 'pkgbuild'] {
50 os.mkdir_all(os.join_path(tmp, d))!
51 }
52 os.write_file(os.join_path(tmp, 'db/local/ALPM_DB_VERSION'), '9\n')!
53 return FakeSystem{
54 tmp: tmp
55 }
56}
57
58fn (s FakeSystem) path(rel string) string {
59 return os.join_path(s.tmp, rel)
60}
61
62// file_list is a package's filelist the way libalpm keeps one: every
63// directory on the way, with its slash, then the files, sorted
64fn file_list(files map[string]string) []string {
65 mut set := map[string]bool{}
66 for f, _ in files {
67 parts := f.split('/')
68 for i in 1 .. parts.len {
69 set[parts[..i].join('/') + '/'] = true
70 }
71 set[f] = true
72 }
73 mut out := set.keys()
74 out.sort()
75 return out
76}
77
78// install_local puts p in the local db as installed, its files on the root
79fn (s FakeSystem) install_local(p FakePkg) ! {
80 // the db entry is the shared writer's; the changelog and the files on
81 // the root are this fake system's own
82 testdb.write_local(s.path('db'), [
83 testdb.Pkg{
84 name: p.name
85 version: p.version
86 reason: p.reason
87 depends: p.depends
88 provides: p.provides
89 groups: p.groups
90 files: file_list(p.files)
91 },
92 ])!
93 if p.changelog != '' {
94 os.write_file(s.path('db/local/${p.name}-${p.version}/changelog'), p.changelog)!
95 }
96 for f, content in p.files {
97 os.mkdir_all(os.dir(s.path('root/${f}')))!
98 os.write_file(s.path('root/${f}'), content)!
99 }
100}
101
102// publish builds an archive of each package into the repo, writes the repo's
103// core.db naming them with their checksums, and puts that db in the sync dir
104// fresh, so no mode asks to update it
105fn (s FakeSystem) publish(pkgs []FakePkg) ! {
106 for p in pkgs {
107 src := s.path('build/${p.name}-${p.version}')
108 os.mkdir_all(src)!
109 mut info := 'pkgname = ${p.name}\npkgbase = ${p.name}\npkgver = ${p.version}\npkgdesc = ${p.name} for a test\narch = any\nsize = 0\n'
110 for d in p.depends {
111 info += 'depend = ${d}\n'
112 }
113 for v in p.provides {
114 info += 'provides = ${v}\n'
115 }
116 for g in p.groups {
117 info += 'group = ${g}\n'
118 }
119 if p.changelog != '' {
120 os.write_file(os.join_path(src, '.CHANGELOG'), p.changelog)!
121 }
122 os.write_file(os.join_path(src, '.PKGINFO'), info)!
123 for f, content in p.files {
124 os.mkdir_all(os.dir(os.join_path(src, f)))!
125 os.write_file(os.join_path(src, f), content)!
126 }
127 file := '${p.name}-${p.version}-any.pkg.tar'
128 tar(s.path('repo/${file}'), src, os.ls(src)!)!
129 text := if p.desc != '' { p.desc } else { '${p.name} for a test' }
130 mut desc := '%FILENAME%\n${file}\n\n%NAME%\n${p.name}\n\n%VERSION%\n${p.version}\n\n%DESC%\n${text}\n\n'
131 desc += '%CSIZE%\n${os.file_size(s.path('repo/${file}'))}\n\n%ISIZE%\n0\n\n'
132 desc += '%SHA256SUM%\n${sha256.hexhash(os.read_file(s.path('repo/${file}'))!)}\n\n%ARCH%\nany\n\n'
133 if p.depends.len > 0 {
134 desc += '%DEPENDS%\n${p.depends.join('\n')}\n\n'
135 }
136 if p.provides.len > 0 {
137 desc += '%PROVIDES%\n${p.provides.join('\n')}\n\n'
138 }
139 if p.groups.len > 0 {
140 desc += '%GROUPS%\n${p.groups.join('\n')}\n\n'
141 }
142 os.mkdir_all(s.path('dbsrc/${p.name}-${p.version}'))!
143 os.write_file(s.path('dbsrc/${p.name}-${p.version}/desc'), desc)!
144 }
145 tar(s.path('repo/core.db'), s.path('dbsrc'), os.ls(s.path('dbsrc'))!)!
146 os.cp(s.path('repo/core.db'), s.path('db/sync/core.db'))!
147 // the file db beside it, the way a repo serves one: each entry's desc and
148 // its file list. it stays on the server until a find -y fetches it
149 for p in pkgs {
150 entry := s.path('filessrc/${p.name}-${p.version}')
151 os.mkdir_all(entry)!
152 os.cp(s.path('dbsrc/${p.name}-${p.version}/desc'), os.join_path(entry, 'desc'))!
153 os.write_file(os.join_path(entry, 'files'), '%FILES%\n${file_list(p.files).join('\n')}\n\n')!
154 }
155 tar(s.path('repo/core.files'), s.path('filessrc'), os.ls(s.path('filessrc'))!)!
156}
157
158fn tar(out string, dir string, entries []string) ! {
159 mut args := ['tar', '-cf', out, '-C', dir]
160 args << entries
161 res := os.exec(args)
162 if res.exit_code != 0 {
163 return error('tar failed: ${res.output}')
164 }
165}
166
167// installed is the local db's name to version, read the way the next
168// command would read it: a fresh handle
169fn (s FakeSystem) installed() !map[string]string {
170 handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
171 defer { handle.release() or {} }
172 // an empty db is no packages; one that cannot be read is an error, not
173 // 'nothing installed' (pkgcache_of tells the two apart by libalpm's errno)
174 mut cache := local_pkgcache(handle)!
175 mut out := map[string]string{}
176 for p in cache.pkgs() {
177 out[p.get_name()] = p.get_version()
178 }
179 return out
180}
181
182fn (s FakeSystem) reason_of(name string) !alpm.PackageReason {
183 handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
184 defer { handle.release() or {} }
185 return (handle.find_local_pkg(name) or { return error('${name} is not installed') }).get_reason()
186}
187
188// FrontendRun is what a mode sent on the channel, decoded, and the error it
189// returned ('' when it returned none)
190struct FrontendRun {
191 events []map[string]json2.Any
192 err string
193 // stdout is what reached fd 1 itself, beside the channel
194 stdout string
195 // failed is how many targets this run reported bad, main's exit status
196 // counting them
197 failed int
198}
199
200fn (r FrontendRun) of(kind string) []map[string]json2.Any {
201 return r.events.filter(it['type'] or { json2.Any('') }.str() == kind)
202}
203
204// done is the run's one done event; it fails when there is not exactly one
205fn (r FrontendRun) done() !map[string]json2.Any {
206 dones := r.of('done')
207 if dones.len != 1 {
208 return error('${dones.len} done events in ${r.events.map(it['type'] or { json2.Any('') }.str())}')
209 }
210 return dones[0]
211}
212
213fn sorted_strs(v json2.Any) []string {
214 mut out := v.as_array().map(it.str())
215 out.sort()
216 return out
217}
218
219// run runs a mode on the system the way a frontend runs vpac: --ui ipc, the
220// events on a channel (a file here), the answers on stdin. the config is
221// aimed at the system — its root and dbs, its cache, its keyring dir, its
222// repo over file:// — and put back at its defaults after, with the ui
223fn (s FakeSystem) run(stdin string, mode fn () !) !FrontendRun {
224 return s.run_ui('ipc', stdin, mode)
225}
226
227// run_ui is run with the ui kind given: 'tty' runs the mode as a terminal
228// sees it, with no channel, its output read back from fd 1
229fn (s FakeSystem) run_ui(kind string, stdin string, mode fn () !) !FrontendRun {
230 chan_path := s.path('channel')
231 out_path := s.path('stdout')
232 mut out_file := os.create(out_path)!
233 saved_out := C.dup(1)
234 if saved_out < 0 {
235 return error('could not save stdout')
236 }
237 in_path := s.path('stdin')
238 os.write_file(in_path, stdin)!
239 mut chan_file := os.create(chan_path)!
240 mut in_file := os.open(in_path)!
241 saved_in := C.dup(0)
242 if saved_in < 0 {
243 return error('could not save stdin')
244 }
245 saved_kind, saved_color, saved_fd := ui_kind, color_flag, ipc_fd
246 // a process-wide count, as main reads it at the end of its one run: each
247 // run here starts from none, and puts the count back after
248 saved_failed := failed_targets
249 failed_targets = 0
250 defer {
251 failed_targets = saved_failed
252 }
253 reset_config()
254 root_path = s.path('root') + '/'
255 db_path = s.path('db') + '/'
256 cfg_cachedirs = [s.path('cache') + '/']
257 cfg_gpgdir = s.path('gpg') + '/'
258 // the machine's own hooks stay out of a fake system's transactions
259 cfg_hookdirs = []string{}
260 // the sandbox user need not exist where the tests run
261 download_user = ''
262 // the pkgbuild builds are the system's own too: never the ones in the
263 // home of whoever runs the tests, which a clean would otherwise look at
264 pkgbuild_dir = s.path('pkgbuild')
265 cfg_repos = [CfgRepo{
266 name: 'core'
267 kind: 'sync'
268 servers: ['file://' + s.path('repo')]
269 }]
270 ui_kind = kind
271 color_flag = 'never'
272 ipc_fd = chan_file.fd
273 C.__fpurge(C.stdin)
274 C.clearerr(C.stdin)
275 C.dup2(in_file.fd, 0)
276 C.fflush(C.stdout)
277 C.dup2(out_file.fd, 1)
278
279 mut msg := ''
280 mode() or { msg = err.msg() }
281
282 C.fflush(C.stdout)
283 C.dup2(saved_out, 1)
284 C.close(saved_out)
285 out_file.close()
286 C.dup2(saved_in, 0)
287 C.close(saved_in)
288 C.__fpurge(C.stdin)
289 C.clearerr(C.stdin)
290 ui_kind, color_flag, ipc_fd = saved_kind, saved_color, saved_fd
291 reset_config()
292 in_file.close()
293 chan_file.close()
294 mut events := []map[string]json2.Any{}
295 for line in os.read_lines(chan_path)! {
296 // every line is one whole json object, or the channel is broken
297 events << json2.decode[json2.Any](line)!.as_map()
298 }
299 return FrontendRun{
300 events: events
301 err: msg
302 stdout: os.read_file(out_path)!
303 failed: failed_targets
304 }
305}
306
307fn (s FakeSystem) lock_left() bool {
308 return os.exists(s.path('db/db.lck'))
309}
310
311fn foo(version string, content string) FakePkg {
312 return FakePkg{
313 name: 'foo'
314 version: version
315 files: {
316 'usr/share/foo/hello': content
317 }
318 }
319}
320
321fn test_upgrade_ends_with_a_done_event() ! {
322 s := fake_system('upgrade')!
323 defer { os.rmdir_all(s.tmp) or {} }
324 s.install_local(foo('1.0-1', 'one'))!
325 s.publish([foo('2.0-1', 'two')])!
326
327 run := s.run('', fn () ! {
328 upgrade(ConfigUpgrade{ noconfirm: true })!
329 })!
330 assert run.err == ''
331 done := run.done()!
332 assert done['action']!.str() == 'upgraded'
333 assert sorted_strs(done['packages']!) == ['foo']
334 // the listing and the go-ahead came first, the done last of them
335 assert run.of('transaction').len == 1
336 assert run.of('question').len == 1
337 // and it happened: the new version is on the root and in the local db
338 assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'two'
339 assert s.installed()! == {
340 'foo': '2.0-1'
341 }
342 assert !s.lock_left()
343}
344
345fn test_upgrade_with_nothing_to_do_sends_no_done() ! {
346 s := fake_system('uptodate')!
347 defer { os.rmdir_all(s.tmp) or {} }
348 s.install_local(foo('1.0-1', 'one'))!
349 s.publish([foo('1.0-1', 'one')])!
350 run := s.run('', fn () ! {
351 upgrade(ConfigUpgrade{ noconfirm: true })!
352 })!
353 assert run.err == ''
354 assert run.of('done').len == 0
355 assert run.of('message').any(it['text']!.str() == 'nothing to upgrade.')
356}
357
358fn test_install_ends_with_a_done_event() ! {
359 s := fake_system('install')!
360 defer { os.rmdir_all(s.tmp) or {} }
361 s.publish([
362 FakePkg{
363 name: 'bar'
364 depends: ['baz']
365 files: {
366 'usr/bin/bar': 'bar'
367 }
368 },
369 FakePkg{
370 name: 'baz'
371 files: {
372 'usr/lib/libbaz': 'baz'
373 }
374 },
375 ])!
376 run := s.run('', fn () ! {
377 install(ConfigInstall{ noconfirm: true, query: ['bar'] })!
378 })!
379 assert run.err == ''
380 done := run.done()!
381 assert done['action']!.str() == 'installed'
382 // the targets: the dependency comes along, but is not one
383 assert sorted_strs(done['packages']!) == ['bar']
384 assert s.installed()! == {
385 'bar': '1.0-1'
386 'baz': '1.0-1'
387 }
388 assert s.reason_of('bar')! == .explicit
389 assert s.reason_of('baz')! == .depend
390 assert os.read_file(s.path('root/usr/bin/bar'))! == 'bar'
391 assert !s.lock_left()
392}
393
394fn test_remove_ends_with_a_done_event() ! {
395 s := fake_system('remove')!
396 defer { os.rmdir_all(s.tmp) or {} }
397 s.install_local(foo('1.0-1', 'one'))!
398 run := s.run('', fn () ! {
399 remove(ConfigRemove{ noconfirm: true, query: ['foo'] })!
400 })!
401 assert run.err == ''
402 done := run.done()!
403 assert done['action']!.str() == 'removed'
404 assert sorted_strs(done['packages']!) == ['foo']
405 assert s.installed()!.len == 0
406 assert !os.exists(s.path('root/usr/share/foo/hello'))
407 assert !s.lock_left()
408}
409
410fn test_autoremove_ends_with_a_done_event() ! {
411 s := fake_system('autoremove')!
412 defer { os.rmdir_all(s.tmp) or {} }
413 s.install_local(FakePkg{
414 name: 'app'
415 depends: ['lib']
416 })!
417 s.install_local(FakePkg{
418 name: 'lib'
419 reason: 1
420 })!
421 s.install_local(FakePkg{
422 name: 'orphan'
423 reason: 1
424 })!
425 // an orphan whose own dependency becomes unneeded with it: the recurse
426 // takes it along, and the done event names it with the rest
427 s.install_local(FakePkg{
428 name: 'stray'
429 reason: 1
430 depends: ['leaf']
431 })!
432 s.install_local(FakePkg{
433 name: 'leaf'
434 reason: 1
435 })!
436 run := s.run('', fn () ! {
437 autoremove(ConfigAutoRemove{ noconfirm: true })!
438 })!
439 assert run.err == ''
440 done := run.done()!
441 assert done['action']!.str() == 'removed'
442 assert sorted_strs(done['packages']!) == ['leaf', 'orphan', 'stray']
443 // the text line of a terminal is not sent beside it
444 assert !run.of('message').any(it['text']!.str().contains('orphaned packages'))
445 mut left := s.installed()!.keys()
446 left.sort()
447 assert left == ['app', 'lib']
448 assert !s.lock_left()
449}
450
451fn test_mark_ends_with_a_done_event() ! {
452 s := fake_system('mark')!
453 defer { os.rmdir_all(s.tmp) or {} }
454 s.install_local(foo('1.0-1', 'one'))!
455 run := s.run('', fn () ! {
456 mark(ConfigMark{ reason: 'd', query: ['foo'] })!
457 })!
458 assert run.err == ''
459 done := run.done()!
460 assert done['action']!.str() == 'marked'
461 assert done['reason']!.str() == 'depend'
462 assert sorted_strs(done['packages']!) == ['foo']
463 assert s.reason_of('foo')! == .depend
464 assert !s.lock_left()
465}
466
467fn test_declined_transaction_sends_no_done() ! {
468 s := fake_system('decline')!
469 defer { os.rmdir_all(s.tmp) or {} }
470 s.install_local(foo('1.0-1', 'one'))!
471 // the frontend says no to the go-ahead, question 1
472 run := s.run('{"id": 1, "answer": false}\n', fn () ! {
473 remove(ConfigRemove{ query: ['foo'] })!
474 })!
475 assert run.err == ''
476 questions := run.of('question')
477 assert questions.len == 1
478 assert questions[0]['question']!.str() == 'proceed'
479 assert run.of('done').len == 0
480 // nothing changed, and the transaction let go of the lock
481 assert s.installed()! == {
482 'foo': '1.0-1'
483 }
484 assert os.exists(s.path('root/usr/share/foo/hello'))
485 assert !s.lock_left()
486}
487
488fn test_print_preview_sends_no_done() ! {
489 s := fake_system('preview')!
490 defer { os.rmdir_all(s.tmp) or {} }
491 s.install_local(foo('1.0-1', 'one'))!
492 s.publish([foo('2.0-1', 'two')])!
493 run := s.run('', fn () ! {
494 upgrade(ConfigUpgrade{ print_only: true })!
495 })!
496 assert run.err == ''
497 listing := run.of('transaction')
498 assert listing.len == 1
499 assert listing[0]['preview']!.bool()
500 assert run.of('done').len == 0
501 assert run.of('question').len == 0
502 assert s.installed()! == {
503 'foo': '1.0-1'
504 }
505 assert !s.lock_left()
506}
507
508fn test_prepare_failure_sends_no_done_and_lets_go_of_the_lock() ! {
509 s := fake_system('prepare')!
510 defer { os.rmdir_all(s.tmp) or {} }
511 // a dependency no repo has: prepare fails, and says on what
512 s.publish([FakePkg{
513 name: 'needy'
514 depends: ['nowhere']
515 }])!
516 run := s.run('', fn () ! {
517 install(ConfigInstall{ noconfirm: true, query: ['needy'] })!
518 })!
519 assert run.err != ''
520 assert run.err.contains('nowhere'), run.err
521 assert run.of('done').len == 0
522 assert s.installed()!.len == 0
523 assert !s.lock_left()
524}
525
526// an empty local db is a db with no packages, not a broken one: the modes
527// that read it answer nothing found, as pacman does on a fresh root (the
528// install above runs on one too)
529fn test_an_empty_system_is_no_error() ! {
530 s := fake_system('empty')!
531 defer { os.rmdir_all(s.tmp) or {} }
532 s.publish([foo('1.0-1', 'one')])!
533 orphaned := s.run('', fn () ! {
534 orphans(ConfigOrphans{})!
535 })!
536 assert orphaned.err == ''
537 verified := s.run('', fn () ! {
538 verify(ConfigVerify{})!
539 })!
540 assert verified.err == ''
541 searched := s.run('', fn () ! {
542 search(ConfigSearch{ local: true, query: ['foo'] })!
543 })!
544 assert searched.err == ''
545 // a name to act on is unknown, said so, not a database failure: mark
546 // and remove report it as the bad target it is
547 marked := s.run('', fn () ! {
548 mark(ConfigMark{ reason: 'd', query: ['foo'] })!
549 })!
550 assert marked.err == '' && marked.failed == 1
551 assert marked.of('error')[0]['msg']!.str().contains('unknown package')
552 assert !s.lock_left()
553 removed := s.run('', fn () ! {
554 remove(ConfigRemove{ noconfirm: true, query: ['foo'] })!
555 })!
556 assert removed.err == '' && removed.failed == 1
557 assert removed.of('error')[0]['msg']!.str().contains('unknown package')
558 assert !s.lock_left()
559}
560
561fn test_pkgcache_of() ! {
562 s := fake_system('pkgcache')!
563 defer { os.rmdir_all(s.tmp) or {} }
564 handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
565 // empty: a nil list, which reads as no packages
566 mut empty := local_pkgcache(handle)!
567 assert empty == unsafe { nil }
568 assert empty.pkgs().len == 0
569 assert empty.pkg_find('foo') == none
570 handle.release()!
571
572 s.install_local(foo('1.0-1', 'one'))!
573 full_handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
574 mut full := local_pkgcache(full_handle)!
575 assert full.pkgs().map(it.get_name()) == ['foo']
576 full_handle.release()!
577
578 if os.geteuid() == 0 {
579 // root reads the unreadable dir below anyway
580 return
581 }
582 // a db libalpm cannot read is still an error, with libalpm's reason. the
583 // handle opens first: libalpm reads the packages only when asked
584 broken := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
585 defer { broken.release() or {} }
586 os.chmod(s.path('db/local'), 0)!
587 defer { os.chmod(s.path('db/local'), 0o755) or {} }
588 if mut got := local_pkgcache(broken) {
589 assert false, 'an unreadable local db read as ${got.pkgs().len} packages'
590 } else {
591 assert err.msg().starts_with('could not read the packages of local: '), err.msg()
592 }
593}
594
595fn test_url_install_through_the_install_handle() ! {
596 s := fake_system('url')!
597 defer { os.rmdir_all(s.tmp) or {} }
598 s.publish([foo('1.0-1', 'one')])!
599 url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar')
600 run := s.run('', fn [url] () ! {
601 install(ConfigInstall{ noconfirm: true, query: [url] })!
602 })!
603 assert run.err == ''
604 done := run.done()!
605 assert done['action']!.str() == 'installed'
606 assert sorted_strs(done['packages']!) == ['foo']
607 assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'one'
608 // the trust warning is a warning to a frontend, and comes before the
609 // download it is about, which comes before the transaction
610 kinds := run.events.map(it['type']!.str())
611 warned := run.events.filter(it['type']!.str() == 'message'
612 && it['text']!.str().contains('signature'))
613 assert warned.len == 1
614 assert warned[0]['warning']!.bool()
615 first_warning := run.events.index(warned[0])
616 first_download := kinds.index('download')
617 assert first_download > first_warning
618 assert kinds.index('transaction') > first_download
619 assert run.of('download').any(it['file']!.str().starts_with('foo-1.0-1-any.pkg.tar'))
620 // the archive was fetched into the cache, as libalpm fetches one
621 assert os.exists(s.path('cache/foo-1.0-1-any.pkg.tar'))
622 assert !s.lock_left()
623}
624
625fn test_url_install_refuses_a_bad_signature_beside_it() ! {
626 s := fake_system('urlsig')!
627 defer { os.rmdir_all(s.tmp) or {} }
628 s.publish([foo('1.0-1', 'one')])!
629 // the server offers a signature that does not hold: libalpm fetches it
630 // with the archive, and the load at the remote level reads it
631 os.write_file(s.path('repo/foo-1.0-1-any.pkg.tar.sig'), 'not a signature')!
632 url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar')
633 run := s.run('', fn [url] () ! {
634 install(ConfigInstall{ noconfirm: true, query: [url] })!
635 })!
636 assert run.err.contains('signature'), run.err
637 assert run.of('done').len == 0
638 assert s.installed()!.len == 0
639 assert !os.exists(s.path('root/usr/share/foo/hello'))
640 assert !s.lock_left()
641}
642
643fn test_find_refresh_takes_the_full_handle() ! {
644 s := fake_system('findhandle')!
645 defer { os.rmdir_all(s.tmp) or {} }
646 run := s.run('', fn () ! {
647 // a sandbox user that exists wherever the test runs: this one
648 download_user = current_user()!
649 mut ui := new_trans_ui()
650 refresh := find_handle(mut ui, true)!
651 defer { refresh.release() or {} }
652 // the refresh downloads as the sandbox user, from the file dbs
653 if refresh.option_get_sandboxuser() != download_user {
654 return error('a refresh downloads as "${refresh.option_get_sandboxuser()}"')
655 }
656 if refresh.option_get_dbext() != '.files' {
657 return error('a refresh reads ${refresh.option_get_dbext()}')
658 }
659 read := find_handle(mut ui, false)!
660 defer { read.release() or {} }
661 if read.option_get_dbext() != '.files' {
662 return error('a lookup reads ${read.option_get_dbext()}')
663 }
664 })!
665 assert run.err == ''
666}
667
668fn test_find_refresh_fetches_the_file_dbs() ! {
669 s := fake_system('findrefresh')!
670 defer { os.rmdir_all(s.tmp) or {} }
671 s.publish([FakePkg{
672 name: 'bar'
673 files: {
674 'usr/bin/bar': 'bar'
675 }
676 }])!
677 assert !os.exists(s.path('db/sync/core.files'))
678 run := s.run('', fn () ! {
679 find(ConfigFind{ refresh: true, query: ['/usr/bin/bar'] })!
680 })!
681 assert run.err == ''
682 // fetched through the full handle: its progress reached the frontend
683 assert run.of('download').any(it['file']!.str().starts_with('core.files'))
684 assert os.exists(s.path('db/sync/core.files'))
685 // and read: the repo package that provides the path
686 provides := run.of('provides')
687 assert provides.len == 1
688 entries := provides[0]['entries']!.as_array()
689 assert entries.len == 1
690 assert entries[0].as_map()['name']!.str() == 'bar'
691}
692
693// verify_lines runs the fast check on the system, with the NoExtract globs
694// given, and returns its report: the lines, and how many packages are bad
695fn (s FakeSystem) verify_lines(noextract []string) !([]string, int) {
696 run := s.run('', fn [noextract] () ! {
697 cfg_noextract = noextract.clone()
698 verify(ConfigVerify{})!
699 })!
700 if run.err != '' {
701 return error(run.err)
702 }
703 events := run.of('verify')
704 if events.len != 1 {
705 return error('${events.len} verify events')
706 }
707 lines := events[0]['lines']!.as_array().map(it.as_map()['text']!.str())
708 return lines, events[0]['bad']!.int()
709}
710
711fn test_verify_fast_check_as_pacman() ! {
712 s := fake_system('verify')!
713 defer { os.rmdir_all(s.tmp) or {} }
714 s.install_local(FakePkg{
715 name: 'docs'
716 files: {
717 'usr/bin/docs': 'docs'
718 'usr/share/man/man1/docs.1': 'man'
719 'usr/share/doc/docs/README.md': 'readme'
720 }
721 })!
722 s.install_local(FakePkg{
723 name: 'dirs'
724 files: {
725 'usr/share/dirs/a': 'a'
726 }
727 })!
728 s.install_local(FakePkg{
729 name: 'intact'
730 files: {
731 'usr/lib/intact': 'ok'
732 }
733 })!
734 // a man page NoExtract kept off the disk, and a binary that is gone
735 os.rm(s.path('root/usr/share/man/man1/docs.1'))!
736 os.rm(s.path('root/usr/bin/docs'))!
737 // a directory the db lists, now a link to one elsewhere: the file in it
738 // is still reached through the link
739 os.mkdir_all(s.path('root/usr/share/elsewhere'))!
740 os.write_file(s.path('root/usr/share/elsewhere/a'), 'a')!
741 os.rmdir_all(s.path('root/usr/share/dirs'))!
742 os.symlink('elsewhere', s.path('root/usr/share/dirs'))!
743
744 lines, bad := s.verify_lines(['usr/share/man/*'])!
745 root := s.path('root')
746 assert bad == 2, lines.str()
747 assert 'docs: missing ${root}/usr/bin/docs' in lines
748 assert 'dirs: ${root}/usr/share/dirs/ is a link, the db says a directory' in lines
749 // NoExtract's file is not missing, and not said at all, as in pacman
750 assert !lines.any(it.contains('docs.1')), lines.str()
751 assert !lines.any(it.starts_with('intact')), lines.str()
752 assert lines.len == 2, lines.str()
753
754 // without the NoExtract glob, the man page is missing like any file
755 lines2, bad2 := s.verify_lines([])!
756 assert bad2 == 2
757 assert 'docs: missing ${root}/usr/share/man/man1/docs.1' in lines2
758}
759
760fn test_verify_fast_check_lets_links_be() ! {
761 s := fake_system('verifylinks')!
762 defer { os.rmdir_all(s.tmp) or {} }
763 s.install_local(FakePkg{
764 name: 'linked'
765 files: {
766 'usr/lib/libx.so.1': 'lib'
767 'usr/lib/libx.so': ''
768 'usr/lib/dangling': ''
769 }
770 })!
771 // a package's file may be a link, to its neighbour or to nothing at all
772 os.rm(s.path('root/usr/lib/libx.so'))!
773 os.symlink('libx.so.1', s.path('root/usr/lib/libx.so'))!
774 os.rm(s.path('root/usr/lib/dangling'))!
775 os.symlink('nowhere', s.path('root/usr/lib/dangling'))!
776 lines, bad := s.verify_lines([])!
777 assert bad == 0, lines.str()
778 assert lines.len == 0
779}
780
781// fake_pkg is a FakePkg with no files, at a version, with its dependencies
782fn fake_pkg(name string, version string, depends []string) FakePkg {
783 return FakePkg{
784 name: name
785 version: version
786 depends: depends
787 }
788}
789
790fn test_install_upgrades_the_whole_outdated_closure() ! {
791 // app needs mid, mid needs low: both installed, both outdated. the walk
792 // is the dependency closure, not one level of it
793 s := fake_system('closure')!
794 defer { os.rmdir_all(s.tmp) or {} }
795 s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })!
796 s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })!
797 s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']),
798 fake_pkg('low', '2.0-1', [])])!
799 run := s.run('', fn () ! {
800 install(ConfigInstall{ noconfirm: true, query: ['app'] })!
801 })!
802 assert run.err == ''
803 assert s.installed()! == {
804 'app': '1.0-1'
805 'mid': '2.0-1'
806 'low': '2.0-1'
807 }
808 // what came along is still a dependency
809 assert s.reason_of('mid')! == .depend
810}
811
812fn test_install_no_upgrade_deps_leaves_the_closure() ! {
813 s := fake_system('noclosure')!
814 defer { os.rmdir_all(s.tmp) or {} }
815 s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })!
816 s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })!
817 s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']),
818 fake_pkg('low', '2.0-1', [])])!
819 run := s.run('', fn () ! {
820 install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })!
821 })!
822 assert run.err == ''
823 assert s.installed()! == {
824 'app': '1.0-1'
825 'mid': '1.0-1'
826 'low': '1.0-1'
827 }
828}
829
830fn test_install_brings_along_what_it_would_break() ! {
831 // user needs lib below 2.0; installing lib 2.0 breaks it, so the repo's
832 // user, which takes the new lib, comes along in the same transaction
833 s := fake_system('broken')!
834 defer { os.rmdir_all(s.tmp) or {} }
835 s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))!
836 s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
837 s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])!
838 run := s.run('', fn () ! {
839 install(ConfigInstall{ noconfirm: true, query: ['lib'] })!
840 })!
841 assert run.err == ''
842 assert s.installed()! == {
843 'lib': '2.0-1'
844 'user': '2.0-1'
845 }
846 // the transaction listed it before the go-ahead
847 listing := run.of('transaction')
848 assert listing.len == 1
849}
850
851fn test_no_upgrade_deps_failure_says_what_breaks() ! {
852 // --no-upgrade-deps keeps an installed package that needs the old lib at
853 // its version: prepare fails on it, and the hint names the cause
854 s := fake_system('noupbreak')!
855 defer { os.rmdir_all(s.tmp) or {} }
856 s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))!
857 s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
858 s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])!
859 run := s.run('', fn () ! {
860 install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['lib'] })!
861 })!
862 lines := run.err.split('\n')
863 assert lines[0] == 'could not satisfy dependencies:', run.err
864 assert lines[1] == " lib breaks dependency 'lib<2.0' required by user", run.err
865 assert lines[2].starts_with('without --no-upgrade-deps, the installed packages this breaks are upgraded along'), run.err
866 assert s.installed()!['lib']! == '1.0-1'
867 assert !s.lock_left()
868}
869
870fn test_no_upgrade_deps_still_takes_a_newer_dependency() ! {
871 // a target that needs a newer dependency than is installed gets it even
872 // under --no-upgrade-deps: libalpm's prepare pulls it in, which is why
873 // the hint never blames this case
874 s := fake_system('noupnewer')!
875 defer { os.rmdir_all(s.tmp) or {} }
876 s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
877 s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('app', '1.0-1', ['lib>=2.0'])])!
878 run := s.run('', fn () ! {
879 install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })!
880 })!
881 assert run.err == ''
882 assert s.installed()! == {
883 'app': '1.0-1'
884 'lib': '2.0-1'
885 }
886}
887
888fn test_mark_failure_names_what_was_set() ! {
889 if os.geteuid() == 0 {
890 // root writes the read-only desc below anyway
891 return
892 }
893 s := fake_system('markfail')!
894 defer { os.rmdir_all(s.tmp) or {} }
895 for name in ['aa', 'bb', 'cc'] {
896 s.install_local(fake_pkg(name, '1.0-1', []))!
897 }
898 // bb's db entry cannot be written: its reason cannot change
899 os.chmod(s.path('db/local/bb-1.0-1/desc'), 0o444)!
900 run := s.run('', fn () ! {
901 mark(ConfigMark{ reason: 'd', query: ['aa', 'bb', 'cc'] })!
902 })!
903 assert run.err.starts_with('could not set the install reason of bb: '), run.err
904 assert run.err.ends_with(' (already set: aa)'), run.err
905 assert run.of('done').len == 0
906 // what the error says is what the db holds
907 assert s.reason_of('aa')! == .depend
908 assert s.reason_of('bb')! == .explicit
909 assert s.reason_of('cc')! == .explicit
910 assert !s.lock_left()
911}
912
913fn test_provider_question_under_a_frontend() ! {
914 // app needs a shell two repo packages provide: libalpm asks which, the
915 // frontend gets the providers as the choices, and the answer is what is
916 // installed
917 s := fake_system('provider')!
918 defer { os.rmdir_all(s.tmp) or {} }
919 s.publish([fake_pkg('app', '1.0-1', ['shell']),
920 FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['shell'] },
921 FakePkg{ ...fake_pkg('dash', '1.0-1', []), provides: ['shell'] }])!
922 // the frontend picks the second provider of question 1
923 run := s.run('{"id": 1, "answer": 1}\n{"id": 2, "answer": true}\n', fn () ! {
924 install(ConfigInstall{ query: ['app'] })!
925 })!
926 assert run.err == ''
927 questions := run.of('question')
928 assert questions.len == 2
929 assert questions[0]['question']!.str() == 'choose'
930 assert questions[0]['msg']!.str() == '2 providers for shell'
931 choices := questions[0]['choices']!.as_array().map(it.str())
932 assert choices.len == 2
933 assert choices.all(it.starts_with('core/') && it.ends_with(' 1.0-1'))
934 chosen := choices[1].all_after('/').all_before(' ')
935 assert questions[1]['question']!.str() == 'proceed'
936 installed := s.installed()!
937 assert chosen in installed && installed.len == 2, installed.str()
938 assert 'app' in installed
939}
940
941fn test_provider_rows_number_the_choices() ! {
942 s := fake_system('providerrows')!
943 defer { os.rmdir_all(s.tmp) or {} }
944 s.publish([fake_pkg('bash', '1.0-1', []), fake_pkg('dash', '2.0-1', [])])!
945 run := s.run('', fn () ! {
946 mut handle := init_handle(new_trans_ui())!
947 defer { handle.release() or {} }
948 dbs := init_repos(mut handle)!
949 bash := dbs[0].get_pkg('bash') or { return error('no bash') }
950 dash := dbs[0].get_pkg('dash') or { return error('no dash') }
951 if provider_choice(dash) != 'core/dash 2.0-1' {
952 return error('choice ${provider_choice(dash)}')
953 }
954 text := table_text(provider_rows([bash, dash]), '', ' ')
955 if text.split('\n').map(it.trim_space()) != ['1) core/bash 1.0-1', '2) core/dash 2.0-1'] {
956 return error('rows ${text}')
957 }
958 })!
959 assert run.err == ''
960}
961
962fn test_fuzzy_search_lists_name_matches_then_desc_matches_once() ! {
963 s := fake_system('fuzzy')!
964 defer { os.rmdir_all(s.tmp) or {} }
965 s.publish([FakePkg{
966 ...fake_pkg('zsh', '1.0-1', [])
967 desc: 'zsh is the z shell'
968 }, FakePkg{
969 ...fake_pkg('fish', '1.0-1', [])
970 desc: 'a friendly shell, much like zsh'
971 }, FakePkg{
972 ...fake_pkg('bash', '1.0-1', [])
973 desc: 'the gnu bourne again shell'
974 }, FakePkg{
975 ...fake_pkg('zsh-doc', '1.0-1', [])
976 desc: 'documentation'
977 }])!
978 run := s.run('', fn () ! {
979 mut handle := init_handle(new_trans_ui())!
980 defer { handle.release() or {} }
981 dbs := init_repos(mut handle)!
982 mut cache := pkgcache_of(handle, dbs[0])!
983 got := build_matches(cache.pkgs(), ConfigSearch{
984 fuzzy: true
985 thold: 0.9
986 query: ['zsh']
987 }).map(it.get_name())
988 // zsh by its name (and not again for its desc), then fish by its desc;
989 // bash matches neither, and zsh-doc's name is too far at this threshold
990 if got != ['zsh', 'fish'] {
991 return error('matched ${got}')
992 }
993 })!
994 assert run.err == ''
995}
996
997// with_file_dbs publishes the packages with their file db already synced,
998// as a find without -y reads it
999fn with_file_dbs(name string, pkgs []FakePkg) !FakeSystem {
1000 s := fake_system(name)!
1001 s.publish(pkgs)!
1002 os.cp(s.path('repo/core.files'), s.path('db/sync/core.files'))!
1003 return s
1004}
1005
1006// providers_of maps each path a find answered to the packages it named
1007fn providers_of(run FrontendRun) map[string][]string {
1008 mut out := map[string][]string{}
1009 for e in run.of('provides') {
1010 mut names := e['entries']!.as_array().map(it.as_map()['name']!.str())
1011 names.sort()
1012 out[e['path']!.str()] = names
1013 }
1014 return out
1015}
1016
1017fn test_find_owner_index_answers_as_the_walk() ! {
1018 s := with_file_dbs('findowner', [
1019 FakePkg{
1020 name: 'bar'
1021 files: {
1022 'usr/bin/bar': 'bar'
1023 }
1024 },
1025 FakePkg{
1026 name: 'baz'
1027 files: {
1028 'usr/bin/baz': 'baz'
1029 'usr/lib/libbaz': 'lib'
1030 }
1031 },
1032 ])!
1033 defer { os.rmdir_all(s.tmp) or {} }
1034 paths := ['/usr/bin/bar', 'usr/lib/libbaz', '/usr/bin/', '/usr/bin', '/nope']
1035 // several paths at once go through the index
1036 many := s.run('', fn [paths] () ! {
1037 find(ConfigFind{ query: paths })!
1038 })!
1039 got := providers_of(many)
1040 assert got['/usr/bin/bar']! == ['bar']
1041 assert got['usr/lib/libbaz']! == ['baz']
1042 // a directory is every package's that carries it, with or without its slash
1043 assert got['/usr/bin/']! == ['bar', 'baz']
1044 assert got['/usr/bin']! == ['bar', 'baz']
1045 // the miss is named, as a target error, and counted
1046 misses := many.of('error').filter(it['target']!.bool())
1047 assert misses.len == 1
1048 assert misses[0]['msg']!.str() == 'no package provides /nope'
1049 // one path at a time walks the filelists: the same answers
1050 for p in paths {
1051 one := s.run('', fn [p] () ! {
1052 find(ConfigFind{ query: [p] })!
1053 })!
1054 assert providers_of(one)[p] or { []string{} } == got[p] or { []string{} }, p
1055 }
1056}
1057
1058fn test_find_list_names_its_misses() ! {
1059 s := with_file_dbs('findlist', [FakePkg{
1060 name: 'bar'
1061 files: {
1062 'usr/bin/bar': 'bar'
1063 }
1064 }])!
1065 defer { os.rmdir_all(s.tmp) or {} }
1066 run := s.run('', fn () ! {
1067 find(ConfigFind{ list: true, query: ['bar', 'nothere'] })!
1068 })!
1069 lists := run.of('files')
1070 assert lists.len == 1
1071 assert lists[0]['package']!.str() == 'bar'
1072 assert lists[0]['repo']!.str() == 'core'
1073 assert lists[0]['paths']!.as_array().map(it.str()) == ['usr/', 'usr/bin/', 'usr/bin/bar']
1074 misses := run.of('error').filter(it['target']!.bool())
1075 assert misses.len == 1
1076 assert misses[0]['msg']!.str().contains('nothere')
1077}
1078
1079// stale_after_update updates the sync dbs over file:// and answers what
1080// the freshness check then calls stale
1081fn (s FakeSystem) stale_after_update() !FrontendRun {
1082 return s.run('', fn () ! {
1083 mut handle := init_handle(new_trans_ui())!
1084 defer { handle.release() or {} }
1085 init_repos(mut handle)!
1086 update_repos(mut handle, false)!
1087 stale := stale_sync_dbs(handle)
1088 report('stale: ${stale.join(',')}')
1089 })!
1090}
1091
1092fn test_sync_stamp_keeps_an_old_server_time_fresh() ! {
1093 s := fake_system('stamp')!
1094 defer { os.rmdir_all(s.tmp) or {} }
1095 s.publish([foo('1.0-1', 'one')])!
1096 // the server's db has not changed in two days: libalpm gives the copy
1097 // it downloads the server's time, so only vpac's stamp says it is current
1098 two_days_ago := time.now().unix() - 2 * sync_max_age
1099 os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)!
1100 os.rm(s.path('db/sync/core.db'))!
1101 run := s.stale_after_update()!
1102 assert run.err == ''
1103 assert os.file_last_mod_unix(s.path('db/sync/core.db')) <= two_days_ago + 1
1104 assert os.exists(s.path('db/sync/vpac.synced'))
1105 assert run.of('message').any(it['text']!.str() == 'stale: ')
1106}
1107
1108fn test_sync_stamp_that_cannot_be_written_is_said() ! {
1109 s := fake_system('stampfail')!
1110 defer { os.rmdir_all(s.tmp) or {} }
1111 s.publish([foo('1.0-1', 'one')])!
1112 two_days_ago := time.now().unix() - 2 * sync_max_age
1113 os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)!
1114 os.rm(s.path('db/sync/core.db'))!
1115 // the stamp's path leads nowhere writable: its write fails, and no stamp
1116 // is there after it (a link into a directory that does not exist)
1117 os.symlink(s.path('nowhere/vpac.synced'), s.path('db/sync/vpac.synced'))!
1118 run := s.stale_after_update()!
1119 assert run.err == ''
1120 // said, as a warning naming the stamp, and the db counts stale again —
1121 // touching the db instead would feed libalpm's If-Modified-Since a lie
1122 warned := run.of('message').filter(it['warning'] or { json2.Any(false) }.bool())
1123 assert warned.len == 1
1124 assert warned[0]['text']!.str().starts_with('could not write the sync stamp ${s.path('db/sync/vpac.synced')}')
1125 assert run.of('message').any(it['text']!.str() == 'stale: core')
1126}
1127
1128fn test_libalpm_warnings_reach_the_frontend() ! {
1129 // installing what is installed already: libalpm says so at warning level,
1130 // through its log callback alone, as pacman prints it
1131 s := fake_system('alpmwarn')!
1132 defer { os.rmdir_all(s.tmp) or {} }
1133 s.install_local(foo('1.0-1', 'one'))!
1134 s.publish([foo('1.0-1', 'one')])!
1135 run := s.run('', fn () ! {
1136 install(ConfigInstall{ noconfirm: true, query: ['foo'] })!
1137 })!
1138 assert run.err == ''
1139 said := run.of('message').filter(it['text']!.str() == 'foo-1.0-1 is up to date -- reinstalling')
1140 assert said.len == 1, run.of('message').str()
1141 assert said[0]['warning']!.bool()
1142 assert 'error' !in said[0]
1143}
1144
1145fn test_libalpm_errors_reach_the_frontend() ! {
1146 // a corrupt mtree: libalpm's error names the file and libarchive's reason
1147 s := fake_system('alpmerror')!
1148 defer { os.rmdir_all(s.tmp) or {} }
1149 s.install_local(foo('1.0-1', 'one'))!
1150 res := os.exec(['sh', '-c', 'printf "#mtree\\n./a type=file\\n" | gzip | head -c 15 > "\$0"',
1151 s.path('db/local/foo-1.0-1/mtree')])
1152 assert res.exit_code == 0, res.output
1153 run := s.run('', fn () ! {
1154 verify(ConfigVerify{
1155 checksums_level: 2
1156 })!
1157 })!
1158 assert run.err == ''
1159 errors := run.of('message').filter(it['error'] or { json2.Any(false) }.bool())
1160 assert errors.len == 1, run.of('message').str()
1161 assert errors[0]['text']!.str() == 'error while reading file ${s.path('db/local/foo-1.0-1/mtree')}: truncated gzip input'
1162 assert errors[0]['warning']!.bool()
1163}
1164
1165fn test_mark_and_verify_skip_what_names_nothing() ! {
1166 s := fake_system('skiptargets')!
1167 defer { os.rmdir_all(s.tmp) or {} }
1168 s.install_local(foo('1.0-1', 'one'))!
1169 s.install_local(FakePkg{
1170 ...fake_pkg('impl', '1.0-1', [])
1171 provides: ['virt=2']
1172 })!
1173 // a bad target is reported and counted; the good ones are still marked
1174 marked := s.run('', fn () ! {
1175 mark(ConfigMark{ reason: 'd', query: ['nope', 'foo'] })!
1176 })!
1177 assert marked.err == '' && marked.failed == 1
1178 assert marked.of('done')[0]['packages']!.as_array().map(it.str()) == ['foo']
1179 // verify resolves a versioned name and a provision, as pacman's -Qk
1180 // does, and names the target nothing answers
1181 checked := s.run('', fn () ! {
1182 verify(ConfigVerify{ query: ['foo>=1.0', 'virt', 'ghost'] })!
1183 })!
1184 assert checked.err == '', checked.err
1185 assert checked.failed == 1
1186 assert target_errors(checked) == ['package "ghost" was not found']
1187 none_there := s.run('', fn () ! {
1188 verify(ConfigVerify{ query: ['ghost'] })!
1189 })!
1190 assert none_there.err.contains('no one of the named packages'), none_there.err
1191}
1192
1193fn test_tree_of_several_targets_under_a_frontend() ! {
1194 s := fake_system('tree')!
1195 defer { os.rmdir_all(s.tmp) or {} }
1196 s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])!
1197 run := s.run('', fn () ! {
1198 tree(ConfigTree{ query: ['app', 'lib', 'nope'] })!
1199 })!
1200 assert run.err == ''
1201 // each tree is its own event, every channel line one json object, and
1202 // nothing at all reaches stdout — the blank line between trees is a
1203 // terminal's frame
1204 trees := run.of('tree')
1205 assert trees.len == 2
1206 assert trees[0]['root']!.as_map()['name']!.str() == 'app'
1207 children := trees[0]['root']!.as_map()['children']!.as_array()
1208 assert children.len == 1 && children[0].as_map()['name']!.str() == 'lib'
1209 assert trees[1]['root']!.as_map()['name']!.str() == 'lib'
1210 assert run.of('error').filter(it['target']!.bool()).len == 1
1211 assert run.stdout == '', run.stdout
1212}
1213
1214fn test_tree_leaves_the_sync_dbs_alone_until_needed() ! {
1215 // no sync db was ever fetched here, so setting them up warns that they
1216 // are not synced: a tree among installed packages never gets that far,
1217 // one that has to look past them does
1218 s := fake_system('treelazy')!
1219 defer { os.rmdir_all(s.tmp) or {} }
1220 s.install_local(fake_pkg('app', '1.0-1', ['lib']))!
1221 s.install_local(fake_pkg('lib', '1.0-1', []))!
1222 s.install_local(fake_pkg('broken', '1.0-1', ['gone']))!
1223 stale := fn (run FrontendRun) int {
1224 return run.of('message').filter(it['text'] or { json2.Any('') }.str().contains('not synced')).len
1225 }
1226 for query in [['app'], ['local/app', 'lib'], ['lib']] {
1227 local := s.run('', fn [query] () ! {
1228 tree(ConfigTree{ query: query })!
1229 })!
1230 assert local.err == '', local.err
1231 assert local.of('tree').len == query.len
1232 assert stale(local) == 0, '${query}: ${local.of('message')}'
1233 }
1234 // the reverse tree reads the installed packages alone, too
1235 reverse := s.run('', fn () ! {
1236 tree(ConfigTree{ reverse: true, query: ['lib'] })!
1237 })!
1238 assert reverse.of('tree').len == 1 && stale(reverse) == 0
1239 // a target that is not installed, and a dependency nothing installed
1240 // answers, each reach for the sync dbs — once, however many ask
1241 for query in [['nowhere'], ['broken'], ['broken', 'nowhere', 'core/x']] {
1242 past := s.run('', fn [query] () ! {
1243 tree(ConfigTree{ query: query })!
1244 })!
1245 assert stale(past) == 1, '${query}: ${past.of('message')}'
1246 }
1247 // what nothing provides is still drawn, as not found
1248 broken := s.run('', fn () ! {
1249 tree(ConfigTree{ query: ['broken'] })!
1250 })!
1251 child := broken.of('tree')[0]['root']!.as_map()['children']!.as_array()[0].as_map()
1252 assert child['name']!.str() == 'gone' && !(child['found'] or { json2.Any(false) }.bool())
1253}
1254
1255fn test_tree_of_several_targets_on_a_terminal() ! {
1256 s := fake_system('treetty')!
1257 defer { os.rmdir_all(s.tmp) or {} }
1258 s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])!
1259 run := s.run_ui('tty', '', fn () ! {
1260 tree(ConfigTree{ query: ['app', 'lib'] })!
1261 })!
1262 assert run.err == ''
1263 // the terminal gets the trees on stdout, a blank line between them
1264 trees := run.stdout.split('\n\n')
1265 assert trees.len == 2, run.stdout
1266 assert trees[0].starts_with('app'), run.stdout
1267 assert trees[1].starts_with('lib'), run.stdout
1268 assert run.events.len == 0
1269}
1270
1271fn test_failed_targets_count_per_run() ! {
1272 // one run's bad targets are its own: the next run in the same process
1273 // starts from none, as each vpac process does
1274 s := with_file_dbs('failedcount', [FakePkg{
1275 name: 'bar'
1276 files: {
1277 'usr/bin/bar': 'bar'
1278 }
1279 }])!
1280 defer { os.rmdir_all(s.tmp) or {} }
1281 misses := s.run('', fn () ! {
1282 find(ConfigFind{ query: ['/nope', '/usr/bin/bar', '/neither'] })!
1283 })!
1284 assert misses.failed == 2
1285 clean := s.run('', fn () ! {
1286 find(ConfigFind{ query: ['/usr/bin/bar'] })!
1287 })!
1288 assert clean.failed == 0
1289 // and a run leaves the count of whoever called it as it found it: the
1290 // run's own is in its result, not in the global after it
1291 failed_targets = 7
1292 defer { failed_targets = 0 }
1293 again := s.run('', fn () ! {
1294 find(ConfigFind{ query: ['/nope'] })!
1295 })!
1296 assert again.failed == 1
1297 assert failed_targets == 7
1298}
1299
1300fn test_install_of_several_archives_is_one_transaction() ! {
1301 // what a split build hands install: its archives, as local files, which
1302 // go in together — one listing, one go-ahead, one done event
1303 s := fake_system('archives')!
1304 defer { os.rmdir_all(s.tmp) or {} }
1305 s.publish([FakePkg{
1306 name: 'split-a'
1307 files: {
1308 'usr/share/split/a': 'a'
1309 }
1310 }, FakePkg{
1311 name: 'split-b'
1312 files: {
1313 'usr/share/split/b': 'b'
1314 }
1315 }])!
1316 archives := ['split-a', 'split-b'].map(s.path('repo/${it}-1.0-1-any.pkg.tar'))
1317 run := s.run('', fn [archives] () ! {
1318 install(ConfigInstall{ noconfirm: true, query: archives })!
1319 })!
1320 assert run.err == ''
1321 assert run.of('transaction').len == 1
1322 assert run.of('question').len == 1
1323 done := run.done()!
1324 assert sorted_strs(done['packages']!) == ['split-a', 'split-b']
1325 assert s.installed()! == {
1326 'split-a': '1.0-1'
1327 'split-b': '1.0-1'
1328 }
1329 assert os.read_file(s.path('root/usr/share/split/b'))! == 'b'
1330}
1331
1332// FakeRpc answers the pkgbuild rpc's info and search requests from a set of
1333// packages, or every request with raw when it is set
1334struct FakeRpc {
1335 pkgs map[string]PackagePkgbuild
1336 raw string
1337}
1338
1339fn (mut h FakeRpc) handle(req http.Request) http.Response {
1340 if h.raw != '' {
1341 return http.new_response(body: h.raw)
1342 }
1343 u := urllib.parse(req.url) or { return http.new_response(status: .bad_request) }
1344 mut results := []PackagePkgbuild{}
1345 if u.path == '/rpc/v5/info' {
1346 q := urllib.parse_query(u.raw_query) or { urllib.new_values() }
1347 for name in q.get_all('arg[]') {
1348 if p := h.pkgs[name] {
1349 results << p
1350 }
1351 }
1352 } else if u.path.starts_with('/rpc/v5/search/') {
1353 needle := u.path.all_after('/rpc/v5/search/')
1354 // by name, so several results come in an order a test can name
1355 mut names := h.pkgs.keys().filter(it.contains(needle))
1356 names.sort()
1357 for name in names {
1358 results << h.pkgs[name]
1359 }
1360 }
1361 return http.new_response(
1362 body: json2.encode(PackagesPkgbuild{
1363 count: results.len
1364 results: results
1365 type: 'multiinfo'
1366 version: 5
1367 })
1368 )
1369}
1370
1371// aur_pkg is a pkgbuild repo package of the fake rpc
1372fn aur_pkg(name string, depends []string, make_depends []string) PackagePkgbuild {
1373 return PackagePkgbuild{
1374 name: name
1375 package_base: name
1376 version: '1.0-1'
1377 depends: depends
1378 make_depends: make_depends
1379 }
1380}
1381
1382// fake_rpc serves h on a free localhost port until the returned server is
1383// stopped, and answers its base url
1384fn fake_rpc(h FakeRpc) !(&http.Server, string) {
1385 mut server := &http.Server{
1386 addr: '127.0.0.1:0'
1387 handler: h
1388 show_startup_message: false
1389 worker_num: 1
1390 }
1391 spawn server.listen_and_serve()
1392 server.wait_till_running()!
1393 return server, 'http://${server.addr}'
1394}
1395
1396fn test_pkgbuild_info_from_the_rpc() ! {
1397 mut server, base := fake_rpc(FakeRpc{
1398 pkgs: {
1399 'yay-bin': aur_pkg('yay-bin', ['pacman'], [])
1400 }
1401 })!
1402 defer { server.stop() }
1403 got := get_pkgbuild_info(base, ['yay-bin', 'nothere'])!
1404 assert got.map(it.name) == ['yay-bin']
1405 assert got[0].depends == ['pacman']
1406 found := get_pkgbuild_packages(base, 'yay')!
1407 assert found.map(it.name) == ['yay-bin']
1408 // no names asks for nothing, without a request
1409 assert get_pkgbuild_info(base, [])!.len == 0
1410}
1411
1412fn test_pkgbuild_rpc_short_garbage_is_an_error() ! {
1413 // a 200 whose body is no json and shorter than the quote of it: an error
1414 // naming what came, not a panic
1415 mut server, base := fake_rpc(FakeRpc{
1416 raw: 'oops'
1417 })!
1418 defer { server.stop() }
1419 get_pkgbuild_info(base, ['x']) or {
1420 assert err.msg().starts_with('failed to decode package info'), err.msg()
1421 assert err.msg().ends_with('(the answer begins: oops)'), err.msg()
1422 get_pkgbuild_packages(base, 'x') or {
1423 assert err.msg().ends_with('(the answer begins: oops)'), err.msg()
1424 return
1425 }
1426 assert false, 'the search took garbage'
1427 }
1428 assert false, 'the info lookup took garbage'
1429}
1430
1431// resolve walks name through the fake system's local and sync dbs and the
1432// fake rpc, as pkgbuild_install does, and answers the build plan
1433fn resolve(s FakeSystem, base string, name string) ![]PkgbuildNode {
1434 // the closure captures by value: the plan comes out through the heap
1435 mut plan := &Plan{}
1436 run := s.run('', fn [base, name, mut plan] () ! {
1437 cfg_repos << CfgRepo{
1438 name: 'aur'
1439 kind: 'pkgbuild'
1440 servers: [base]
1441 }
1442 mut handle := init_handle(new_trans_ui())!
1443 defer { handle.release() or {} }
1444 init_repos(mut handle)!
1445 plan.nodes << pkgbuild_plan(handle, name)!
1446 })!
1447 if run.err != '' {
1448 return error(run.err)
1449 }
1450 return plan.nodes
1451}
1452
1453@[heap]
1454struct Plan {
1455mut:
1456 nodes []PkgbuildNode
1457}
1458
1459fn test_pkgbuild_resolver_orders_the_build() ! {
1460 s := fake_system('resolver')!
1461 defer { os.rmdir_all(s.tmp) or {} }
1462 // glibc installed, lib in the repos, the rest only in the pkgbuild repo
1463 s.install_local(fake_pkg('glibc', '1.0-1', []))!
1464 s.publish([fake_pkg('lib', '1.0-1', [])])!
1465 mut server, base := fake_rpc(FakeRpc{
1466 pkgs: {
1467 'top': PackagePkgbuild{
1468 ...aur_pkg('top', ['mid', 'lib', 'glibc>=1.0', 'shared'], ['tool'])
1469 check_depends: ['checker']
1470 }
1471 'checker': aur_pkg('checker', [], [])
1472 'mid': aur_pkg('mid', ['leaf', 'shared'], [])
1473 'leaf': aur_pkg('leaf', [], [])
1474 'shared': aur_pkg('shared', [], [])
1475 'tool': aur_pkg('tool', [], [])
1476 }
1477 })!
1478 defer { server.stop() }
1479 plan := resolve(s, base, 'top')!
1480 // dependencies first, each once (shared is reached twice), the target last
1481 // what check() needs is planned as what the build needs is
1482 assert plan.map(it.info.name) == ['leaf', 'shared', 'mid', 'tool', 'checker', 'top']
1483 // a repo package is installed before the build that needs it; an
1484 // installed one is not touched; the site is the pkgbuild repo it came from
1485 top := plan.last()
1486 assert top.repo_deps == ['lib']
1487 assert plan.all(it.site == base)
1488 assert plan.filter(it.info.name != 'top').all(it.repo_deps.len == 0)
1489 // every node carries what wanted it, as the dependents spelled it: the
1490 // target nothing, a node wanted twice both spellings once each
1491 wanted := fn [plan] (name string) []string {
1492 return plan.filter(it.info.name == name)[0].wanted
1493 }
1494 assert wanted('top') == []
1495 assert wanted('mid') == ['mid'] && wanted('leaf') == ['leaf']
1496 assert wanted('shared') == ['shared']
1497 assert wanted('checker') == ['checker']
1498 // a site the config spells with a trailing slash joins a clone url with
1499 // one slash all the same
1500 slashed := resolve(s, base + '/', 'leaf')!
1501 assert slashed[0].site == base
1502}
1503
1504fn test_pkgbuild_resolver_refuses_cycles_and_unknowns() ! {
1505 s := fake_system('resolverbad')!
1506 defer { os.rmdir_all(s.tmp) or {} }
1507 s.publish([fake_pkg('lib', '1.0-1', [])])!
1508 mut server, base := fake_rpc(FakeRpc{
1509 pkgs: {
1510 'c1': aur_pkg('c1', ['c2'], [])
1511 'c2': aur_pkg('c2', ['c1'], [])
1512 'needy': aur_pkg('needy', ['ghost>=2'], [])
1513 }
1514 })!
1515 defer { server.stop() }
1516 resolve(s, base, 'c1') or {
1517 assert err.msg() == 'circular pkgbuild dependency: c1 is walked as its own dependency', err.msg()
1518 resolve(s, base, 'needy') or {
1519 assert err.msg() == '"ghost" is not in the repos or the pkgbuild repo', err.msg()
1520 return
1521 }
1522 assert false, 'a dependency nowhere was planned'
1523 }
1524 assert false, 'a cycle was planned'
1525}
1526
1527// target_errors are the messages of the target errors a run reported
1528fn target_errors(run FrontendRun) []string {
1529 return run.of('error').filter(it['target'] or { json2.Any(false) }.bool()).map(it['msg'] or {
1530 json2.Any('')
1531 }.str())
1532}
1533
1534fn test_install_scopes_a_target_to_its_repo() ! {
1535 s := fake_system('scope')!
1536 defer { os.rmdir_all(s.tmp) or {} }
1537 s.publish([fake_pkg('foo', '1.0-1', [])])!
1538 // a repo the config does not carry is an error, not a prefix to drop
1539 bad := s.run('', fn () ! {
1540 install(ConfigInstall{ noconfirm: true, query: ['nope/foo'] })!
1541 })!
1542 assert target_errors(bad) == ['database not found: nope']
1543 assert s.installed()!.len == 0
1544 // a name the repo named does not hold is not looked up anywhere else
1545 miss := s.run('', fn () ! {
1546 install(ConfigInstall{ noconfirm: true, query: ['core/nothere'] })!
1547 })!
1548 assert target_errors(miss) == ['target not found in core: nothere']
1549 good := s.run('', fn () ! {
1550 install(ConfigInstall{ noconfirm: true, query: ['core/foo'] })!
1551 })!
1552 assert good.err == '' && good.failed == 0
1553 assert s.installed()! == {
1554 'foo': '1.0-1'
1555 }
1556}
1557
1558fn test_install_resolves_constraints_and_providers() ! {
1559 s := fake_system('satisfier')!
1560 defer { os.rmdir_all(s.tmp) or {} }
1561 s.publish([fake_pkg('foo', '2.0-1', []),
1562 FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] }])!
1563 run := s.run('', fn () ! {
1564 install(ConfigInstall{ noconfirm: true, query: ['foo>=2', 'sh'] })!
1565 })!
1566 assert run.err == '' && run.failed == 0, run.err
1567 assert s.installed()! == {
1568 'foo': '2.0-1'
1569 'bash': '1.0-1'
1570 }
1571 // a version nothing has is a miss like any other
1572 old := s.run('', fn () ! {
1573 install(ConfigInstall{ noconfirm: true, query: ['core/foo>=3'] })!
1574 })!
1575 assert target_errors(old) == ['target not found in core: foo>=3']
1576}
1577
1578fn test_install_names_every_bad_target_and_installs_nothing() ! {
1579 s := fake_system('badtargets')!
1580 defer { os.rmdir_all(s.tmp) or {} }
1581 s.publish([fake_pkg('foo', '1.0-1', [])])!
1582 run := s.run('', fn () ! {
1583 install(ConfigInstall{ noconfirm: true, query: ['zzzzzz', 'foo', 'qqqqqq'] })!
1584 })!
1585 // both misses are told, not only the first, and the good one waits
1586 assert run.err == ''
1587 assert run.failed == 2
1588 assert target_errors(run).len == 2
1589 assert run.of('done').len == 0
1590 assert s.installed()!.len == 0
1591 assert !s.lock_left()
1592}
1593
1594fn tool(name string) FakePkg {
1595 return FakePkg{
1596 ...fake_pkg(name, '1.0-1', [])
1597 groups: ['tools']
1598 }
1599}
1600
1601fn test_install_asks_which_members_of_a_group() ! {
1602 s := fake_system('groupselect')!
1603 defer { os.rmdir_all(s.tmp) or {} }
1604 s.publish([tool('aa'), tool('bb'), tool('cc')])!
1605 // the frontend picks the first and the third, then lets it go
1606 run := s.run('{"id": 1, "answer": [0, 2]}\n{"id": 2, "answer": true}\n', fn () ! {
1607 install(ConfigInstall{ query: ['tools'] })!
1608 })!
1609 assert run.err == '', run.err
1610 // the members go out as a listing, each naming its group, then the question
1611 lists := run.of('listing')
1612 assert lists.len == 1
1613 members := lists[0]['entries']!.as_array().map(it.as_map())
1614 assert members.map(it['name'] or { json2.Any('') }.str()) == ['aa', 'bb', 'cc']
1615 assert members.all(it['group'] or { json2.Any('') }.str() == 'tools')
1616 questions := run.of('question')
1617 assert questions[0]['question']!.str() == 'select'
1618 assert questions[0]['preset']!.as_array().len == 3
1619 assert s.installed()! == {
1620 'aa': '1.0-1'
1621 'cc': '1.0-1'
1622 }
1623 // --noconfirm takes every member left; the installed ones are not offered
1624 rest := s.run('', fn () ! {
1625 install(ConfigInstall{ noconfirm: true, query: ['tools'] })!
1626 })!
1627 assert rest.err == ''
1628 assert rest.of('listing')[0]['entries']!.as_array().len == 1
1629 assert s.installed()!.len == 3
1630 // nothing left: said, and no failure
1631 done := s.run('', fn () ! {
1632 install(ConfigInstall{ noconfirm: true, query: ['tools'] })!
1633 })!
1634 assert done.err == '' && done.failed == 0
1635 assert done.of('message').any(it['text'] or { json2.Any('') }.str().contains('every member'))
1636}
1637
1638fn test_group_selection_on_a_terminal() ! {
1639 s := fake_system('groupselecttty')!
1640 defer { os.rmdir_all(s.tmp) or {} }
1641 s.publish([tool('aa'), tool('bb'), tool('cc')])!
1642 // all but the second, then the go-ahead
1643 run := s.run_ui('tty', '^2\ny\n', fn () ! {
1644 install(ConfigInstall{ query: ['tools'] })!
1645 })!
1646 assert run.err == '', run.err
1647 assert s.installed()! == {
1648 'aa': '1.0-1'
1649 'cc': '1.0-1'
1650 }
1651 // --print lists every member and asks nothing
1652 preview := s.run_ui('tty', '', fn () ! {
1653 install(ConfigInstall{ print_only: true, query: ['tools'] })!
1654 })!
1655 assert preview.stdout.trim_space() == 'bb-1.0-1-any.pkg.tar', preview.stdout
1656}
1657
1658fn test_remove_takes_a_group_and_names_every_bad_target() ! {
1659 s := fake_system('removegroup')!
1660 defer { os.rmdir_all(s.tmp) or {} }
1661 s.install_local(tool('aa'))!
1662 s.install_local(tool('bb'))!
1663 s.install_local(fake_pkg('keep', '1.0-1', []))!
1664 // one unknown target stops the removal, after every one is named
1665 bad := s.run('', fn () ! {
1666 remove(ConfigRemove{ noconfirm: true, query: ['zzzzzz', 'tools', 'qqqqqq'] })!
1667 })!
1668 assert bad.failed == 2
1669 assert s.installed()!.len == 3
1670 assert !s.lock_left()
1671 run := s.run('', fn () ! {
1672 remove(ConfigRemove{ noconfirm: true, query: ['tools'] })!
1673 })!
1674 assert run.err == '', run.err
1675 assert sorted_strs(run.done()!['packages']!) == ['aa', 'bb']
1676 assert s.installed()! == {
1677 'keep': '1.0-1'
1678 }
1679}
1680
1681fn test_remove_unneeded_and_recursive_levels() ! {
1682 s := fake_system('removelevels')!
1683 defer { os.rmdir_all(s.tmp) or {} }
1684 s.install_local(fake_pkg('app', '1.0-1', ['lib', 'tool']))!
1685 s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
1686 // tool was installed explicitly, though app needs it
1687 s.install_local(fake_pkg('tool', '1.0-1', []))!
1688 s.install_local(fake_pkg('other', '1.0-1', []))!
1689 // -u: lib stays where app needs it, other goes, and that is no failure
1690 u := s.run('', fn () ! {
1691 remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib', 'other'] })!
1692 })!
1693 assert u.err == '', u.err
1694 assert sorted_strs(u.done()!['packages']!) == ['other']
1695 assert 'lib' in s.installed()!
1696 none_left := s.run('', fn () ! {
1697 remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib'] })!
1698 })!
1699 assert none_left.err == '' && none_left.of('done').len == 0
1700 // a version constraint names what satisfies it
1701 // -s takes lib, a dependency; tool was asked for by name and stays
1702 one := s.run('', fn () ! {
1703 remove(ConfigRemove{ print_only: true, recursive_level: 1, query: ['app>=1'] })!
1704 })!
1705 assert one.err == '', one.err
1706 assert sorted_strs(one.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or {
1707 json2.Any('')
1708 })) == ['app', 'lib']
1709 // -ss takes the explicitly installed dependency too
1710 two := s.run('', fn () ! {
1711 remove(ConfigRemove{ print_only: true, recursive_level: 2, query: ['app'] })!
1712 })!
1713 assert sorted_strs(two.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or {
1714 json2.Any('')
1715 })) == ['app', 'lib', 'tool']
1716}
1717
1718fn test_upgrade_downgrades_only_when_asked() ! {
1719 s := fake_system('downgrade')!
1720 defer { os.rmdir_all(s.tmp) or {} }
1721 s.install_local(foo('2.0-1', 'two'))!
1722 s.publish([foo('1.0-1', 'one')])!
1723 plain := s.run('', fn () ! {
1724 upgrade(ConfigUpgrade{ noconfirm: true })!
1725 })!
1726 assert plain.err == ''
1727 assert s.installed()!['foo']! == '2.0-1'
1728 down := s.run('', fn () ! {
1729 upgrade(ConfigUpgrade{ noconfirm: true, sysupgrade_level: 2 })!
1730 })!
1731 assert down.err == '', down.err
1732 assert s.installed()!['foo']! == '1.0-1'
1733}
1734
1735fn test_info_changelog_and_package_files() ! {
1736 s := fake_system('changelog')!
1737 defer { os.rmdir_all(s.tmp) or {} }
1738 s.install_local(FakePkg{ ...fake_pkg('logged', '1.0-1', []), changelog: 'first release\n' })!
1739 s.install_local(fake_pkg('silent', '1.0-1', []))!
1740 s.publish([
1741 FakePkg{ ...fake_pkg('filed', '1.0-1', []), changelog: 'from the archive\n' },
1742 fake_pkg('other', '2.0-1', []),
1743 ])!
1744 run := s.run('', fn () ! {
1745 info(ConfigInfo{ changelog: true, query: ['logged', 'silent'] })!
1746 })!
1747 assert run.err == '' && run.failed == 0
1748 logs := run.of('changelog')
1749 assert logs.len == 1
1750 assert logs[0]['package']!.str() == 'logged'
1751 assert logs[0]['text']!.str() == 'first release\n'
1752 // the one without is said, and is no failure, as in pacman
1753 assert run.of('message').any(it['text'] or { json2.Any('') }.str().contains('no changelog available for silent'))
1754
1755 // -p: every target is a package file, and one that does not load is its
1756 // own error
1757 archives := ['filed-1.0-1', 'other-2.0-1'].map(s.path('repo/${it}-any.pkg.tar'))
1758 mut targets := archives.clone()
1759 targets << s.path('repo/nothere.pkg.tar')
1760 files := s.run('', fn [targets] () ! {
1761 info(ConfigInfo{ file: true, fields: 'name,version', query: targets })!
1762 })!
1763 infos := files.of('info')
1764 assert infos.len == 2
1765 assert files.failed == 1
1766 first := archives[0]
1767 log := s.run('', fn [first] () ! {
1768 info(ConfigInfo{ file: true, changelog: true, query: [first] })!
1769 })!
1770 assert log.of('changelog')[0]['text']!.str() == 'from the archive\n'
1771 tty := s.run_ui('tty', '', fn () ! {
1772 info(ConfigInfo{ changelog: true, query: ['logged'] })!
1773 })!
1774 assert tty.stdout == 'changelog for logged:\nfirst release\n', tty.stdout
1775}
1776
1777fn test_info_scopes_and_satisfiers() ! {
1778 s := fake_system('infoscope')!
1779 defer { os.rmdir_all(s.tmp) or {} }
1780 s.install_local(FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] })!
1781 s.publish([fake_pkg('bash', '2.0-1', []), fake_pkg('zsh', '1.0-1', [])])!
1782 version_of := fn (run FrontendRun) string {
1783 for f in run.of('info')[0]['fields'] or { json2.Any([]json2.Any{}) }.as_array() {
1784 m := f.as_map()
1785 if m['field'] or { json2.Any('') }.str() == 'version' {
1786 return m['value'] or { json2.Any('') }.str()
1787 }
1788 }
1789 return ''
1790 }
1791 // bare: the installed one; core/: the repo's; a provider resolves
1792 for target, version in {
1793 'bash': '1.0-1'
1794 'local/bash': '1.0-1'
1795 'core/bash': '2.0-1'
1796 'sh': '1.0-1'
1797 'bash>=2': '2.0-1'
1798 } {
1799 run := s.run('', fn [target] () ! {
1800 info(ConfigInfo{ noconfirm: true, query: [target] })!
1801 })!
1802 assert run.failed == 0, target
1803 assert version_of(run) == version, target
1804 }
1805 // local/ never reaches the sync dbs, and an unknown repo is an error
1806 for target, msg in {
1807 'local/zsh': 'unknown package: "zsh"'
1808 'nope/bash': 'database not found: nope'
1809 } {
1810 run := s.run('', fn [target] () ! {
1811 info(ConfigInfo{ noconfirm: true, query: [target] })!
1812 })!
1813 assert target_errors(run) == [msg], target
1814 }
1815}
1816
1817fn test_search_local_groups_and_all_members() ! {
1818 s := fake_system('localgroups')!
1819 defer { os.rmdir_all(s.tmp) or {} }
1820 s.install_local(tool('aa'))!
1821 s.install_local(fake_pkg('plain', '1.0-1', []))!
1822 s.publish([tool('aa'), tool('bb'), FakePkg{
1823 ...fake_pkg('cc', '1.0-1', [])
1824 groups: [
1825 'extras',
1826 ]
1827 }])!
1828 names := fn (run FrontendRun) []string {
1829 return run.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().map('${it.as_map()['group'] or {
1830 json2.Any('')
1831 }.str()} ${it.as_map()['name'] or { json2.Any('') }.str()}')
1832 }
1833 // -l -g: the local db's groups, the installed members alone
1834 local := s.run('', fn () ! {
1835 search(ConfigSearch{ local: true, groups: true, query: ['tools'] })!
1836 })!
1837 assert local.err == '', local.err
1838 assert names(local) == ['tools aa']
1839 bare := s.run('', fn () ! {
1840 search(ConfigSearch{ local: true, groups: true })!
1841 })!
1842 groups := bare.of('groups')[0]['groups']!.as_array().map(it.as_map())
1843 assert groups.len == 1
1844 assert groups[0]['repo']!.str() == 'local' && groups[0]['name']!.str() == 'tools'
1845 // -gg: every group of the sync dbs with its members
1846 all := s.run('', fn () ! {
1847 search(ConfigSearch{ remote: true, groups: true, groups_level: 2 })!
1848 })!
1849 mut got := names(all)
1850 got.sort()
1851 assert got == ['extras cc', 'tools aa', 'tools bb']
1852 tty := s.run_ui('tty', '', fn () ! {
1853 search(ConfigSearch{ local: true, groups: true, groups_level: 2 })!
1854 })!
1855 assert tty.stdout == 'tools aa\n', tty.stdout
1856 // a sync-comparing filter on the sync groups: the dbs are registered
1857 // once, and only the installed member can pass
1858 native := s.run('', fn () ! {
1859 search(ConfigSearch{ remote: true, groups: true, native: true, query: ['tools'] })!
1860 })!
1861 assert native.err == '', native.err
1862 assert names(native) == ['tools aa']
1863 // the terminal's table leads with the group, as the ipc entries carry it
1864 named := s.run_ui('tty', '', fn () ! {
1865 search(ConfigSearch{ remote: true, groups: true, fields: 'name', query: ['tools'] })!
1866 })!
1867 assert named.err == '', named.err
1868 assert named.stdout.split_into_lines().map(it.fields().join(' ')) == ['tools aa', 'tools bb'], named.stdout
1869}
1870
1871fn test_owner_quiet_names_the_package_alone() ! {
1872 s := fake_system('ownerquiet')!
1873 defer { os.rmdir_all(s.tmp) or {} }
1874 s.install_local(foo('1.0-1', 'one'))!
1875 path := s.path('root/usr/share/foo/hello')
1876 run := s.run_ui('tty', '', fn [path] () ! {
1877 owner(ConfigOwner{ quiet: true, query: [path] })!
1878 })!
1879 assert run.err == ''
1880 assert run.stdout == 'foo\n', run.stdout
1881}
1882
1883fn test_find_regex_and_machinereadable() ! {
1884 s := with_file_dbs('findregex', [
1885 FakePkg{
1886 name: 'bar'
1887 files: {
1888 'usr/bin/bar': 'bar'
1889 'usr/share/bar/x': 'x'
1890 }
1891 },
1892 FakePkg{
1893 name: 'baz'
1894 files: {
1895 'usr/bin/baz': 'baz'
1896 }
1897 },
1898 ])!
1899 defer { os.rmdir_all(s.tmp) or {} }
1900 // without a slash the expression is tried on file names, case ignored
1901 names := s.run('', fn () ! {
1902 find(ConfigFind{ regex: true, query: ['^BA.$'] })!
1903 })!
1904 assert providers_of(names)['^BA.$']! == ['bar', 'baz']
1905 // with one, on whole paths
1906 paths := s.run('', fn () ! {
1907 find(ConfigFind{ regex: true, query: ['share/.*x$', '/usr/bin/ba[rz]'] })!
1908 })!
1909 got := providers_of(paths)
1910 assert got['share/.*x$']! == ['bar']
1911 assert got['/usr/bin/ba[rz]']! == ['bar', 'baz']
1912 // a bad expression is named and nothing is searched
1913 bad := s.run('', fn () ! {
1914 find(ConfigFind{ regex: true, query: ['(', 'bar'] })!
1915 })!
1916 assert target_errors(bad) == ["invalid regular expression '('"]
1917 assert bad.of('provides').len == 0
1918 // pacman's --machinereadable: repo, package, version, path, NUL parted
1919 machine := s.run_ui('tty', '', fn () ! {
1920 find(ConfigFind{ regex: true, machinereadable: true, query: ['usr/bin/ba.'] })!
1921 })!
1922 assert machine.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\ncore\0baz\x001.0-1\0usr/bin/baz\n', machine.stdout.bytes().str()
1923 exact := s.run_ui('tty', '', fn () ! {
1924 find(ConfigFind{ machinereadable: true, query: ['/usr/bin/bar'] })!
1925 })!
1926 assert exact.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\n', exact.stdout.bytes().str()
1927 list := s.run_ui('tty', '', fn () ! {
1928 find(ConfigFind{ list: true, machinereadable: true, query: ['baz'] })!
1929 })!
1930 assert list.stdout.split('\n')[2] == 'core\0baz\x001.0-1\0usr/bin/baz', list.stdout.bytes().str()
1931 // an expression's event names the files it matched, one list a package
1932 matched := paths.of('provides').filter(it['path']!.str() == 'share/.*x$')
1933 assert matched[0]['files']!.as_array().map(it.as_array().map(it.str())) == [
1934 ['usr/share/bar/x'],
1935 ]
1936}
1937
1938fn test_find_names_slashes_and_scoped_lists() ! {
1939 s := with_file_dbs('findnames', [
1940 FakePkg{
1941 name: 'bar'
1942 files: {
1943 'usr/bin/bar': 'bar'
1944 'usr/share/bar/x': 'x'
1945 }
1946 },
1947 FakePkg{
1948 name: 'baz'
1949 files: {
1950 'usr/bin/baz': 'baz'
1951 }
1952 },
1953 ])!
1954 defer { os.rmdir_all(s.tmp) or {} }
1955 // a target with no slash is a file name: the directory usr/share/bar/
1956 // has none, the file usr/bin/bar does
1957 name := s.run('', fn () ! {
1958 find(ConfigFind{ query: ['bar'] })!
1959 })!
1960 assert providers_of(name)['bar']! == ['bar']
1961 assert name.of('provides')[0]['files']!.as_array().map(it.as_array().map(it.str())) == [
1962 ['usr/bin/bar'],
1963 ]
1964 // a trailing slash on a file's path answers the same alone as among
1965 // others: the walk and the index match it the same way
1966 alone := s.run('', fn () ! {
1967 find(ConfigFind{ query: ['/usr/bin/bar/'] })!
1968 })!
1969 among := s.run('', fn () ! {
1970 find(ConfigFind{ query: ['/usr/bin/bar/', '/usr/bin/baz'] })!
1971 })!
1972 assert providers_of(alone)['/usr/bin/bar/']! == ['bar']
1973 assert providers_of(among)['/usr/bin/bar/']! == ['bar']
1974 // slashes alone never become the empty expression
1975 assert find_rel('//') == '/' && find_rel('/usr/bin') == 'usr/bin' && find_rel('x') == 'x'
1976 // -l takes repo/package, and lists the package before the path
1977 scoped := s.run_ui('tty', '', fn () ! {
1978 find(ConfigFind{ list: true, query: ['core/baz'] })!
1979 })!
1980 assert scoped.err == '', scoped.err
1981 assert scoped.stdout.split_into_lines().map(it.fields().join(' ')) == ['baz usr/', 'baz usr/bin/',
1982 'baz usr/bin/baz'], scoped.stdout
1983 other := s.run('', fn () ! {
1984 find(ConfigFind{ list: true, query: ['nope/baz', 'core/'] })!
1985 })!
1986 assert other.of('files').len == 0
1987 assert target_errors(other).len == 2
1988}
1989
1990fn test_clean_levels_and_unused_sync_dbs() ! {
1991 s := fake_system('cleandbs')!
1992 defer { os.rmdir_all(s.tmp) or {} }
1993 s.install_local(foo('1.0-1', 'one'))!
1994 for f in ['foo-1.0-1-any.pkg.tar.zst', 'gone-1.0-1-any.pkg.tar.zst'] {
1995 os.write_file(s.path('cache/${f}'), 'x')!
1996 }
1997 // core is configured; old is a repo the config dropped
1998 for f in ['core.db', 'core.files', 'old.db', 'old.db.sig', 'old.files', 'vpac.synced'] {
1999 os.write_file(s.path('db/sync/${f}'), 'x')!
2000 }
2001 preview := s.run('', fn () ! {
2002 clean(ConfigClean{ print_only: true })!
2003 })!
2004 assert preview.err == '', preview.err
2005 ev := preview.of('clean')[0].clone()
2006 assert ev['files']!.as_array().map(os.base(it.str())) == ['gone-1.0-1-any.pkg.tar.zst']
2007 assert ev['dbs']!.as_array().map(os.base(it.str())) == ['old.db', 'old.db.sig', 'old.files']
2008 // -cc is every cached package, the installed one too
2009 all := s.run('', fn () ! {
2010 clean(ConfigClean{ print_only: true, level: 2 })!
2011 })!
2012 assert all.of('clean')[0]['files']!.as_array().len == 2
2013 run := s.run('', fn () ! {
2014 clean(ConfigClean{ noconfirm: true, level: 1 })!
2015 })!
2016 assert run.err == '', run.err
2017 mut left := os.ls(s.path('db/sync'))!
2018 left.sort()
2019 assert left == ['core.db', 'core.files', 'vpac.synced']
2020 assert os.ls(s.path('cache'))! == ['foo-1.0-1-any.pkg.tar.zst']
2021}
2022
2023// dead_mirror aims the repo at a server that has nothing: every refresh
2024// against it fails
2025fn (s FakeSystem) dead_mirror() {
2026 cfg_repos = [CfgRepo{
2027 name: 'core'
2028 kind: 'sync'
2029 servers: ['file://' + s.path('nowhere')]
2030 }]
2031}
2032
2033fn test_a_failed_refresh_is_an_error() ! {
2034 s := fake_system('deadmirror')!
2035 defer { os.rmdir_all(s.tmp) or {} }
2036 s.install_local(foo('1.0-1', 'one'))!
2037 s.publish([foo('2.0-1', 'two')])!
2038 up := s.run_ui('tty', '', fn [s] () ! {
2039 s.dead_mirror()
2040 upgrade(ConfigUpgrade{ noconfirm: true, sync_dbs: true })!
2041 })!
2042 se := s.run('', fn [s] () ! {
2043 s.dead_mirror()
2044 search(ConfigSearch{ remote: true, sync_dbs: true, query: ['foo'] })!
2045 })!
2046 fy := s.run('', fn [s] () ! {
2047 s.dead_mirror()
2048 find(ConfigFind{ refresh: true, query: ['/usr/share/foo/hello'] })!
2049 })!
2050 assert up.err != ''
2051 assert se.err != ''
2052 assert fy.err != ''
2053 assert s.installed()!['foo']! == '1.0-1'
2054 // no server left to fall through to: the held 404 is said, an error
2055 said := se.of('message').filter(it['text'] or { json2.Any('') }.str().contains('failed retrieving'))
2056 assert said.len == 1
2057 assert said[0]['error'] or { json2.Any(false) }.bool()
2058}
2059
2060// a mirror that lacks the package falls through to the next server: libalpm
2061// tries a repo's servers in order, and a file the first one does not have
2062// moves it on — the way a mirror that has not synced the archive yet is met.
2063// the first server here serves the db alone, the way a lagging mirror does,
2064// and the archive lives on the second
2065fn test_a_mirror_without_the_package_falls_through_to_the_next() ! {
2066 s := fake_system('fallback')!
2067 defer { os.rmdir_all(s.tmp) or {} }
2068 s.install_local(foo('1.0-1', 'one'))!
2069 s.publish([foo('2.0-1', 'two')])!
2070 // the lagging mirror: the db the primary serves, none of the archives
2071 lag := s.path('lag')
2072 os.mkdir_all(lag)!
2073 os.cp(s.path('repo/core.db'), os.join_path(lag, 'core.db'))!
2074 os.cp(s.path('repo/core.files'), os.join_path(lag, 'core.files'))!
2075 up := s.run('', fn [s, lag] () ! {
2076 cfg_repos = [CfgRepo{
2077 name: 'core'
2078 kind: 'sync'
2079 servers: ['file://' + lag, 'file://' + s.path('repo')]
2080 }]
2081 upgrade(ConfigUpgrade{ noconfirm: true })!
2082 })!
2083 assert up.err == '', up.err
2084 assert s.installed()!['foo']! == '2.0-1'
2085 // the fallback is an event a frontend sees: the archive's download says
2086 // retry, then completes
2087 retries := up.of('download').filter(it['retry'] or { json2.Any(false) }.bool())
2088 assert retries.len == 1
2089 assert retries[0]['file'].str() == 'foo-2.0-1-any.pkg.tar'
2090 // the 404 the lagging mirror got is not said: a mirror served the file
2091 said := up.of('message').filter(it['text'] or { json2.Any('') }.str().contains('failed retrieving'))
2092 assert said.len == 0
2093}
2094
2095// --verbose says the mirror's 404 as it comes, even when the fallback finds
2096// the file on the next mirror: the verbose log tells a run's whole story
2097fn test_verbose_says_the_fallback_error() ! {
2098 s := fake_system('fallbackverbose')!
2099 defer { os.rmdir_all(s.tmp) or {} }
2100 s.install_local(foo('1.0-1', 'one'))!
2101 s.publish([foo('2.0-1', 'two')])!
2102 lag := s.path('lag')
2103 os.mkdir_all(lag)!
2104 os.cp(s.path('repo/core.db'), os.join_path(lag, 'core.db'))!
2105 os.cp(s.path('repo/core.files'), os.join_path(lag, 'core.files'))!
2106 saved_verbose := verbose_flag
2107 defer {
2108 verbose_flag = saved_verbose
2109 }
2110 up := s.run('', fn [s, lag] () ! {
2111 verbose_flag = true
2112 cfg_repos = [CfgRepo{
2113 name: 'core'
2114 kind: 'sync'
2115 servers: ['file://' + lag, 'file://' + s.path('repo')]
2116 }]
2117 upgrade(ConfigUpgrade{ noconfirm: true })!
2118 })!
2119 assert up.err == '', up.err
2120 assert s.installed()!['foo']! == '2.0-1'
2121 said := up.of('message').filter(it['text'] or { json2.Any('') }.str().contains('failed retrieving'))
2122 assert said.len == 1
2123 assert said[0]['text'].str().contains('from disk')
2124}
2125
2126// check is an assertion inside a run's closure, where a failed assert would
2127// leave the fake system's redirected fds behind: it fails the run instead
2128fn check(ok bool, what string) ! {
2129 if !ok {
2130 return error('check failed: ${what}')
2131 }
2132}
2133
2134fn test_targets_resolve_by_scope_version_and_provision() ! {
2135 s := fake_system('targets')!
2136 defer { os.rmdir_all(s.tmp) or {} }
2137 s.install_local(fake_pkg('app', '1.0-1', ['lib']))!
2138 s.install_local(FakePkg{
2139 ...fake_pkg('impl', '1.0-1', [])
2140 provides: ['virt=2']
2141 })!
2142 s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []), FakePkg{
2143 ...fake_pkg('simpl', '1.0-1', [])
2144 provides: ['svirt=3']
2145 }])!
2146 run := s.run('', fn () ! {
2147 mut ui := new_trans_ui()
2148 mut handle := init_handle(ui)!
2149 defer { handle.release() or {} }
2150 dbs := init_repos(mut handle)!
2151 local := local_pkgcache(handle)!
2152 // the scope is all the dbs, or the one named; an unknown name is an
2153 // error and never a search of everything
2154 check(scope_dbs(dbs, '')!.len == 1, 'no scope keeps every db')!
2155 check(scope_dbs(dbs, 'core')!.map(it.get_name()) == ['core'], 'core scopes to core')!
2156 if _ := scope_dbs(dbs, 'extra') {
2157 return error('an unknown repo scoped')
2158 } else {
2159 check(err.msg() == 'database not found: extra', err.msg())!
2160 }
2161 if _ := scope_dbs([], 'core') {
2162 return error('a repo was found among no dbs')
2163 }
2164 // installed: by name, by a constraint it meets, and by provision
2165 // only where the caller takes providers
2166 check(find_local_target(local, 'app', false) != none, 'app by name')!
2167 check(find_local_target(local, 'app>=1.0', false) != none, 'app by a met constraint')!
2168 check(find_local_target(local, 'app>=2', false) == none, 'app by an unmet constraint')!
2169 check(find_local_target(local, 'virt', false) == none, 'a provision without providers')!
2170 check(find_local_target(local, 'virt', true) != none, 'a provision with providers')!
2171 check(find_local_target(local, 'virt>=3', true) == none, 'a provision too old')!
2172 check(find_local_target(local, '', true) == none, 'the empty name')!
2173 check(find_local_target(local, 'ap', true) == none, 'a prefix of a name')!
2174 // sync: by name, constraint and provision; the empty name is nothing
2175 check(find_sync_target(handle, dbs, 'app', false) != none, 'sync app')!
2176 check(find_sync_target(handle, dbs, 'app>=2.0', false) != none, 'sync app>=2.0')!
2177 check(find_sync_target(handle, dbs, 'app>2.0', false) == none, 'sync app>2.0')!
2178 check(find_sync_target(handle, dbs, 'svirt', false) != none, 'sync provision')!
2179 check(find_sync_target(handle, dbs, 'svirt=4', false) == none, 'sync provision, wrong version')!
2180 check(find_sync_target(handle, dbs, '', false) == none, 'sync empty name')!
2181 check(find_sync_target(handle, []&alpm.DB{}, 'app', false) == none, 'no dbs')!
2182 // a db not for installing answers a provision only when it was
2183 // named with the target, and its usage is put back after
2184 dbs[0].set_usage(.sync | .search)!
2185 check(find_sync_target(handle, dbs, 'svirt', false) == none, 'usage without install')!
2186 check(find_sync_target(handle, dbs, 'svirt', true) != none, 'named db, usage lifted')!
2187 usage := dbs[0].get_usage() or { return error('no usage') }
2188 check(!usage.has(.install), 'the usage was put back')!
2189 // by name it is found either way: the name is asked of the db itself
2190 check(find_sync_target(handle, dbs, 'app', false) != none, 'by name whatever the usage')!
2191 })!
2192 assert run.err == '', run.err
2193}
2194
2195fn test_filters_combine_as_pacmans_query_filters() ! {
2196 s := fake_system('filters')!
2197 defer { os.rmdir_all(s.tmp) or {} }
2198 // app: explicit, in the repos, newer there. lib: a dependency app needs.
2199 // own: explicit, in no repo. loose: a dependency nothing needs, older in
2200 // the repos than installed. opt-only would need optdepends, which the
2201 // level-2 unrequired check is covered with in orphans_test
2202 s.install_local(fake_pkg('app', '1.0-1', ['lib']))!
2203 s.install_local(FakePkg{
2204 ...fake_pkg('lib', '1.0-1', [])
2205 reason: 1
2206 })!
2207 s.install_local(fake_pkg('own', '1.0-1', []))!
2208 s.install_local(FakePkg{
2209 ...fake_pkg('loose', '2.0-1', [])
2210 reason: 1
2211 })!
2212 s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []),
2213 fake_pkg('loose', '1.0-1', [])])!
2214 run := s.run('', fn () ! {
2215 mut ui := new_trans_ui()
2216 mut handle := init_handle(ui)!
2217 defer { handle.release() or {} }
2218 dbs := init_repos(mut handle)!
2219 mut local := local_pkgcache(handle)!
2220 pass := fn [mut local, dbs] (c ConfigSearch) []string {
2221 mut names := local.pkgs().filter(pkg_matches_filter(it, c, dbs)).map(it.get_name())
2222 names.sort()
2223 return names
2224 }
2225 check(pass(ConfigSearch{}) == ['app', 'lib', 'loose', 'own'], 'no filter passes all')!
2226 check(pass(ConfigSearch{ explicit: true }) == ['app', 'own'], 'explicit')!
2227 check(pass(ConfigSearch{ deps: true }) == ['lib', 'loose'], 'deps')!
2228 // the two reasons together pass nothing: no package is both
2229 check(pass(ConfigSearch{ deps: true, explicit: true }) == [], 'deps and explicit')!
2230 check(pass(ConfigSearch{ unrequired: true, unrequired_level: 1 }) == ['app', 'loose', 'own'], 'unrequired')!
2231 check(pass(ConfigSearch{ deps: true, unrequired: true, unrequired_level: 1 }) == ['loose'], 'unrequired deps')!
2232 check(pass(ConfigSearch{ foreign: true }) == ['own'], 'foreign')!
2233 check(pass(ConfigSearch{ native: true }) == ['app', 'lib', 'loose'], 'native')!
2234 check(pass(ConfigSearch{ native: true, foreign: true }) == [], 'native and foreign')!
2235 // an upgrade is a strictly newer sync version: an equal one, an
2236 // older one (loose) and a package in no repo are not
2237 check(pass(ConfigSearch{ upgrades: true }) == ['app'], 'upgrades')!
2238 check(pass(ConfigSearch{ upgrades: true, deps: true }) == [], 'upgrades among deps')!
2239 check(pass(ConfigSearch{ upgrades: true, foreign: true }) == [], 'upgrades of foreign')!
2240 // with no sync dbs to compare with, everything is foreign
2241 none_synced := local.pkgs().filter(pkg_matches_filter(it, ConfigSearch{ native: true },
2242 []&alpm.DB{}))
2243 check(none_synced.len == 0, 'native with no sync dbs')!
2244 // the filters that need no sync data never load it
2245 check(filter_sync_dbs(mut ui, mut handle, ConfigSearch{ explicit: true, unrequired: true })!.len == 0,
2246 'no sync dbs for local-only filters')!
2247 })!
2248 assert run.err == '', run.err
2249}
2250
2251fn test_search_groups_take_one_side_and_fuzzy_keeps_its_order() ! {
2252 s := fake_system('searchedges')!
2253 defer { os.rmdir_all(s.tmp) or {} }
2254 s.install_local(tool('aa'))!
2255 s.publish([tool('aa'), FakePkg{
2256 ...fake_pkg('zeditor', '1.0-1', [])
2257 desc: 'an editor'
2258 }, FakePkg{
2259 ...fake_pkg('notes', '1.0-1', [])
2260 desc: 'a small editor for notes'
2261 }, FakePkg{
2262 ...fake_pkg('editor', '1.0-1', [])
2263 desc: 'the editor'
2264 }])!
2265 // -g with both sides named would drop one of them: refused, before any
2266 // db is opened, with or without a group named
2267 for query in [[]string{}, ['tools']] {
2268 both := s.run('', fn [query] () ! {
2269 search(ConfigSearch{ local: true, remote: true, groups: true, query: query })!
2270 })!
2271 assert both.err.contains('not both at once'), both.err
2272 assert both.of('listing').len == 0 && both.of('groups').len == 0
2273 }
2274 // each side alone still answers
2275 for local in [true, false] {
2276 one := s.run('', fn [local] () ! {
2277 search(ConfigSearch{ local: local, remote: !local, groups: true, query: ['tools'] })!
2278 })!
2279 assert one.err == '', one.err
2280 assert one.of('listing').len == 1
2281 }
2282 // fuzzy: the names that match lead, best first, and a package matched
2283 // by its description alone trails them, listed once
2284 fuzzy := s.run('', fn () ! {
2285 search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, fields: 'name', query: ['editor'] })!
2286 })!
2287 assert fuzzy.err == '', fuzzy.err
2288 names := fuzzy.of('listing')[0]['entries']!.as_array().map(it.as_map()['name']!.str())
2289 assert names == ['editor', 'zeditor', 'notes'], names.str()
2290 // a term nothing is near matches nothing, and is no error
2291 none_near := s.run('', fn () ! {
2292 search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, query: ['qqqqqqqq'] })!
2293 })!
2294 assert none_near.err == ''
2295 assert none_near.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().len == 0
2296}
2297
2298fn test_info_fields_and_listing_on_real_packages() ! {
2299 s := fake_system('formatreal')!
2300 defer { os.rmdir_all(s.tmp) or {} }
2301 s.install_local(FakePkg{
2302 ...fake_pkg('app', '1.0-1', ['lib>=1', 'glibc'])
2303 provides: ['virt=2']
2304 groups: ['tools']
2305 })!
2306 s.install_local(fake_pkg('bare', '2.0-1', []))!
2307 run := s.run_ui('tty', '', fn () ! {
2308 mut ui := new_trans_ui()
2309 mut handle := init_handle(ui)!
2310 defer { handle.release() or {} }
2311 local := local_pkgcache(handle)!
2312 app := local.pkg_find('app') or { return error('no app') }
2313 bare := local.pkg_find('bare') or { return error('no bare') }
2314 // asked for by default, an empty field is left out; named on the
2315 // command line it is shown, empty
2316 fields := ['name', 'version', 'depends', 'provides', 'groups', 'url']
2317 quiet := info_fields(bare, fields, false)
2318 check(quiet.map(it.field) == ['name', 'version'], 'empty fields left out: ${quiet.map(it.field)}')!
2319 named := info_fields(bare, fields, true)
2320 check(named.map(it.field) == fields, 'named fields all shown')!
2321 check(named.filter(it.field == 'depends')[0].value == '', 'an empty value stays empty')!
2322 check(named.filter(it.field == 'depends')[0].items.len == 0, 'and has no items')!
2323 // a list field carries its items one by one, a plain one none
2324 full := info_fields(app, fields, false)
2325 check(full.map(it.field) == ['name', 'version', 'depends', 'provides', 'groups'], 'app fields: ${full.map(it.field)}')!
2326 deps := full.filter(it.field == 'depends')[0]
2327 check(deps.items == ['lib>=1', 'glibc'] && deps.value == 'lib>=1, glibc', 'depends items: ${deps}')!
2328 check(full.filter(it.field == 'name')[0].items.len == 0, 'a plain field has no items')!
2329 check(full.filter(it.field == 'provides')[0].items == ['virt=2'], 'provides items')!
2330 // no fields asked for is nothing to show, not a crash
2331 check(info_fields(app, [], true).len == 0, 'no fields')!
2332 check(info_table([]) == '', 'an empty table is no text')!
2333 // a listing: the default mode holds a value per field, the quiet one
2334 // the name alone, and a member carries its group
2335 mut l := Listing{
2336 fields: ['name', 'version', 'groups']
2337 }
2338 l.add_pkg(app, 'local')
2339 l.add_pkg(bare, 'local')
2340 check(l.entries[0].values == ['app', '1.0-1', 'tools'], 'values: ${l.entries[0].values}')!
2341 check(l.entries[1].values == ['bare', '2.0-1', ''], 'an empty value is kept in its place')!
2342 mut q := Listing{
2343 mode: .minimal
2344 fields: ['name', 'version']
2345 }
2346 q.add_pkg(app, 'local')
2347 q.add_member(bare, 'local', 'tools')
2348 check(q.entries.all(it.values.len == 0), 'quiet entries hold no values')!
2349 check(q.entries[1].group == 'tools' && q.entries[0].group == '', 'the member has its group')!
2350 // what the terminal gets: a table with '-' for the empty value, the
2351 // names alone for the quiet one, nothing at all for an empty listing
2352 l.print()
2353 println('--')
2354 q.print()
2355 println('--')
2356 Listing{
2357 fields: ['name']
2358 }.print()
2359 println('--')
2360 // a collection that failed part way shows what a quiet listing
2361 // found, and nothing of a table
2362 l.print_found()
2363 q.print_found()
2364 })!
2365 assert run.err == '', run.err
2366 parts := run.stdout.split('--\n')
2367 assert parts.len == 4, run.stdout
2368 assert parts[0].split_into_lines().map(it.fields().join(' ')) == ['app 1.0-1 tools', 'bare 2.0-1 -'], parts[0]
2369 assert parts[1] == 'app\nbare\n'
2370 assert parts[2] == ''
2371 assert parts[3] == 'app\nbare\n'
2372}
2373
2374fn test_pkgbuild_plan_gathers_every_spelling_that_wanted_a_node() ! {
2375 s := fake_system('wanted')!
2376 defer { os.rmdir_all(s.tmp) or {} }
2377 // dep 1.0 is installed, and too old for everything that asks for it
2378 s.install_local(fake_pkg('dep', '1.0-1', []))!
2379 s.publish([fake_pkg('lib', '1.0-1', [])])!
2380 mut server, base := fake_rpc(FakeRpc{
2381 pkgs: {
2382 'top': aur_pkg('top', ['a', 'b', 'dep>=2'], [])
2383 'a': aur_pkg('a', ['dep>=2', 'dep>=3'], [])
2384 'b': aur_pkg('b', ['dep>=3'], ['dep>=2'])
2385 'dep': aur_pkg('dep', [], [])
2386 }
2387 })!
2388 defer { server.stop() }
2389 plan := resolve(s, base, 'top')!
2390 assert plan.map(it.info.name) == ['dep', 'a', 'b', 'top']
2391 // the node is planned once, and holds each spelling once, in the order
2392 // they were met, those that came after it was planned too
2393 assert plan[0].wanted == ['dep>=2', 'dep>=3']
2394 assert plan[1].wanted == ['a'] && plan[2].wanted == ['b'] && plan[3].wanted == []
2395 // the plan is made on the local db of this moment: with dep new enough
2396 // for everyone installed since, it is planned by nobody
2397 os.rmdir_all(s.path('db/local/dep-1.0-1'))!
2398 s.install_local(fake_pkg('dep', '3.0-1', []))!
2399 again := resolve(s, base, 'top')!
2400 assert again.map(it.info.name) == ['a', 'b', 'top']
2401 // new enough for some and not for all, it is still planned, and wanted
2402 // by the one spelling it does not meet: a spelling that is met already
2403 // plans nothing and is not held
2404 os.rmdir_all(s.path('db/local/dep-3.0-1'))!
2405 s.install_local(fake_pkg('dep', '2.0-1', []))!
2406 partly := resolve(s, base, 'top')!
2407 assert partly.map(it.info.name) == ['dep', 'a', 'b', 'top']
2408 assert partly[0].wanted == ['dep>=3']
2409}
2410