module main import alpm import alpm.tests.archivefixtures import alpm.tests.httpfixtures import alpm.tests.signaturefixtures import crypto.sha256 import encoding.base64 import json2 import net.http import net.urllib import os import testdb import time fn C.stat(&char, &C.stat) i32 #include #flag linux -ldl #flag linux -Wl,--export-dynamic-symbol=gpgme_new fn C.dlsym(voidptr, &char) voidptr type FrontendSignatureContext = fn (&&C.gpgme_context) u32 struct FrontendSignatureFault { mut: remaining int failures int } const frontend_signature_fault = &FrontendSignatureFault{} @[export: 'gpgme_new'] fn frontend_signature_new(context &&C.gpgme_context) u32 { mut state := unsafe { frontend_signature_fault } if state != unsafe { nil } && state.remaining > 0 { state.remaining-- state.failures++ return u32(C.GPG_ERR_ENOMEM) } symbol := C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'gpgme_new') if symbol == unsafe { nil } { return u32(C.GPG_ERR_GENERAL) } real_new := unsafe { FrontendSignatureContext(symbol) } return real_new(context) } fn test_prepare_conflict_keeps_its_error_kind_after_copying_names() ! { s := fake_system('prepare_conflict_kind')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } testdb.write_local(s.path('db'), [testdb.Pkg{ name: 'old', conflicts: ['new'] }])! s.publish([FakePkg{ name: 'new' }])! handle := alpm.initialize(s.path('root'), s.path('db'))! defer { handle.release() or { went_on('release the alpm handle', err) } } db := handle.register_syncdb('core', 0)! trans_begin(handle, .nolock)! defer { trans_cleanup(handle) } handle.add_pkg(db.get_pkg('new') or { return error('missing new package') })! trans_prepare_checked(handle) or { assert err.code() == int(alpm.Errno.conflicting_deps) assert err.msg().contains('unresolvable package conflicts:') assert err.msg().contains('new and old are in conflict') return } assert false, 'the conflicting transaction was accepted' } #include fn C.__fpurge(stream &C.FILE) fn C.clearerr(stream &C.FILE) // the modes that commit a transaction, run whole under --ui ipc against a // system that lives in a temp dir: a root, a local db, a sync repo served // over file:// with real package archives, and a cache. libalpm does every // step for real — download, validation, extraction, db writes — and the // events the mode sends are read back line by line, as a frontend reads them // FakePkg is a package of the fake system: its files are paths under the // root with their content struct FakePkg { name string version string = '1.0-1' reason int // installed ones: 0 explicit, 1 a dependency depends []string provides []string groups []string desc string // changelog is the text the package carries as its changelog, if any changelog string files map[string]string } // FakeSystem is the temp dir a run's whole system lives in struct FakeSystem { tmp string } fn fake_system(name string) !FakeSystem { tmp := os.join_path(os.vtmp_dir(), 'vpac_test_frontend_${name}_${os.getpid()}') os.rmdir_all(tmp) or {} // pkgbuild is the build dir the runs point pkgbuild_dir at: it is there, // empty, so a mode that lists the builds reads a dir and not an error for d in ['root', 'db/local', 'db/sync', 'cache', 'repo', 'gpg', 'build', 'dbsrc', 'pkgbuild'] { os.mkdir_all(os.join_path(tmp, d))! } os.write_file(os.join_path(tmp, 'db/local/ALPM_DB_VERSION'), '9\n')! return FakeSystem{ tmp: tmp } } fn (s FakeSystem) path(rel string) string { return os.join_path(s.tmp, rel) } // file_list is a package's filelist the way libalpm keeps one: every // directory on the way, with its slash, then the files, sorted fn file_list(files map[string]string) []string { mut set := map[string]bool{} for f, _ in files { parts := f.split('/') for i in 1 .. parts.len { set[parts[..i].join('/') + '/'] = true } set[f] = true } mut out := set.keys() out.sort() return out } // install_local puts p in the local db as installed, its files on the root fn (s FakeSystem) install_local(p FakePkg) ! { // the db entry is the shared writer's; the changelog and the files on // the root are this fake system's own testdb.write_local(s.path('db'), [ testdb.Pkg{ name: p.name version: p.version reason: p.reason depends: p.depends provides: p.provides groups: p.groups files: file_list(p.files) }, ])! if p.changelog != '' { os.write_file(s.path('db/local/${p.name}-${p.version}/changelog'), p.changelog)! } for f, content in p.files { os.mkdir_all(os.dir(s.path('root/${f}')))! os.write_file(s.path('root/${f}'), content)! } } // publish builds an archive of each package into the repo, writes the repo's // core.db naming them with their checksums, and puts that db in the sync dir // fresh, so no mode asks to update it fn (s FakeSystem) publish(pkgs []FakePkg) ! { for p in pkgs { src := s.path('build/${p.name}-${p.version}') os.mkdir_all(src)! mut info := 'pkgname = ${p.name}\npkgbase = ${p.name}\npkgver = ${p.version}\npkgdesc = ${p.name} for a test\narch = any\nsize = 0\n' for d in p.depends { info += 'depend = ${d}\n' } for v in p.provides { info += 'provides = ${v}\n' } for g in p.groups { info += 'group = ${g}\n' } if p.changelog != '' { os.write_file(os.join_path(src, '.CHANGELOG'), p.changelog)! } os.write_file(os.join_path(src, '.PKGINFO'), info)! for f, content in p.files { os.mkdir_all(os.dir(os.join_path(src, f)))! os.write_file(os.join_path(src, f), content)! } file := '${p.name}-${p.version}-any.pkg.tar' tar(s.path('repo/${file}'), src, os.ls(src)!)! text := if p.desc != '' { p.desc } else { '${p.name} for a test' } mut desc := '%FILENAME%\n${file}\n\n%NAME%\n${p.name}\n\n%VERSION%\n${p.version}\n\n%DESC%\n${text}\n\n' desc += '%CSIZE%\n${os.file_size(s.path('repo/${file}'))}\n\n%ISIZE%\n0\n\n' desc += '%SHA256SUM%\n${sha256.hexhash(os.read_file(s.path('repo/${file}'))!)}\n\n%ARCH%\nany\n\n' if p.depends.len > 0 { desc += '%DEPENDS%\n${p.depends.join('\n')}\n\n' } if p.provides.len > 0 { desc += '%PROVIDES%\n${p.provides.join('\n')}\n\n' } if p.groups.len > 0 { desc += '%GROUPS%\n${p.groups.join('\n')}\n\n' } os.mkdir_all(s.path('dbsrc/${p.name}-${p.version}'))! os.write_file(s.path('dbsrc/${p.name}-${p.version}/desc'), desc)! } tar(s.path('repo/core.db'), s.path('dbsrc'), os.ls(s.path('dbsrc'))!)! os.cp(s.path('repo/core.db'), s.path('db/sync/core.db'))! // the file db beside it, the way a repo serves one: each entry's desc and // its file list. it stays on the server until a find -y fetches it for p in pkgs { entry := s.path('filessrc/${p.name}-${p.version}') os.mkdir_all(entry)! os.cp(s.path('dbsrc/${p.name}-${p.version}/desc'), os.join_path(entry, 'desc'))! os.write_file(os.join_path(entry, 'files'), '%FILES%\n${file_list(p.files).join('\n')}\n\n')! } tar(s.path('repo/core.files'), s.path('filessrc'), os.ls(s.path('filessrc'))!)! } fn tar(out string, dir string, entries []string) ! { mut args := ['tar', '-cf', out, '-C', dir] args << entries res := os.exec(args) if res.exit_code != 0 { return error('tar failed: ${res.output}') } } // installed is the local db's name to version, read the way the next // command would read it: a fresh handle fn (s FakeSystem) installed() !map[string]string { handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! defer { handle.release() or {} } // an empty db is no packages; one that cannot be read is an error, not // 'nothing installed' (pkgcache_of tells the two apart by libalpm's errno) mut cache := local_pkgcache(handle)! mut out := map[string]string{} for p in cache.pkgs() { out[p.get_name()] = p.get_version() } return out } fn (s FakeSystem) reason_of(name string) !alpm.PackageReason { handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! defer { handle.release() or {} } return (handle.find_local_pkg(name) or { return error('${name} is not installed') }).get_reason() } // FrontendRun is what a mode sent on the channel, decoded, and the error it // returned ('' when it returned none) struct FrontendRun { events []map[string]json2.Any err string // stdout is what reached fd 1 itself, beside the channel stdout string // failed is how many targets this run reported bad, main's exit status // counting them failed int } fn (r FrontendRun) of(kind string) []map[string]json2.Any { return r.events.filter(it['type'] or { json2.Any('') }.str() == kind) } // done is the run's one done event; it fails when there is not exactly one fn (r FrontendRun) done() !map[string]json2.Any { dones := r.of('done') if dones.len != 1 { return error('${dones.len} done events in ${r.events.map(it['type'] or { json2.Any('') }.str())}') } return dones[0] } fn sorted_strs(v json2.Any) []string { mut out := v.as_array().map(it.str()) out.sort() return out } // run runs a mode on the system the way a frontend runs vpac: --ui ipc, the // events on a channel (a file here), the answers on stdin. the config is // aimed at the system — its root and dbs, its cache, its keyring dir, its // repo over file:// — and put back at its defaults after, with the ui fn (s FakeSystem) run(stdin string, mode fn () !) !FrontendRun { return s.run_ui('ipc', stdin, mode) } // run_ui is run with the ui kind given: 'tty' runs the mode as a terminal // sees it, with no channel, its output read back from fd 1 fn (s FakeSystem) run_ui(kind string, stdin string, mode fn () !) !FrontendRun { chan_path := s.path('channel') out_path := s.path('stdout') mut out_file := os.create(out_path)! saved_out := C.dup(1) if saved_out < 0 { return error('could not save stdout') } in_path := s.path('stdin') os.write_file(in_path, stdin)! mut chan_file := os.create(chan_path)! mut in_file := os.open(in_path)! saved_in := C.dup(0) if saved_in < 0 { return error('could not save stdin') } saved_kind, saved_color, saved_fd := ui_kind, color_flag, ipc_fd // a process-wide count, as main reads it at the end of its one run: each // run here starts from none, and puts the count back after saved_failed := failed_targets failed_targets = 0 defer { failed_targets = saved_failed } reset_config() root_path = s.path('root') + '/' db_path = s.path('db') + '/' cfg_cachedirs = [s.path('cache') + '/'] cfg_gpgdir = s.path('gpg') + '/' // the machine's own hooks stay out of a fake system's transactions cfg_hookdirs = []string{} // the sandbox user need not exist where the tests run download_user = '' // the pkgbuild builds are the system's own too: never the ones in the // home of whoever runs the tests, which a clean would otherwise look at pkgbuild_dir = s.path('pkgbuild') cfg_repos = [CfgRepo{ name: 'core' kind: 'sync' servers: ['file://' + s.path('repo')] }] ui_kind = kind color_flag = 'never' ipc_fd = chan_file.fd C.__fpurge(C.stdin) C.clearerr(C.stdin) C.dup2(in_file.fd, 0) C.fflush(C.stdout) C.dup2(out_file.fd, 1) mut msg := '' mode() or { msg = err.msg() } C.fflush(C.stdout) C.dup2(saved_out, 1) C.close(saved_out) out_file.close() C.dup2(saved_in, 0) C.close(saved_in) C.__fpurge(C.stdin) C.clearerr(C.stdin) ui_kind, color_flag, ipc_fd = saved_kind, saved_color, saved_fd reset_config() in_file.close() chan_file.close() mut events := []map[string]json2.Any{} for line in os.read_lines(chan_path)! { // every line is one whole json object, or the channel is broken events << json2.decode[json2.Any](line)!.as_map() } return FrontendRun{ events: events err: msg stdout: os.read_file(out_path)! failed: failed_targets } } fn (s FakeSystem) lock_left() bool { return os.exists(s.path('db/db.lck')) } fn foo(version string, content string) FakePkg { return FakePkg{ name: 'foo' version: version files: { 'usr/share/foo/hello': content } } } fn test_upgrade_ends_with_a_done_event() ! { s := fake_system('upgrade')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.publish([foo('2.0-1', 'two')])! run := s.run('', fn () ! { upgrade(ConfigUpgrade{ noconfirm: true })! })! assert run.err == '' done := run.done()! assert done['action']!.str() == 'upgraded' assert sorted_strs(done['packages']!) == ['foo'] // the listing and the go-ahead came first, the done last of them assert run.of('transaction').len == 1 assert run.of('question').len == 1 // and it happened: the new version is on the root and in the local db assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'two' assert s.installed()! == { 'foo': '2.0-1' } assert !s.lock_left() } fn test_upgrade_with_nothing_to_do_sends_no_done() ! { s := fake_system('uptodate')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.publish([foo('1.0-1', 'one')])! run := s.run('', fn () ! { upgrade(ConfigUpgrade{ noconfirm: true })! })! assert run.err == '' assert run.of('done').len == 0 assert run.of('message').any(it['text']!.str() == 'nothing to upgrade.') } fn test_install_ends_with_a_done_event() ! { s := fake_system('install')! defer { os.rmdir_all(s.tmp) or {} } s.publish([ FakePkg{ name: 'bar' depends: ['baz'] files: { 'usr/bin/bar': 'bar' } }, FakePkg{ name: 'baz' files: { 'usr/lib/libbaz': 'baz' } }, ])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['bar'] })! })! assert run.err == '' done := run.done()! assert done['action']!.str() == 'installed' // the targets: the dependency comes along, but is not one assert sorted_strs(done['packages']!) == ['bar'] assert s.installed()! == { 'bar': '1.0-1' 'baz': '1.0-1' } assert s.reason_of('bar')! == .explicit assert s.reason_of('baz')! == .depend assert os.read_file(s.path('root/usr/bin/bar'))! == 'bar' assert !s.lock_left() } fn test_remove_ends_with_a_done_event() ! { s := fake_system('remove')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! run := s.run('', fn () ! { remove(ConfigRemove{ noconfirm: true, query: ['foo'] })! })! assert run.err == '' done := run.done()! assert done['action']!.str() == 'removed' assert sorted_strs(done['packages']!) == ['foo'] assert s.installed()!.len == 0 assert !os.exists(s.path('root/usr/share/foo/hello')) assert !s.lock_left() } fn test_autoremove_ends_with_a_done_event() ! { s := fake_system('autoremove')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(FakePkg{ name: 'app' depends: ['lib'] })! s.install_local(FakePkg{ name: 'lib' reason: 1 })! s.install_local(FakePkg{ name: 'orphan' reason: 1 })! // an orphan whose own dependency becomes unneeded with it: the recurse // takes it along, and the done event names it with the rest s.install_local(FakePkg{ name: 'stray' reason: 1 depends: ['leaf'] })! s.install_local(FakePkg{ name: 'leaf' reason: 1 })! run := s.run('', fn () ! { autoremove(ConfigAutoRemove{ noconfirm: true })! })! assert run.err == '' done := run.done()! assert done['action']!.str() == 'removed' assert sorted_strs(done['packages']!) == ['leaf', 'orphan', 'stray'] // the text line of a terminal is not sent beside it assert !run.of('message').any(it['text']!.str().contains('orphaned packages')) mut left := s.installed()!.keys() left.sort() assert left == ['app', 'lib'] assert !s.lock_left() } fn test_mark_ends_with_a_done_event() ! { s := fake_system('mark')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! run := s.run('', fn () ! { mark(ConfigMark{ reason: 'd', query: ['foo'] })! })! assert run.err == '' done := run.done()! assert done['action']!.str() == 'marked' assert done['reason']!.str() == 'depend' assert sorted_strs(done['packages']!) == ['foo'] assert s.reason_of('foo')! == .depend assert !s.lock_left() } fn test_mark_preserves_legacy_md5_verification_history() ! { s := fake_system('mark_legacy_md5')! defer { os.rmdir_all(s.tmp) or { went_on('remove test root', err) } } s.install_local(foo('1.0-1', 'one'))! desc := s.path('db/local/foo-1.0-1/desc') os.write_file(desc, os.read_file(desc)! + '%VALIDATION%\nmd5\nsha256\npgp\n\n')! run := s.run('', fn () ! { mark(ConfigMark{ reason: 'd', query: ['foo'] })! })! assert run.err == '', run.err assert s.reason_of('foo')! == .depend recorded := os.read_file(desc)! assert recorded.contains('\nmd5\n') assert recorded.contains('\nsha256\n') assert recorded.contains('\npgp\n') assert !s.lock_left() } fn test_declined_transaction_sends_no_done() ! { s := fake_system('decline')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! // the frontend says no to the go-ahead, question 1 run := s.run('{"id": 1, "answer": false}\n', fn () ! { remove(ConfigRemove{ query: ['foo'] })! })! assert run.err == '' questions := run.of('question') assert questions.len == 1 assert questions[0]['question']!.str() == 'proceed' assert run.of('done').len == 0 // nothing changed, and the transaction let go of the lock assert s.installed()! == { 'foo': '1.0-1' } assert os.exists(s.path('root/usr/share/foo/hello')) assert !s.lock_left() } fn test_print_preview_sends_no_done() ! { s := fake_system('preview')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.publish([foo('2.0-1', 'two')])! run := s.run('', fn () ! { upgrade(ConfigUpgrade{ print_only: true })! })! assert run.err == '' listing := run.of('transaction') assert listing.len == 1 assert listing[0]['preview']!.bool() assert run.of('done').len == 0 assert run.of('question').len == 0 assert s.installed()! == { 'foo': '1.0-1' } assert !s.lock_left() } fn test_prepare_failure_sends_no_done_and_lets_go_of_the_lock() ! { s := fake_system('prepare')! defer { os.rmdir_all(s.tmp) or {} } // a dependency no repo has: prepare fails, and says on what s.publish([FakePkg{ name: 'needy' depends: ['nowhere'] }])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['needy'] })! })! assert run.err != '' assert run.err.contains('nowhere'), run.err assert run.of('done').len == 0 assert s.installed()!.len == 0 assert !s.lock_left() } // an empty local db is a db with no packages, not a broken one: the modes // that read it answer nothing found, as pacman does on a fresh root (the // install above runs on one too) fn test_an_empty_system_is_no_error() ! { s := fake_system('empty')! defer { os.rmdir_all(s.tmp) or {} } s.publish([foo('1.0-1', 'one')])! orphaned := s.run('', fn () ! { orphans(ConfigOrphans{})! })! assert orphaned.err == '' verified := s.run('', fn () ! { verify(ConfigVerify{})! })! assert verified.err == '' searched := s.run('', fn () ! { search(ConfigSearch{ local: true, query: ['foo'] })! })! assert searched.err == '' // a name to act on is unknown, said so, not a database failure: mark // and remove report it as the bad target it is marked := s.run('', fn () ! { mark(ConfigMark{ reason: 'd', query: ['foo'] })! })! assert marked.err == '' && marked.failed == 1 assert marked.of('error')[0]['msg']!.str().contains('unknown package') assert !s.lock_left() removed := s.run('', fn () ! { remove(ConfigRemove{ noconfirm: true, query: ['foo'] })! })! assert removed.err == '' && removed.failed == 1 assert removed.of('error')[0]['msg']!.str().contains('unknown package') assert !s.lock_left() } fn test_pkgcache_of() ! { s := fake_system('pkgcache')! defer { os.rmdir_all(s.tmp) or {} } handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! // empty: a nil list, which reads as no packages mut empty := local_pkgcache(handle)! assert empty == unsafe { nil } assert empty.pkgs().len == 0 assert empty.pkg_find('foo') == none handle.release()! s.install_local(foo('1.0-1', 'one'))! full_handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! mut full := local_pkgcache(full_handle)! assert full.pkgs().map(it.get_name()) == ['foo'] full_handle.release()! if os.geteuid() == 0 { // root reads the unreadable dir below anyway return } // a db libalpm cannot read is still an error, with libalpm's reason. the // handle opens first: libalpm reads the packages only when asked broken := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! defer { broken.release() or {} } os.chmod(s.path('db/local'), 0)! defer { os.chmod(s.path('db/local'), 0o755) or {} } if mut got := local_pkgcache(broken) { assert false, 'an unreadable local db read as ${got.pkgs().len} packages' } else { assert err.msg().starts_with('could not read the packages of local: '), err.msg() } } fn test_url_install_through_the_install_handle() ! { s := fake_system('url')! defer { os.rmdir_all(s.tmp) or {} } s.publish([foo('1.0-1', 'one')])! url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar') run := s.run('', fn [url] () ! { install(ConfigInstall{ noconfirm: true, query: [url] })! })! assert run.err == '' done := run.done()! assert done['action']!.str() == 'installed' assert sorted_strs(done['packages']!) == ['foo'] assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'one' // the trust warning is a warning to a frontend, and comes before the // download it is about, which comes before the transaction kinds := run.events.map(it['type']!.str()) warned := run.events.filter(it['type']!.str() == 'message' && it['text']!.str().contains('signature')) assert warned.len == 1 assert warned[0]['warning']!.bool() first_warning := run.events.index(warned[0]) first_download := kinds.index('download') assert first_download > first_warning assert kinds.index('transaction') > first_download assert run.of('download').any(it['file']!.str().starts_with('foo-1.0-1-any.pkg.tar')) // the archive was fetched into the cache, as libalpm fetches one assert os.exists(s.path('cache/foo-1.0-1-any.pkg.tar')) assert !s.lock_left() } fn test_url_install_refuses_a_bad_signature_beside_it() ! { s := fake_system('urlsig')! defer { os.rmdir_all(s.tmp) or {} } s.publish([foo('1.0-1', 'one')])! // the server offers a signature that does not hold: libalpm fetches it // with the archive, and the load at the remote level reads it os.write_file(s.path('repo/foo-1.0-1-any.pkg.tar.sig'), 'not a signature')! url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar') run := s.run('', fn [url] () ! { install(ConfigInstall{ noconfirm: true, query: [url] })! })! assert run.err.contains('signature'), run.err assert run.of('done').len == 0 assert s.installed()!.len == 0 assert !os.exists(s.path('root/usr/share/foo/hello')) assert !s.lock_left() } fn test_url_install_uses_the_next_cache_after_a_file_and_reports_warnings() ! { s := fake_system('url_cache_file')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } s.publish([foo('1.0-1', 'one')])! bad_cache := s.path('bad-cache') good_cache := s.path('cache') os.write_file(bad_cache, 'keep this file')! url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar') run := s.run('', fn [url, bad_cache, good_cache] () ! { cfg_cachedirs = [bad_cache, good_cache] install(ConfigInstall{ noconfirm: true, query: [url] })! })! assert run.err == '', run.err assert run.done()!['action']!.str() == 'installed' assert os.read_file(bad_cache)! == 'keep this file' assert os.exists(s.path('cache/foo-1.0-1-any.pkg.tar')) assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'one' created := run.events.filter(it['type']!.str() == 'message' && it['text']!.str().contains('cache exists, creating')) assert created.len > 0 assert created.all(it['warning']!.bool()) lookups := run.events.filter(it['type']!.str() == 'message' && it['text']!.str().contains("could not open '${bad_cache}/")) assert lookups.len > 0 assert lookups.all(it['warning']!.bool()) kinds := run.events.map(it['type']!.str()) assert kinds.index('download') > run.events.index(created[0]) assert !s.lock_left() } fn test_find_refresh_takes_the_full_handle() ! { s := fake_system('findhandle')! defer { os.rmdir_all(s.tmp) or {} } run := s.run('', fn () ! { // a sandbox user that exists wherever the test runs: this one download_user = current_user()! mut ui := new_trans_ui() refresh := find_handle(mut ui, true)! defer { refresh.release() or {} } // the refresh downloads as the sandbox user, from the file dbs if refresh.option_get_sandboxuser() != download_user { return error('a refresh downloads as "${refresh.option_get_sandboxuser()}"') } if refresh.option_get_dbext() != '.files' { return error('a refresh reads ${refresh.option_get_dbext()}') } read := find_handle(mut ui, false)! defer { read.release() or {} } if read.option_get_dbext() != '.files' { return error('a lookup reads ${read.option_get_dbext()}') } })! assert run.err == '' } fn test_find_refresh_fetches_the_file_dbs() ! { s := fake_system('findrefresh')! defer { os.rmdir_all(s.tmp) or {} } s.publish([FakePkg{ name: 'bar' files: { 'usr/bin/bar': 'bar' } }])! assert !os.exists(s.path('db/sync/core.files')) run := s.run('', fn () ! { find(ConfigFind{ refresh: true, query: ['/usr/bin/bar'] })! })! assert run.err == '' // fetched through the full handle: its progress reached the frontend assert run.of('download').any(it['file']!.str().starts_with('core.files')) assert os.exists(s.path('db/sync/core.files')) // and read: the repo package that provides the path provides := run.of('provides') assert provides.len == 1 entries := provides[0]['entries']!.as_array() assert entries.len == 1 assert entries[0].as_map()['name']!.str() == 'bar' } // verify_lines runs the fast check on the system, with the NoExtract globs // given, and returns its report: the lines, and how many packages are bad fn (s FakeSystem) verify_lines(noextract []string) !([]string, int) { run := s.run('', fn [noextract] () ! { cfg_noextract = noextract.clone() verify(ConfigVerify{})! })! if run.err != '' { return error(run.err) } events := run.of('verify') if events.len != 1 { return error('${events.len} verify events') } lines := events[0]['lines']!.as_array().map(it.as_map()['text']!.str()) return lines, events[0]['bad']!.int() } fn test_verify_fast_check_as_pacman() ! { s := fake_system('verify')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(FakePkg{ name: 'docs' files: { 'usr/bin/docs': 'docs' 'usr/share/man/man1/docs.1': 'man' 'usr/share/doc/docs/README.md': 'readme' } })! s.install_local(FakePkg{ name: 'dirs' files: { 'usr/share/dirs/a': 'a' } })! s.install_local(FakePkg{ name: 'intact' files: { 'usr/lib/intact': 'ok' } })! // a man page NoExtract kept off the disk, and a binary that is gone os.rm(s.path('root/usr/share/man/man1/docs.1'))! os.rm(s.path('root/usr/bin/docs'))! // a directory the db lists, now a link to one elsewhere: the file in it // is still reached through the link os.mkdir_all(s.path('root/usr/share/elsewhere'))! os.write_file(s.path('root/usr/share/elsewhere/a'), 'a')! os.rmdir_all(s.path('root/usr/share/dirs'))! os.symlink('elsewhere', s.path('root/usr/share/dirs'))! lines, bad := s.verify_lines(['usr/share/man/*'])! root := s.path('root') assert bad == 2, lines.str() assert 'docs: missing ${root}/usr/bin/docs' in lines assert 'dirs: ${root}/usr/share/dirs/ is a link, the db says a directory' in lines // NoExtract's file is not missing, and not said at all, as in pacman assert !lines.any(it.contains('docs.1')), lines.str() assert !lines.any(it.starts_with('intact')), lines.str() assert lines.len == 2, lines.str() // without the NoExtract glob, the man page is missing like any file lines2, bad2 := s.verify_lines([])! assert bad2 == 2 assert 'docs: missing ${root}/usr/share/man/man1/docs.1' in lines2 } fn test_verify_fast_check_lets_links_be() ! { s := fake_system('verifylinks')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(FakePkg{ name: 'linked' files: { 'usr/lib/libx.so.1': 'lib' 'usr/lib/libx.so': '' 'usr/lib/dangling': '' } })! // a package's file may be a link, to its neighbour or to nothing at all os.rm(s.path('root/usr/lib/libx.so'))! os.symlink('libx.so.1', s.path('root/usr/lib/libx.so'))! os.rm(s.path('root/usr/lib/dangling'))! os.symlink('nowhere', s.path('root/usr/lib/dangling'))! lines, bad := s.verify_lines([])! assert bad == 0, lines.str() assert lines.len == 0 } // fake_pkg is a FakePkg with no files, at a version, with its dependencies fn fake_pkg(name string, version string, depends []string) FakePkg { return FakePkg{ name: name version: version depends: depends } } fn test_install_upgrades_the_whole_outdated_closure() ! { // app needs mid, mid needs low: both installed, both outdated. the walk // is the dependency closure, not one level of it s := fake_system('closure')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })! s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })! s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']), fake_pkg('low', '2.0-1', [])])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['app'] })! })! assert run.err == '' assert s.installed()! == { 'app': '1.0-1' 'mid': '2.0-1' 'low': '2.0-1' } // what came along is still a dependency assert s.reason_of('mid')! == .depend } fn test_install_no_upgrade_deps_leaves_the_closure() ! { s := fake_system('noclosure')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })! s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })! s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']), fake_pkg('low', '2.0-1', [])])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })! })! assert run.err == '' assert s.installed()! == { 'app': '1.0-1' 'mid': '1.0-1' 'low': '1.0-1' } } fn test_install_brings_along_what_it_would_break() ! { // user needs lib below 2.0; installing lib 2.0 breaks it, so the repo's // user, which takes the new lib, comes along in the same transaction s := fake_system('broken')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))! s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })! s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['lib'] })! })! assert run.err == '' assert s.installed()! == { 'lib': '2.0-1' 'user': '2.0-1' } // the transaction listed it before the go-ahead listing := run.of('transaction') assert listing.len == 1 } fn test_no_upgrade_deps_failure_says_what_breaks() ! { // --no-upgrade-deps keeps an installed package that needs the old lib at // its version: prepare fails on it, and the hint names the cause s := fake_system('noupbreak')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))! s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })! s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['lib'] })! })! lines := run.err.split('\n') assert lines[0] == 'could not satisfy dependencies:', run.err assert lines[1] == " lib breaks dependency 'lib<2.0' required by user", run.err assert lines[2].starts_with('without --no-upgrade-deps, the installed packages this breaks are upgraded along'), run.err assert s.installed()!['lib']! == '1.0-1' assert !s.lock_left() } fn test_no_upgrade_deps_still_takes_a_newer_dependency() ! { // a target that needs a newer dependency than is installed gets it even // under --no-upgrade-deps: libalpm's prepare pulls it in, which is why // the hint never blames this case s := fake_system('noupnewer')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })! s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('app', '1.0-1', ['lib>=2.0'])])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })! })! assert run.err == '' assert s.installed()! == { 'app': '1.0-1' 'lib': '2.0-1' } } fn test_mark_failure_names_what_was_set() ! { if os.geteuid() == 0 { // root writes the read-only desc below anyway return } s := fake_system('markfail')! defer { os.rmdir_all(s.tmp) or {} } for name in ['aa', 'bb', 'cc'] { s.install_local(fake_pkg(name, '1.0-1', []))! } // bb's db entry cannot be written: its reason cannot change os.chmod(s.path('db/local/bb-1.0-1/desc'), 0o444)! run := s.run('', fn () ! { mark(ConfigMark{ reason: 'd', query: ['aa', 'bb', 'cc'] })! })! assert run.err.starts_with('could not set the install reason of bb: '), run.err assert run.err.ends_with(' (already set: aa)'), run.err assert run.of('done').len == 0 // what the error says is what the db holds assert s.reason_of('aa')! == .depend assert s.reason_of('bb')! == .explicit assert s.reason_of('cc')! == .explicit assert !s.lock_left() } fn test_provider_question_under_a_frontend() ! { // app needs a shell two repo packages provide: libalpm asks which, the // frontend gets the providers as the choices, and the answer is what is // installed s := fake_system('provider')! defer { os.rmdir_all(s.tmp) or {} } s.publish([fake_pkg('app', '1.0-1', ['shell']), FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['shell'] }, FakePkg{ ...fake_pkg('dash', '1.0-1', []), provides: ['shell'] }])! // the frontend picks the second provider of question 1 run := s.run('{"id": 1, "answer": 1}\n{"id": 2, "answer": true}\n', fn () ! { install(ConfigInstall{ query: ['app'] })! })! assert run.err == '' questions := run.of('question') assert questions.len == 2 assert questions[0]['question']!.str() == 'choose' assert questions[0]['msg']!.str() == '2 providers for shell' choices := questions[0]['choices']!.as_array().map(it.str()) assert choices.len == 2 assert choices.all(it.starts_with('core/') && it.ends_with(' 1.0-1')) chosen := choices[1].all_after('/').all_before(' ') assert questions[1]['question']!.str() == 'proceed' installed := s.installed()! assert chosen in installed && installed.len == 2, installed.str() assert 'app' in installed } fn test_provider_rows_number_the_choices() ! { s := fake_system('providerrows')! defer { os.rmdir_all(s.tmp) or {} } s.publish([fake_pkg('bash', '1.0-1', []), fake_pkg('dash', '2.0-1', [])])! run := s.run('', fn () ! { mut handle := init_handle(new_trans_ui())! defer { handle.release() or {} } dbs := init_repos(mut handle)! bash := dbs[0].get_pkg('bash') or { return error('no bash') } dash := dbs[0].get_pkg('dash') or { return error('no dash') } if provider_choice(dash) != 'core/dash 2.0-1' { return error('choice ${provider_choice(dash)}') } text := table_text(provider_rows([bash, dash]), '', ' ') if text.split('\n').map(it.trim_space()) != ['1) core/bash 1.0-1', '2) core/dash 2.0-1'] { return error('rows ${text}') } })! assert run.err == '' } fn test_fuzzy_search_lists_name_matches_then_desc_matches_once() ! { s := fake_system('fuzzy')! defer { os.rmdir_all(s.tmp) or {} } s.publish([FakePkg{ ...fake_pkg('zsh', '1.0-1', []) desc: 'zsh is the z shell' }, FakePkg{ ...fake_pkg('fish', '1.0-1', []) desc: 'a friendly shell, much like zsh' }, FakePkg{ ...fake_pkg('bash', '1.0-1', []) desc: 'the gnu bourne again shell' }, FakePkg{ ...fake_pkg('zsh-doc', '1.0-1', []) desc: 'documentation' }])! run := s.run('', fn () ! { mut handle := init_handle(new_trans_ui())! defer { handle.release() or {} } dbs := init_repos(mut handle)! mut cache := pkgcache_of(handle, dbs[0])! got := build_matches(cache.pkgs(), ConfigSearch{ fuzzy: true thold: 0.9 query: ['zsh'] }).map(it.get_name()) // zsh by its name (and not again for its desc), then fish by its desc; // bash matches neither, and zsh-doc's name is too far at this threshold if got != ['zsh', 'fish'] { return error('matched ${got}') } })! assert run.err == '' } // with_file_dbs publishes the packages with their file db already synced, // as a find without -y reads it fn with_file_dbs(name string, pkgs []FakePkg) !FakeSystem { s := fake_system(name)! s.publish(pkgs)! os.cp(s.path('repo/core.files'), s.path('db/sync/core.files'))! return s } // providers_of maps each path a find answered to the packages it named fn providers_of(run FrontendRun) map[string][]string { mut out := map[string][]string{} for e in run.of('provides') { mut names := e['entries']!.as_array().map(it.as_map()['name']!.str()) names.sort() out[e['path']!.str()] = names } return out } fn test_find_owner_index_answers_as_the_walk() ! { s := with_file_dbs('findowner', [ FakePkg{ name: 'bar' files: { 'usr/bin/bar': 'bar' } }, FakePkg{ name: 'baz' files: { 'usr/bin/baz': 'baz' 'usr/lib/libbaz': 'lib' } }, ])! defer { os.rmdir_all(s.tmp) or {} } paths := ['/usr/bin/bar', 'usr/lib/libbaz', '/usr/bin/', '/usr/bin', '/nope'] // several paths at once go through the index many := s.run('', fn [paths] () ! { find(ConfigFind{ query: paths })! })! got := providers_of(many) assert got['/usr/bin/bar']! == ['bar'] assert got['usr/lib/libbaz']! == ['baz'] // a directory is every package's that carries it, with or without its slash assert got['/usr/bin/']! == ['bar', 'baz'] assert got['/usr/bin']! == ['bar', 'baz'] // the miss is named, as a target error, and counted misses := many.of('error').filter(it['target']!.bool()) assert misses.len == 1 assert misses[0]['msg']!.str() == 'no package provides /nope' // one path at a time walks the filelists: the same answers for p in paths { one := s.run('', fn [p] () ! { find(ConfigFind{ query: [p] })! })! assert providers_of(one)[p] or { []string{} } == got[p] or { []string{} }, p } } fn test_find_list_names_its_misses() ! { s := with_file_dbs('findlist', [FakePkg{ name: 'bar' files: { 'usr/bin/bar': 'bar' } }])! defer { os.rmdir_all(s.tmp) or {} } run := s.run('', fn () ! { find(ConfigFind{ list: true, query: ['bar', 'nothere'] })! })! lists := run.of('files') assert lists.len == 1 assert lists[0]['package']!.str() == 'bar' assert lists[0]['repo']!.str() == 'core' assert lists[0]['paths']!.as_array().map(it.str()) == ['usr/', 'usr/bin/', 'usr/bin/bar'] misses := run.of('error').filter(it['target']!.bool()) assert misses.len == 1 assert misses[0]['msg']!.str().contains('nothere') } // stale_after_update updates the sync dbs over file:// and answers what // the freshness check then calls stale fn (s FakeSystem) stale_after_update() !FrontendRun { return s.run('', fn () ! { mut handle := init_handle(new_trans_ui())! defer { handle.release() or {} } init_repos(mut handle)! update_repos(mut handle, false)! stale := stale_sync_dbs(handle) report('stale: ${stale.join(',')}') })! } fn test_sync_stamp_keeps_an_old_server_time_fresh() ! { s := fake_system('stamp')! defer { os.rmdir_all(s.tmp) or {} } s.publish([foo('1.0-1', 'one')])! // the server's db has not changed in two days: libalpm gives the copy // it downloads the server's time, so only vpac's stamp says it is current two_days_ago := time.now().unix() - 2 * sync_max_age os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)! os.rm(s.path('db/sync/core.db'))! run := s.stale_after_update()! assert run.err == '' assert os.file_last_mod_unix(s.path('db/sync/core.db')) <= two_days_ago + 1 assert os.exists(s.path('db/sync/vpac.synced')) assert run.of('message').any(it['text']!.str() == 'stale: ') } fn test_sync_stamp_that_cannot_be_written_is_said() ! { s := fake_system('stampfail')! defer { os.rmdir_all(s.tmp) or {} } s.publish([foo('1.0-1', 'one')])! two_days_ago := time.now().unix() - 2 * sync_max_age os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)! os.rm(s.path('db/sync/core.db'))! // the stamp's path leads nowhere writable: its write fails, and no stamp // is there after it (a link into a directory that does not exist) os.symlink(s.path('nowhere/vpac.synced'), s.path('db/sync/vpac.synced'))! run := s.stale_after_update()! assert run.err == '' // said, as a warning naming the stamp, and the db counts stale again — // touching the db instead would feed libalpm's If-Modified-Since a lie warned := run.of('message').filter(it['warning'] or { json2.Any(false) }.bool()) assert warned.len == 1 assert warned[0]['text']!.str().starts_with('could not write the sync stamp ${s.path('db/sync/vpac.synced')}') assert run.of('message').any(it['text']!.str() == 'stale: core') } fn test_libalpm_warnings_reach_the_frontend() ! { // installing what is installed already: libalpm says so at warning level, // through its log callback alone, as pacman prints it s := fake_system('alpmwarn')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.publish([foo('1.0-1', 'one')])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['foo'] })! })! assert run.err == '' said := run.of('message').filter(it['text']!.str() == 'foo-1.0-1 is up to date -- reinstalling') assert said.len == 1, run.of('message').str() assert said[0]['warning']!.bool() assert 'error' !in said[0] } fn test_libalpm_errors_reach_the_frontend() ! { // a corrupt mtree: libalpm's error names the file and libarchive's reason s := fake_system('alpmerror')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! res := os.exec(['sh', '-c', 'printf "#mtree\\n./a type=file\\n" | gzip | head -c 15 > "\$0"', s.path('db/local/foo-1.0-1/mtree')]) assert res.exit_code == 0, res.output run := s.run('', fn () ! { verify(ConfigVerify{ checksums_level: 2 })! })! assert run.err == '' errors := run.of('message').filter(it['error'] or { json2.Any(false) }.bool()) assert errors.len == 1, run.of('message').str() assert errors[0]['text']!.str() == 'error while reading file ${s.path('db/local/foo-1.0-1/mtree')}: truncated gzip input' assert errors[0]['warning']!.bool() } fn test_mark_and_verify_skip_what_names_nothing() ! { s := fake_system('skiptargets')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.install_local(FakePkg{ ...fake_pkg('impl', '1.0-1', []) provides: ['virt=2'] })! // a bad target is reported and counted; the good ones are still marked marked := s.run('', fn () ! { mark(ConfigMark{ reason: 'd', query: ['nope', 'foo'] })! })! assert marked.err == '' && marked.failed == 1 assert marked.of('done')[0]['packages']!.as_array().map(it.str()) == ['foo'] // verify resolves a versioned name and a provision, as pacman's -Qk // does, and names the target nothing answers checked := s.run('', fn () ! { verify(ConfigVerify{ query: ['foo>=1.0', 'virt', 'ghost'] })! })! assert checked.err == '', checked.err assert checked.failed == 1 assert target_errors(checked) == ['package "ghost" was not found'] none_there := s.run('', fn () ! { verify(ConfigVerify{ query: ['ghost'] })! })! assert none_there.err.contains('no one of the named packages'), none_there.err } fn test_tree_of_several_targets_under_a_frontend() ! { s := fake_system('tree')! defer { os.rmdir_all(s.tmp) or {} } s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])! run := s.run('', fn () ! { tree(ConfigTree{ query: ['app', 'lib', 'nope'] })! })! assert run.err == '' // each tree is its own event, every channel line one json object, and // nothing at all reaches stdout — the blank line between trees is a // terminal's frame trees := run.of('tree') assert trees.len == 2 assert trees[0]['root']!.as_map()['name']!.str() == 'app' children := trees[0]['root']!.as_map()['children']!.as_array() assert children.len == 1 && children[0].as_map()['name']!.str() == 'lib' assert trees[1]['root']!.as_map()['name']!.str() == 'lib' assert run.of('error').filter(it['target']!.bool()).len == 1 assert run.stdout == '', run.stdout } fn test_tree_leaves_the_sync_dbs_alone_until_needed() ! { // no sync db was ever fetched here, so setting them up warns that they // are not synced: a tree among installed packages never gets that far, // one that has to look past them does s := fake_system('treelazy')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(fake_pkg('app', '1.0-1', ['lib']))! s.install_local(fake_pkg('lib', '1.0-1', []))! s.install_local(fake_pkg('broken', '1.0-1', ['gone']))! stale := fn (run FrontendRun) int { return run.of('message').filter(it['text'] or { json2.Any('') }.str().contains('not synced')).len } for query in [['app'], ['local/app', 'lib'], ['lib']] { local := s.run('', fn [query] () ! { tree(ConfigTree{ query: query })! })! assert local.err == '', local.err assert local.of('tree').len == query.len assert stale(local) == 0, '${query}: ${local.of('message')}' } // the reverse tree reads the installed packages alone, too reverse := s.run('', fn () ! { tree(ConfigTree{ reverse: true, query: ['lib'] })! })! assert reverse.of('tree').len == 1 && stale(reverse) == 0 // a target that is not installed, and a dependency nothing installed // answers, each reach for the sync dbs — once, however many ask for query in [['nowhere'], ['broken'], ['broken', 'nowhere', 'core/x']] { past := s.run('', fn [query] () ! { tree(ConfigTree{ query: query })! })! assert stale(past) == 1, '${query}: ${past.of('message')}' } // what nothing provides is still drawn, as not found broken := s.run('', fn () ! { tree(ConfigTree{ query: ['broken'] })! })! child := broken.of('tree')[0]['root']!.as_map()['children']!.as_array()[0].as_map() assert child['name']!.str() == 'gone' && !(child['found'] or { json2.Any(false) }.bool()) } fn test_tree_of_several_targets_on_a_terminal() ! { s := fake_system('treetty')! defer { os.rmdir_all(s.tmp) or {} } s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])! run := s.run_ui('tty', '', fn () ! { tree(ConfigTree{ query: ['app', 'lib'] })! })! assert run.err == '' // the terminal gets the trees on stdout, a blank line between them trees := run.stdout.split('\n\n') assert trees.len == 2, run.stdout assert trees[0].starts_with('app'), run.stdout assert trees[1].starts_with('lib'), run.stdout assert run.events.len == 0 } fn test_failed_targets_count_per_run() ! { // one run's bad targets are its own: the next run in the same process // starts from none, as each vpac process does s := with_file_dbs('failedcount', [FakePkg{ name: 'bar' files: { 'usr/bin/bar': 'bar' } }])! defer { os.rmdir_all(s.tmp) or {} } misses := s.run('', fn () ! { find(ConfigFind{ query: ['/nope', '/usr/bin/bar', '/neither'] })! })! assert misses.failed == 2 clean := s.run('', fn () ! { find(ConfigFind{ query: ['/usr/bin/bar'] })! })! assert clean.failed == 0 // and a run leaves the count of whoever called it as it found it: the // run's own is in its result, not in the global after it failed_targets = 7 defer { failed_targets = 0 } again := s.run('', fn () ! { find(ConfigFind{ query: ['/nope'] })! })! assert again.failed == 1 assert failed_targets == 7 } fn test_install_of_several_archives_is_one_transaction() ! { // what a split build hands install: its archives, as local files, which // go in together — one listing, one go-ahead, one done event s := fake_system('archives')! defer { os.rmdir_all(s.tmp) or {} } s.publish([FakePkg{ name: 'split-a' files: { 'usr/share/split/a': 'a' } }, FakePkg{ name: 'split-b' files: { 'usr/share/split/b': 'b' } }])! archives := ['split-a', 'split-b'].map(s.path('repo/${it}-1.0-1-any.pkg.tar')) run := s.run('', fn [archives] () ! { install(ConfigInstall{ noconfirm: true, query: archives })! })! assert run.err == '' assert run.of('transaction').len == 1 assert run.of('question').len == 1 done := run.done()! assert sorted_strs(done['packages']!) == ['split-a', 'split-b'] assert s.installed()! == { 'split-a': '1.0-1' 'split-b': '1.0-1' } assert os.read_file(s.path('root/usr/share/split/b'))! == 'b' } // FakeRpc answers the pkgbuild rpc's info and search requests from a set of // packages, or every request with raw when it is set struct FakeRpc { pkgs map[string]PackagePkgbuild raw string } fn (mut h FakeRpc) handle(req http.Request) http.Response { if h.raw != '' { return http.new_response(body: h.raw) } u := urllib.parse(req.url) or { return http.new_response(status: .bad_request) } mut results := []PackagePkgbuild{} if u.path == '/rpc/v5/info' { q := urllib.parse_query(u.raw_query) or { urllib.new_values() } for name in q.get_all('arg[]') { if p := h.pkgs[name] { results << p } } } else if u.path.starts_with('/rpc/v5/search/') { needle := u.path.all_after('/rpc/v5/search/') // by name, so several results come in an order a test can name mut names := h.pkgs.keys().filter(it.contains(needle)) names.sort() for name in names { results << h.pkgs[name] } } return http.new_response( body: json2.encode(PackagesPkgbuild{ count: results.len results: results type: 'multiinfo' version: 5 }) ) } // aur_pkg is a pkgbuild repo package of the fake rpc fn aur_pkg(name string, depends []string, make_depends []string) PackagePkgbuild { return PackagePkgbuild{ name: name package_base: name version: '1.0-1' depends: depends make_depends: make_depends } } // fake_rpc serves h on a free localhost port until the returned server is // stopped, and answers its base url fn fake_rpc(h FakeRpc) !(&http.Server, string) { mut server := &http.Server{ addr: '127.0.0.1:0' handler: h show_startup_message: false worker_num: 1 } spawn server.listen_and_serve() server.wait_till_running()! return server, 'http://${server.addr}' } fn test_pkgbuild_info_from_the_rpc() ! { mut server, base := fake_rpc(FakeRpc{ pkgs: { 'yay-bin': aur_pkg('yay-bin', ['pacman'], []) } })! defer { server.stop() } got := get_pkgbuild_info(base, ['yay-bin', 'nothere'])! assert got.map(it.name) == ['yay-bin'] assert got[0].depends == ['pacman'] found := get_pkgbuild_packages(base, 'yay')! assert found.map(it.name) == ['yay-bin'] // no names asks for nothing, without a request assert get_pkgbuild_info(base, [])!.len == 0 } fn test_pkgbuild_rpc_short_garbage_is_an_error() ! { // a 200 whose body is no json and shorter than the quote of it: an error // naming what came, not a panic mut server, base := fake_rpc(FakeRpc{ raw: 'oops' })! defer { server.stop() } get_pkgbuild_info(base, ['x']) or { assert err.msg().starts_with('failed to decode package info'), err.msg() assert err.msg().ends_with('(the answer begins: oops)'), err.msg() get_pkgbuild_packages(base, 'x') or { assert err.msg().ends_with('(the answer begins: oops)'), err.msg() return } assert false, 'the search took garbage' } assert false, 'the info lookup took garbage' } // resolve walks name through the fake system's local and sync dbs and the // fake rpc, as pkgbuild_install does, and answers the build plan fn resolve(s FakeSystem, base string, name string) ![]PkgbuildNode { // the closure captures by value: the plan comes out through the heap mut plan := &Plan{} run := s.run('', fn [base, name, mut plan] () ! { cfg_repos << CfgRepo{ name: 'aur' kind: 'pkgbuild' servers: [base] } mut handle := init_handle(new_trans_ui())! defer { handle.release() or {} } init_repos(mut handle)! plan.nodes << pkgbuild_plan(handle, name)! })! if run.err != '' { return error(run.err) } return plan.nodes } @[heap] struct Plan { mut: nodes []PkgbuildNode } fn test_pkgbuild_resolver_orders_the_build() ! { s := fake_system('resolver')! defer { os.rmdir_all(s.tmp) or {} } // glibc installed, lib in the repos, the rest only in the pkgbuild repo s.install_local(fake_pkg('glibc', '1.0-1', []))! s.publish([fake_pkg('lib', '1.0-1', [])])! mut server, base := fake_rpc(FakeRpc{ pkgs: { 'top': PackagePkgbuild{ ...aur_pkg('top', ['mid', 'lib', 'glibc>=1.0', 'shared'], ['tool']) check_depends: ['checker'] } 'checker': aur_pkg('checker', [], []) 'mid': aur_pkg('mid', ['leaf', 'shared'], []) 'leaf': aur_pkg('leaf', [], []) 'shared': aur_pkg('shared', [], []) 'tool': aur_pkg('tool', [], []) } })! defer { server.stop() } plan := resolve(s, base, 'top')! // dependencies first, each once (shared is reached twice), the target last // what check() needs is planned as what the build needs is assert plan.map(it.info.name) == ['leaf', 'shared', 'mid', 'tool', 'checker', 'top'] // a repo package is installed before the build that needs it; an // installed one is not touched; the site is the pkgbuild repo it came from top := plan.last() assert top.repo_deps == ['lib'] assert plan.all(it.site == base) assert plan.filter(it.info.name != 'top').all(it.repo_deps.len == 0) // every node carries what wanted it, as the dependents spelled it: the // target nothing, a node wanted twice both spellings once each wanted := fn [plan] (name string) []string { return plan.filter(it.info.name == name)[0].wanted } assert wanted('top') == [] assert wanted('mid') == ['mid'] && wanted('leaf') == ['leaf'] assert wanted('shared') == ['shared'] assert wanted('checker') == ['checker'] // a site the config spells with a trailing slash joins a clone url with // one slash all the same slashed := resolve(s, base + '/', 'leaf')! assert slashed[0].site == base } fn test_pkgbuild_resolver_refuses_cycles_and_unknowns() ! { s := fake_system('resolverbad')! defer { os.rmdir_all(s.tmp) or {} } s.publish([fake_pkg('lib', '1.0-1', [])])! mut server, base := fake_rpc(FakeRpc{ pkgs: { 'c1': aur_pkg('c1', ['c2'], []) 'c2': aur_pkg('c2', ['c1'], []) 'needy': aur_pkg('needy', ['ghost>=2'], []) } })! defer { server.stop() } resolve(s, base, 'c1') or { assert err.msg() == 'circular pkgbuild dependency: c1 is walked as its own dependency', err.msg() resolve(s, base, 'needy') or { assert err.msg() == '"ghost" is not in the repos or the pkgbuild repo', err.msg() return } assert false, 'a dependency nowhere was planned' } assert false, 'a cycle was planned' } // target_errors are the messages of the target errors a run reported fn target_errors(run FrontendRun) []string { return run.of('error').filter(it['target'] or { json2.Any(false) }.bool()).map(it['msg'] or { json2.Any('') }.str()) } fn test_install_scopes_a_target_to_its_repo() ! { s := fake_system('scope')! defer { os.rmdir_all(s.tmp) or {} } s.publish([fake_pkg('foo', '1.0-1', [])])! // a repo the config does not carry is an error, not a prefix to drop bad := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['nope/foo'] })! })! assert target_errors(bad) == ['database not found: nope'] assert s.installed()!.len == 0 // a name the repo named does not hold is not looked up anywhere else miss := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['core/nothere'] })! })! assert target_errors(miss) == ['target not found in core: nothere'] good := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['core/foo'] })! })! assert good.err == '' && good.failed == 0 assert s.installed()! == { 'foo': '1.0-1' } } fn test_install_resolves_constraints_and_providers() ! { s := fake_system('satisfier')! defer { os.rmdir_all(s.tmp) or {} } s.publish([fake_pkg('foo', '2.0-1', []), FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] }])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['foo>=2', 'sh'] })! })! assert run.err == '' && run.failed == 0, run.err assert s.installed()! == { 'foo': '2.0-1' 'bash': '1.0-1' } // a version nothing has is a miss like any other old := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['core/foo>=3'] })! })! assert target_errors(old) == ['target not found in core: foo>=3'] } fn test_install_names_every_bad_target_and_installs_nothing() ! { s := fake_system('badtargets')! defer { os.rmdir_all(s.tmp) or {} } s.publish([fake_pkg('foo', '1.0-1', [])])! run := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['zzzzzz', 'foo', 'qqqqqq'] })! })! // both misses are told, not only the first, and the good one waits assert run.err == '' assert run.failed == 2 assert target_errors(run).len == 2 assert run.of('done').len == 0 assert s.installed()!.len == 0 assert !s.lock_left() } fn tool(name string) FakePkg { return FakePkg{ ...fake_pkg(name, '1.0-1', []) groups: ['tools'] } } fn test_install_asks_which_members_of_a_group() ! { s := fake_system('groupselect')! defer { os.rmdir_all(s.tmp) or {} } s.publish([tool('aa'), tool('bb'), tool('cc')])! // the frontend picks the first and the third, then lets it go run := s.run('{"id": 1, "answer": [0, 2]}\n{"id": 2, "answer": true}\n', fn () ! { install(ConfigInstall{ query: ['tools'] })! })! assert run.err == '', run.err // the members go out as a listing, each naming its group, then the question lists := run.of('listing') assert lists.len == 1 members := lists[0]['entries']!.as_array().map(it.as_map()) assert members.map(it['name'] or { json2.Any('') }.str()) == ['aa', 'bb', 'cc'] assert members.all(it['group'] or { json2.Any('') }.str() == 'tools') questions := run.of('question') assert questions[0]['question']!.str() == 'select' assert questions[0]['preset']!.as_array().len == 3 assert s.installed()! == { 'aa': '1.0-1' 'cc': '1.0-1' } // --noconfirm takes every member left; the installed ones are not offered rest := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['tools'] })! })! assert rest.err == '' assert rest.of('listing')[0]['entries']!.as_array().len == 1 assert s.installed()!.len == 3 // nothing left: said, and no failure done := s.run('', fn () ! { install(ConfigInstall{ noconfirm: true, query: ['tools'] })! })! assert done.err == '' && done.failed == 0 assert done.of('message').any(it['text'] or { json2.Any('') }.str().contains('every member')) } fn test_needed_group_queries_deliver_skip_warnings() ! { s := fake_system('needed_group')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } s.install_local(tool('aa'))! s.publish([tool('aa'), tool('bb')])! run := s.run('', fn () ! { mut ui := new_trans_ui() defer { ui.stop() } mut handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } init_repos(mut handle)! handle.trans_init(.needed | .nolock)! defer { handle.trans_release() or { went_on('release the test transaction', err) } } dbs := handle.get_syncdbs()! mut members := dbs.find_group_pkgs('tools') defer { members.free() } check(members.pkgs().map(it.get_name()) == ['bb'], 'needed group queries skip installed members')! })! assert run.err == '' && run.failed == 0 && run.stdout == '', run.err messages := run.of('message') assert messages.len == 1, messages.str() assert messages[0]['text']!.str() == 'aa-1.0-1 is up to date -- skipping' assert messages[0]['warning']!.bool() assert !(messages[0]['error'] or { json2.Any(false) }).bool() assert run.of('question').len == 0 assert s.installed()! == { 'aa': '1.0-1' } assert !s.lock_left() } fn test_group_selection_on_a_terminal() ! { s := fake_system('groupselecttty')! defer { os.rmdir_all(s.tmp) or {} } s.publish([tool('aa'), tool('bb'), tool('cc')])! // all but the second, then the go-ahead run := s.run_ui('tty', '^2\ny\n', fn () ! { install(ConfigInstall{ query: ['tools'] })! })! assert run.err == '', run.err assert s.installed()! == { 'aa': '1.0-1' 'cc': '1.0-1' } // --print lists every member and asks nothing preview := s.run_ui('tty', '', fn () ! { install(ConfigInstall{ print_only: true, query: ['tools'] })! })! assert preview.stdout.trim_space() == 'bb-1.0-1-any.pkg.tar', preview.stdout } fn test_remove_takes_a_group_and_names_every_bad_target() ! { s := fake_system('removegroup')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(tool('aa'))! s.install_local(tool('bb'))! s.install_local(fake_pkg('keep', '1.0-1', []))! // one unknown target stops the removal, after every one is named bad := s.run('', fn () ! { remove(ConfigRemove{ noconfirm: true, query: ['zzzzzz', 'tools', 'qqqqqq'] })! })! assert bad.failed == 2 assert s.installed()!.len == 3 assert !s.lock_left() run := s.run('', fn () ! { remove(ConfigRemove{ noconfirm: true, query: ['tools'] })! })! assert run.err == '', run.err assert sorted_strs(run.done()!['packages']!) == ['aa', 'bb'] assert s.installed()! == { 'keep': '1.0-1' } } fn test_remove_unneeded_and_recursive_levels() ! { s := fake_system('removelevels')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(fake_pkg('app', '1.0-1', ['lib', 'tool']))! s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })! // tool was installed explicitly, though app needs it s.install_local(fake_pkg('tool', '1.0-1', []))! s.install_local(fake_pkg('other', '1.0-1', []))! // -u: lib stays where app needs it, other goes, and that is no failure u := s.run('', fn () ! { remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib', 'other'] })! })! assert u.err == '', u.err assert sorted_strs(u.done()!['packages']!) == ['other'] assert 'lib' in s.installed()! none_left := s.run('', fn () ! { remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib'] })! })! assert none_left.err == '' && none_left.of('done').len == 0 // a version constraint names what satisfies it // -s takes lib, a dependency; tool was asked for by name and stays one := s.run('', fn () ! { remove(ConfigRemove{ print_only: true, recursive_level: 1, query: ['app>=1'] })! })! assert one.err == '', one.err assert sorted_strs(one.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or { json2.Any('') })) == ['app', 'lib'] // -ss takes the explicitly installed dependency too two := s.run('', fn () ! { remove(ConfigRemove{ print_only: true, recursive_level: 2, query: ['app'] })! })! assert sorted_strs(two.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or { json2.Any('') })) == ['app', 'lib', 'tool'] } fn test_upgrade_downgrades_only_when_asked() ! { s := fake_system('downgrade')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('2.0-1', 'two'))! s.publish([foo('1.0-1', 'one')])! plain := s.run('', fn () ! { upgrade(ConfigUpgrade{ noconfirm: true })! })! assert plain.err == '' assert s.installed()!['foo']! == '2.0-1' down := s.run('', fn () ! { upgrade(ConfigUpgrade{ noconfirm: true, sysupgrade_level: 2 })! })! assert down.err == '', down.err assert s.installed()!['foo']! == '1.0-1' } fn test_info_changelog_and_package_files() ! { s := fake_system('changelog')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(FakePkg{ ...fake_pkg('logged', '1.0-1', []), changelog: 'first release\n' })! s.install_local(fake_pkg('silent', '1.0-1', []))! s.publish([ FakePkg{ ...fake_pkg('filed', '1.0-1', []), changelog: 'from the archive\n' }, fake_pkg('other', '2.0-1', []), ])! run := s.run('', fn () ! { info(ConfigInfo{ changelog: true, query: ['logged', 'silent'] })! })! assert run.err == '' && run.failed == 0 logs := run.of('changelog') assert logs.len == 1 assert logs[0]['package']!.str() == 'logged' assert logs[0]['text']!.str() == 'first release\n' // the one without is said, and is no failure, as in pacman assert run.of('message').any(it['text'] or { json2.Any('') }.str().contains('no changelog available for silent')) // -p: every target is a package file, and one that does not load is its // own error archives := ['filed-1.0-1', 'other-2.0-1'].map(s.path('repo/${it}-any.pkg.tar')) mut targets := archives.clone() targets << s.path('repo/nothere.pkg.tar') files := s.run('', fn [targets] () ! { info(ConfigInfo{ file: true, fields: 'name,version', query: targets })! })! infos := files.of('info') assert infos.len == 2 assert files.failed == 1 first := archives[0] log := s.run('', fn [first] () ! { info(ConfigInfo{ file: true, changelog: true, query: [first] })! })! assert log.of('changelog')[0]['text']!.str() == 'from the archive\n' tty := s.run_ui('tty', '', fn () ! { info(ConfigInfo{ changelog: true, query: ['logged'] })! })! assert tty.stdout == 'changelog for logged:\nfirst release\n', tty.stdout } fn test_info_directory_changelog_is_an_empty_stream() ! { $if !linux { return } s := fake_system('changelog_directory')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } s.install_local(fake_pkg('logged', '1.0-1', []))! // fopen accepts a directory; fread reaches its error with no bytes. os.mkdir(s.path('db/local/logged-1.0-1/changelog'))! run := s.run('', fn () ! { info(ConfigInfo{ changelog: true, query: ['logged'] })! })! assert run.err == '' && run.failed == 0, run.err logs := run.of('changelog') assert logs.len == 1, run.events.str() assert logs[0]['package']!.str() == 'logged' assert logs[0]['text']!.str() == '' assert !run.of('message').any(it['text']!.str().contains('no changelog available')) } fn test_verify_without_mtree_sends_no_library_error() ! { s := fake_system('missing_mtree')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } s.install_local(fake_pkg('old', '1.0-1', []))! run := s.run('', fn () ! { verify(ConfigVerify{ checksums_level: 2 })! })! assert run.err == '' && run.failed == 0, run.err assert !run.of('message').any(it['error'] or { json2.Any(false) }.bool()), run.events.str() reports := run.of('verify') assert reports.len == 1 lines := reports[0]['lines']!.as_array().map(it.as_map()['text']!.str()) assert lines == ['old: no mtree file'], lines.str() assert reports[0]['bad']!.int() == 0 } fn test_package_info_delivers_metadata_warnings_without_losing_the_package() ! { s := fake_system('package_metadata_warning')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } path := s.path('repo/app.pkg.tar') bytes := archivefixtures.tar_bytes([ archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\nfuture = value\npkgdesc = a description\n' }, archivefixtures.Entry{ name: 'usr/app', text: 'payload' }, ]) os.write_file_array(path, bytes)! run := s.run('', fn [path] () ! { info(ConfigInfo{ file: true, fields: 'name,version,description', query: [path] })! })! assert run.err == '' && run.failed == 0, run.err assert run.of('info').len == 1 messages := run.of('message').filter(it['text']!.str() == "app: unknown key 'future' in package description") assert messages.len == 1 assert messages[0]['warning']!.bool() assert !(messages[0]['error'] or { json2.Any(false) }).bool() assert os.read_bytes(path)! == bytes assert !s.lock_left() } fn test_package_info_preserves_metadata_and_archive_read_failure_kinds() ! { s := fake_system('package_read_errors')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } missing := s.path('repo/no-metadata.pkg.tar') truncated := s.path('repo/truncated.pkg.tar') valid := s.path('repo/valid.pkg.tar') without_info := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'usr/file', text: 'payload' }]) good := archivefixtures.tar_bytes([ archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }, archivefixtures.Entry{ name: 'usr/file', text: 'payload' }, ]) os.write_file_array(missing, without_info)! os.write_file_array(truncated, good[..1124])! os.write_file_array(valid, good)! run := s.run('', fn [missing, truncated, valid] () ! { info(ConfigInfo{ file: true, fields: 'name,version', query: [missing, truncated, valid] })! })! assert run.err == '' && run.failed == 2, run.err assert run.of('info').len == 1 errors := target_errors(run) assert errors.len == 2 assert errors[0].contains(alpm.Errno.pkg_invalid.strerror()) assert errors[1].contains(alpm.Errno.libarchive.strerror()) messages := run.of('message').filter(it['text']!.str().starts_with('missing package metadata in ') || it['text']!.str().starts_with('error while reading package ')) assert messages.len == 2 assert messages[0]['text']!.str() == 'missing package metadata in ${missing}' assert messages[1]['text']!.str().starts_with('error while reading package ${truncated}:') assert messages.all(it['warning']!.bool() && it['error']!.bool()) assert os.read_bytes(missing)! == without_info assert os.read_bytes(truncated)! == good[..1124] assert os.read_bytes(valid)! == good assert !s.lock_left() } fn test_bad_package_mtree_falls_back_without_rejecting_the_archive() ! { s := fake_system('package_mtree_fallback')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } path := s.path('repo/app.pkg.tar') bytes := archivefixtures.tar_bytes([ archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }, archivefixtures.Entry{ name: '.MTREE', text: 'invalid mtree' }, archivefixtures.Entry{ name: 'usr/file', text: 'payload' }, ]) os.write_file_array(path, bytes)! run := s.run('', fn [path] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } pkg := handle.pkg_load(path, 1, 0)! defer { pkg.free_pkg() or { went_on('free the test package', err) } } check(handle.errno() == .libarchive, 'mtree fallback preserves the source error state')! check(pkg.get_files().names() == ['usr/file'], 'archive scan recovers the payload list')! })! assert run.err == '' && run.failed == 0, run.err assert os.read_bytes(path)! == bytes assert !s.lock_left() } fn test_raw_signature_failure_reaches_the_frontend_before_its_target_error() ! { s := fake_system('raw_signature_error')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } defer { signaturefixtures.cleanup(s.path('gpg')) or { went_on('remove the test keyring', err) } } path := s.path('repo/app.pkg.tar') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }]) os.write_file_array(path, bytes)! os.write_file(path + '.sig', '')! run := s.run('', fn [path] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } pkg := handle.pkg_load(path, 0, 0)! defer { pkg.free_pkg() or { went_on('free the test package', err) } } if result := pkg.check_pgp_signature() { result.cleanup()! return error('accepted an empty signature') } check(handle.errno() == .gpgme, 'raw signature failure retains its error kind')! target_error('signature check failed: ' + handle.errno().strerror()) })! assert run.err == '' && run.failed == 1, run.err messages := run.of('message').filter(it['text']!.str().starts_with('GPGME error:')) assert messages.len == 1 assert messages[0]['warning']!.bool() && messages[0]['error']!.bool() ordered := run.events.filter(it['type']!.str() in ['message', 'error']) assert ordered.len == 3 assert ordered[0]['type']!.str() == 'message' assert ordered[0]['text']!.str() == "Public keyring not found; have you run 'pacman-key --init'?" assert ordered[0]['warning']!.bool() && !(ordered[0]['error'] or { json2.Any(false) }).bool() assert ordered[1]['type']!.str() == 'message' assert ordered[2]['type']!.str() == 'error' assert target_errors(run) == ['signature check failed: ' + alpm.Errno.gpgme.strerror()] assert os.read_bytes(path)! == bytes assert os.read_file(path + '.sig')! == '' assert !s.lock_left() } fn test_signature_context_allocation_error_reaches_frontends_and_allows_a_retry() ! { s := fake_system('signature_context_allocation')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } ring := signaturefixtures.create(s.path('gpg'))! defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } } path := s.path('repo/app.pkg.tar') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }]) os.write_file_array(path, bytes)! ring.sign(path, [ring.fingerprint], false)! sig := os.read_bytes(path + '.sig')! run := s.run('', fn [path] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } pkg := handle.pkg_load(path, 0, 0)! defer { pkg.free_pkg() or { went_on('free the test package', err) } } mut state := unsafe { frontend_signature_fault } saved_remaining, saved_failures := state.remaining, state.failures state.remaining = 1 state.failures = 0 defer { state.remaining = saved_remaining state.failures = saved_failures } if result := pkg.check_pgp_signature() { result.cleanup()! return error('accepted the failed context allocation') } check(state.failures == 1 && handle.errno() == .gpgme, 'the context allocation failure retains the GPGME error')! target_error('signature check failed: ' + handle.errno().strerror()) result := pkg.check_pgp_signature() or { return error('signature verification did not recover') } defer { result.cleanup() or { went_on('clean up the signature result', err) } } check(handle.errno() == .ok && result.count == 1, 'retry verifies the signature')! check(unsafe { result.results[0].status == .valid && result.results[0].key.data != nil }, 'retry retains the real verification key')! })! assert run.err == '' && run.failed == 1 && run.stdout == '', run.err messages := run.of('message') assert messages.len == 1 && messages[0]['text']!.str().starts_with('GPGME error: ') assert messages[0]['text']!.str().contains('allocate memory') assert messages[0]['warning']!.bool() && messages[0]['error']!.bool() ordered := run.events.filter(it['type']!.str() in ['message', 'error']) assert ordered.map(it['type']!.str()) == ['message', 'error'] assert target_errors(run) == ['signature check failed: ' + alpm.Errno.gpgme.strerror()] assert os.read_bytes(path)! == bytes assert os.read_bytes(path + '.sig')! == sig assert !s.lock_left() } fn test_package_load_still_verifies_after_a_failed_preliminary_key_lookup() ! { s := fake_system('signature_preliminary_lookup')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } ring := signaturefixtures.create(s.path('gpg'))! defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } } path := s.path('repo/app.pkg.tar') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }]) os.write_file_array(path, bytes)! ring.sign(path, [ring.fingerprint], false)! sig := os.read_bytes(path + '.sig')! for tampered in [false, true] { mut content := bytes.clone() if tampered { content[512 + 'pkgname = '.len] = 'b'[0] } os.write_file_array(path, content)! run := s.run('', fn [path, tampered] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } mut state := unsafe { frontend_signature_fault } saved_remaining, saved_failures := state.remaining, state.failures state.remaining = 1 state.failures = 0 defer { state.remaining = saved_remaining state.failures = saved_failures } if pkg := handle.pkg_load(path, 1, 9) { defer { pkg.free_pkg() or { went_on('free the test package', err) } } check(!tampered && handle.errno() == .ok, 'valid package survives the advisory lookup failure')! check(pkg.get_name() == 'app' && pkg.get_validation() == .signature, 'package loading performed signature verification')! } else { check(tampered && handle.errno() == .pkg_invalid_sig, 'final verification rejects the tampered package')! target_error('package signature rejected: ' + handle.errno().strerror()) } check(state.failures == 1, 'the preliminary key lookup allocation failed exactly once')! })! assert run.err == '' && run.stdout == '', run.err assert run.failed == if tampered { 1 } else { 0 } assert run.of('message').all(!it['text']!.str().contains('allocate memory')) assert run.of('question').len == 0 if !tampered { assert run.of('message').len == 0 && run.of('error').len == 0 } assert os.read_bytes(path)! == content assert os.read_bytes(path + '.sig')! == sig assert !s.lock_left() } } fn test_missing_keyring_warns_frontends_once_across_repeated_signature_checks() ! { s := fake_system('signature_initialization_warning')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } defer { signaturefixtures.cleanup(s.path('gpg')) or { went_on('remove the test keyring', err) } } signer := signaturefixtures.create(s.path('signer'))! defer { signaturefixtures.cleanup(signer.path) or { went_on('remove the signing keyring', err) } } path := s.path('repo/app.pkg.tar') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }]) os.write_file_array(path, bytes)! signer.sign(path, [signer.fingerprint], false)! sig := os.read_bytes(path + '.sig')! run := s.run('', fn [path] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } pkg := handle.pkg_load(path, 0, 0)! defer { pkg.free_pkg() or { went_on('free the test package', err) } } for attempt in 0 .. 2 { result := pkg.check_pgp_signature() or { return error('could not inspect the unknown-key signature') } defer { result.cleanup() or { went_on('clean up the signature result', err) } } check(handle.errno() == if attempt == 0 { alpm.Errno.not_a_file } else { alpm.Errno.ok }, 'keyring warning retains the source error state')! check(result.count == 1 && unsafe { result.results[0].status == .key_unknown }, 'missing key is reported without importing it')! } })! assert run.err == '' && run.failed == 0 && run.stdout == '', run.err messages := run.of('message') assert messages.len == 1 assert messages[0]['text']!.str() == "Public keyring not found; have you run 'pacman-key --init'?" assert messages[0]['warning']!.bool() && !(messages[0]['error'] or { json2.Any(false) }).bool() assert run.of('question').len == 0 assert os.read_bytes(path)! == bytes assert os.read_bytes(path + '.sig')! == sig assert !s.lock_left() } fn test_modern_keybox_verifies_without_a_false_missing_keyring_warning() ! { s := fake_system('signature_modern_keybox')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } ring := signaturefixtures.create(s.path('gpg'))! defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } } assert os.exists(os.join_path(ring.path, 'pubring.kbx')) assert !os.exists(os.join_path(ring.path, 'pubring.gpg')) path := s.path('repo/app.pkg.tar') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }]) os.write_file_array(path, bytes)! ring.sign(path, [ring.fingerprint], false)! sig := os.read_bytes(path + '.sig')! run := s.run('', fn [path] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } pkg := handle.pkg_load(path, 0, 0)! defer { pkg.free_pkg() or { went_on('free the test package', err) } } for _ in 0 .. 2 { result := pkg.check_pgp_signature() or { return error('could not verify with the modern keybox') } defer { result.cleanup() or { went_on('clean up the signature result', err) } } check(handle.errno() == .ok && result.count == 1, 'modern keybox verification has no stale error')! check(unsafe { result.results[0].status == .valid && result.results[0].key.data != nil }, 'modern keybox supplies the retained verification key')! } })! assert run.err == '' && run.failed == 0 && run.stdout == '', run.err assert run.of('message').len == 0 assert run.of('question').len == 0 assert os.read_bytes(path)! == bytes assert os.read_bytes(path + '.sig')! == sig assert !s.lock_left() } fn test_issuer_extraction_errors_reach_frontends_and_preserve_the_previous_errno() ! { s := fake_system('signature_issuer_errors')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } for prior in [false, true] { for unsupported in [false, true] { data := if unsupported { [u8(0xc2), 10, 3, 0, 1, 8, 0, 0, 0, 0, 0, 0] } else { [u8(0)] } identifier := if prior { 'fixture.pkg.tar\x00ignored' } else { 'fixture.pkg.tar' } run := s.run('', fn [prior, data, identifier] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } if prior { if _ := handle.register_syncdb('', 0) { return error('accepted an empty repository name') } } previous := handle.errno() if keys := handle.extract_keyid(identifier, data.data, uint(data.len)) { keys.free_inner(C.free) keys.free() return error('accepted malformed issuer data') } else { check(err.code() == int(previous), 'issuer parser failure retains the previous error code')! } check(handle.errno() == previous, 'issuer parser failure leaves the handle error state unchanged')! target_error('could not extract signature issuers') })! assert run.err == '' && run.failed == 1 && run.stdout == '', run.err messages := run.of('message') assert messages.len == 1 detail := if unsupported { 'unsupported signature format' } else { 'signature format error' } assert messages[0]['text']!.str() == 'fixture.pkg.tar: ${detail}' assert messages[0]['warning']!.bool() && messages[0]['error']!.bool() ordered := run.events.filter(it['type']!.str() in ['message', 'error']) assert ordered.len == 2 && ordered[0]['type']!.str() == 'message' && ordered[1]['type']!.str() == 'error' assert target_errors(run) == ['could not extract signature issuers'] assert !s.lock_left() } } } fn test_embedded_signature_verifies_the_recorded_file_without_a_package_cache() ! { s := fake_system('embedded_signature_no_cache')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } ring := signaturefixtures.create(s.path('verification-keys'))! defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } } path := s.path('signed.pkg.tar') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = app\npkgver = 1-1\n' }]) os.write_file_array(path, bytes)! ring.sign(path, [ring.fingerprint], false)! signature := os.read_bytes(path + '.sig')! archivefixtures.write(s.path('db/sync/metadata.db'), [archivefixtures.Entry{ name: 'app-1-1/desc', text: '%FILENAME%\nsigned.pkg.tar\n\n%PGPSIG%\n${base64.encode(signature)}\n\n' }], false)! root := s.tmp home := ring.path fingerprint := ring.fingerprint run := s.run('', fn [root, home, fingerprint] () ! { previous := os.getwd() os.chdir(root)! defer { os.chdir(previous) or { went_on('restore the test directory', err) } } mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } handle.option_set_gpgdir(home)! handle.option_set_cachedirs(unsafe { nil })! db := handle.register_syncdb('metadata', 0)! pkg := db.get_pkg('app') or { return error('missing repository package') } result := pkg.check_pgp_signature() or { return error('could not verify the recorded package file') } defer { result.cleanup() or { went_on('clean up the signature result', err) } } check(handle.errno() == .ok && result.count == 1, 'embedded signature is verified')! check(unsafe { cstring_to_vstring(result.results[0].key.fingerprint) } == fingerprint, 'signature belongs to the fixture key')! check(unsafe { result.results[0].key.data != nil }, 'signature retains the actual key data')! })! assert run.err == '' && run.failed == 0, run.err assert os.ls(s.path('cache'))!.len == 0 assert os.read_bytes(path)! == bytes assert os.read_bytes(path + '.sig')! == signature assert !s.lock_left() } fn test_database_signature_requirement_reaches_frontends() ! { s := fake_system('database_signature_requirement')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } path := s.path('db/sync/core.db') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'app-1-1/desc', text: '%DESC%\napp\n\n' }]) os.write_file_array(path, bytes)! for level in [1024, 3072] { run := s.run('', fn [level] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } db := handle.register_syncdb('core', level)! if level == 1024 { if _ := db.get_valid() { return error('accepted a missing required database signature') } check(handle.errno() == .db_invalid_sig, 'required signature keeps its failure kind')! target_error('database signature rejected: ' + handle.errno().strerror()) } else { check(db.get_valid()!, 'optional database signature may be absent')! } })! assert run.err == '', run.err assert run.failed == if level == 1024 { 1 } else { 0 } messages := run.of('message').filter(it['text']!.str() == 'core: missing required signature') assert messages.len == if level == 1024 { 1 } else { 0 } if messages.len > 0 { assert messages[0]['warning']!.bool() && messages[0]['error']!.bool() } assert run.of('question').len == 0 } assert os.read_bytes(path)! == bytes assert !os.exists(path + '.sig') assert !s.lock_left() } fn test_database_marginal_trust_policy_reports_its_reason() ! { s := fake_system('database_signature_trust')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } ring := signaturefixtures.create(s.path('verification-keys'))! defer { signaturefixtures.cleanup(ring.path) or { went_on('remove the test keyring', err) } } path := s.path('db/sync/core.db') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'app-1-1/desc', text: '%DESC%\napp\n\n' }]) os.write_file_array(path, bytes)! ring.sign(path, [ring.fingerprint], false)! ring.trust(ring.fingerprint, 4)! signature := os.read_bytes(path + '.sig')! home := ring.path for level in [1024, 5120] { run := s.run('', fn [home, level] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } handle.option_set_gpgdir(home)! db := handle.register_syncdb('core', level)! if level == 1024 { if _ := db.get_valid() { return error('accepted disallowed marginal trust') } target_error('database signature rejected: ' + handle.errno().strerror()) } else { check(db.get_valid()!, 'configured marginal trust is accepted')! } })! assert run.err == '', run.err assert run.failed == if level == 1024 { 1 } else { 0 } messages := run.of('message').filter(it['text']!.str() == 'core: signature from "Native ALPM Fixture " is marginal trust') assert messages.len == if level == 1024 { 1 } else { 0 } assert run.of('question').len == 0 } assert os.read_bytes(path)! == bytes assert os.read_bytes(path + '.sig')! == signature assert !s.lock_left() } fn test_declined_database_key_import_is_reported_without_importing_the_key() ! { s := fake_system('database_key_decline')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } signer := signaturefixtures.create(s.path('signer-keys'))! defer { signaturefixtures.cleanup(signer.path) or { went_on('remove the signing keyring', err) } } verifier := signaturefixtures.empty(s.path('verification-keys'))! defer { signaturefixtures.cleanup(verifier.path) or { went_on('remove the verification keyring', err) } } path := s.path('db/sync/core.db') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'app-1-1/desc', text: '%DESC%\napp\n\n' }]) os.write_file_array(path, bytes)! signer.sign(path, [signer.fingerprint], false)! signature := os.read_bytes(path + '.sig')! home := verifier.path run := s.run('{"id": 1, "answer": false}\n', fn [home] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } handle.option_set_gpgdir(home)! db := handle.register_syncdb('core', 1024)! if _ := db.get_valid() { return error('accepted a signature after key import was declined') } target_error('database signature rejected: ' + handle.errno().strerror()) })! assert run.err == '' && run.failed == 1, run.err questions := run.of('question') assert questions.len == 1 assert questions[0]['question']!.str() == 'confirm' assert questions[0]['msg']!.str().starts_with('import pgp key ') assert questions[0]['msg']!.str().contains(signer.fingerprint[signer.fingerprint.len - 16..]) messages := run.of('message').filter(it['text']!.str().starts_with('core: key "') && it['text']!.str().ends_with('" is unknown')) assert messages.len == 1 ordered := run.events.filter(it['type']!.str() in ['message', 'question', 'error']) assert ordered.map(it['type']!.str()) == ['message', 'question', 'error'] assert !verifier.gpg(['--with-colons', '--list-keys'])!.contains(signer.fingerprint) assert os.read_bytes(path)! == bytes assert os.read_bytes(path + '.sig')! == signature assert !s.lock_left() } fn missing_import_key(_ voidptr, _ httpfixtures.Request) httpfixtures.Response { return httpfixtures.Response{ body: 'info:1:0\n' headers: { 'Content-Type': 'text/plain' } } } fn test_failed_remote_key_lookup_reaches_frontends_after_the_import_question() ! { s := fake_system('database_remote_key_missing')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } signer := signaturefixtures.create(s.path('signer-keys'))! defer { signaturefixtures.cleanup(signer.path) or { went_on('remove the signing keyring', err) } } verifier := signaturefixtures.empty(s.path('verification-keys'))! defer { signaturefixtures.cleanup(verifier.path) or { went_on('remove the verification keyring', err) } } environment := httpfixtures.local_only()! defer { environment.restore() or { went_on('restore the test proxy settings', err) } } mut server := httpfixtures.start(missing_import_key, unsafe { nil })! defer { server.close() or { went_on('close the test keyserver', err) } } config := os.join_path(verifier.path, 'gpg.conf') os.write_file(config, os.read_file(config)! + 'keyserver ${server.url.replace('http://', 'hkp://')}\n')! os.write_file(os.join_path(verifier.path, 'dirmngr.conf'), 'no-use-tor\nconnect-timeout 2\nconnect-quick-timeout 2\n')! path := s.path('db/sync/core.db') bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: 'app-1-1/desc', text: '%DESC%\napp\n\n' }]) os.write_file_array(path, bytes)! signer.sign(path, [signer.fingerprint], false)! sig := os.read_bytes(path + '.sig')! home := verifier.path run := s.run('{"id": 1, "answer": true}\n', fn [home] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } handle.option_set_gpgdir(home)! db := handle.register_syncdb('core', 1024)! if _ := db.get_valid() { return error('accepted a signature without its remote key') } check(handle.errno() == .db_invalid_sig, 'missing remote key preserves the database signature error')! target_error('database signature rejected: ' + handle.errno().strerror()) })! assert run.err == '' && run.failed == 1 && run.stdout == '', run.err assert run.of('question').len == 1 messages := run.of('message') assert messages.len == 2 assert messages[0]['text']!.str() == 'core: key "${signer.fingerprint}" is unknown' assert messages[1]['text']!.str() == 'key "${signer.fingerprint}" could not be looked up remotely' assert messages.all(it['warning']!.bool() && it['error']!.bool()) ordered := run.events.filter(it['type']!.str() in ['message', 'question', 'error']) assert ordered.map(it['type']!.str()) == ['message', 'question', 'message', 'error'] requests := server.snapshot() assert requests.len == 2 && requests.all(it.path.contains('op=index')) assert requests[0].path.contains(signer.fingerprint) assert requests[1].path.contains(signer.fingerprint[signer.fingerprint.len - 8..]) assert !verifier.gpg(['--with-colons', '--list-keys'])!.contains(signer.fingerprint) assert os.read_bytes(path)! == bytes assert os.read_bytes(path + '.sig')! == sig assert !s.lock_left() } fn test_package_info_preserves_metadata_at_the_source_archive_block_boundary() ! { s := fake_system('package_metadata_block_boundary')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } path := s.path('repo/app.pkg.tar') os.write_file(path, '')! mut stat := C.stat{} assert C.stat(unsafe { &char(path.str) }, &stat) == 0 block_size := if stat.st_blksize > u64(C.BUFSIZ) { int(stat.st_blksize) } else { int(C.BUFSIZ) } prefix := 'pkgname = app\npkgver = 1-1\npkgdesc = ' text := prefix + 'x'.repeat(block_size - 512 - 10 - prefix.len) + '\x00pkgname = changed\n' bytes := archivefixtures.tar_bytes([archivefixtures.Entry{ name: '.PKGINFO', text: text }]) os.write_file_array(path, bytes)! run := s.run('', fn [path] () ! { info(ConfigInfo{ file: true, fields: 'name,version', query: [path] })! })! assert run.err == '' && run.failed == 0, run.err assert run.of('info').len == 1 mut fields := map[string]string{} for raw in run.of('info')[0]['fields']!.as_array() { field := raw.as_map() fields[field['field']!.str()] = field['value']!.str() } assert fields['name'] == 'changed' assert fields['version'] == '1-1' assert os.read_bytes(path)! == bytes assert !s.lock_left() } fn test_info_preserves_partial_metadata_and_delivers_its_warning() ! { s := fake_system('info_partial_metadata')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } s.install_local(fake_pkg('app', '1.0-1', []))! path := s.path('db/local/app-1.0-1/desc') text := '%NAME%\napp\n\n%VERSION%\n1.0-1\n\n%DESC%\nkept\n\n%REASON%\n1\n\n%FUTURE%\nignored\n\n%XDATA%\na=b\ninvalid\n\n' os.write_file(path, text)! run := s.run('', fn () ! { info(ConfigInfo{ fields: 'name,description,install_reason', query: ['local/app'] })! })! assert run.err == '' && run.failed == 0, run.err infos := run.of('info') assert infos.len == 1 mut values := map[string]string{} for raw in infos[0]['fields']!.as_array() { field := raw.as_map() values[field['field']!.str()] = field['value']!.str() } assert values['name'] == 'app' assert values['description'] == 'kept' assert values['install_reason'] == reason_to_str(.depend) messages := run.of('message').filter(it['text']!.str().contains("unknown key '%FUTURE%' in local database")) assert messages.len == 1 assert messages[0]['warning']!.bool() assert !(messages[0]['error'] or { json2.Any(false) }).bool() assert os.read_file(path)! == text assert !s.lock_left() } fn test_info_delivers_a_missing_metadata_file_error_without_writing_the_db() ! { s := fake_system('info_missing_metadata')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } s.install_local(fake_pkg('app', '1.0-1', []))! path := s.path('db/local/app-1.0-1/desc') os.rm(path)! run := s.run('', fn () ! { info(ConfigInfo{ fields: 'name,description', query: ['local/app'] })! })! assert run.err == '' && run.failed == 0, run.err assert run.of('info').len == 1 messages := run.of('message').filter(it['text']!.str().contains('could not open file ' + path + ':')) assert messages.len == 1 assert messages[0]['warning']!.bool() assert messages[0]['error']!.bool() assert !os.exists(path) assert os.is_dir(os.dir(path)) assert !s.lock_left() } fn test_info_reports_invalid_and_duplicate_local_entries() ! { s := fake_system('info_local_entries')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } s.install_local(fake_pkg('app', '1.0-1', []))! os.mkdir(s.path('db/local/broken'))! os.mkdir(s.path('db/local/app-2.0-1'))! before := os.read_file(s.path('db/local/app-1.0-1/desc'))! run := s.run('', fn () ! { info(ConfigInfo{ fields: 'name,version', query: ['local/app'] })! })! assert run.err == '' && run.failed == 0, run.err assert run.of('info').len == 1 for text in ["invalid name for database entry 'broken'", "duplicated database entry 'app'"] { messages := run.of('message').filter(it['text']!.str() == text) assert messages.len == 1, text assert messages[0]['warning']!.bool() assert messages[0]['error']!.bool() } assert os.read_file(s.path('db/local/app-1.0-1/desc'))! == before assert os.is_dir(s.path('db/local/broken')) assert os.is_dir(s.path('db/local/app-2.0-1')) assert !os.exists(s.path('db/local/app-2.0-1/desc')) assert !s.lock_left() } struct LocalCacheReadFault { path string mut: closed bool } fn local_cache_read_fault_log(context voidptr, level alpm.LogLevel, message &u8) { mut fault := unsafe { &LocalCacheReadFault(context) } if fault.closed || !level.has(.function) { return } if unsafe { cstring_to_vstring(message) } != 'loading package data for app : level=0x1\n' { return } for name in os.ls('/proc/self/fd') or { assert false, err.msg() []string{} } { actual := os.readlink('/proc/self/fd/' + name) or { continue } if actual == fault.path { assert C.close(i32(name.int())) == 0 fault.closed = true break } } assert fault.closed } fn test_local_cache_read_failure_is_reported_and_can_be_retried() ! { s := fake_system('local_cache_read_fault')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } s.install_local(fake_pkg('app', '1.0-1', []))! before := os.read_file(s.path('db/local/app-1.0-1/desc'))! mut fault := &LocalCacheReadFault{ path: s.path('db/local') } run := s.run('', fn [fault] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } handle.option_set_logcb_line(local_cache_read_fault_log, fault)! mut failed := false if _ := local_pkgcache(handle) { return error('accepted an incomplete local cache') } else { target_error(err.msg()) failed = true } check(failed, 'the failed cache was reported')! recovered := local_pkgcache(handle)! check(recovered.pkgs().len == 1, 'retry recovered the installed package')! })! assert fault.closed assert run.err == '' && run.failed == 1, run.err messages := target_errors(run).filter(it.starts_with('could not read the packages of local:')) assert messages.len == 1 assert os.read_file(s.path('db/local/app-1.0-1/desc'))! == before assert !s.lock_left() } fn test_local_database_file_reports_an_open_error_without_replacing_it() ! { s := fake_system('local_db_file')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } path := s.path('db/local') os.rmdir_all(path)! os.write_file(path, 'keep this file')! run := s.run('', fn () ! { info(ConfigInfo{ fields: 'name', query: ['local/app'] }) or { check(err.code() == int(alpm.Errno.db_open), 'initialization error kind is preserved')! return err } })! assert run.err.contains(alpm.Errno.db_open.strerror()), run.err assert run.of('info').len == 0 assert os.read_file(path)! == 'keep this file' assert !s.lock_left() } fn test_empty_database_creation_does_not_reopen_a_write_only_version_file() ! { s := fake_system('local_db_umask')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } version := s.path('db/local/ALPM_DB_VERSION') os.rm(version)! run := s.run('', fn () ! { prior := C.umask(0o444) defer { C.umask(prior) } mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } packages := local_pkgcache(handle)! check(packages.pkgs().len == 0, 'new local database is empty')! })! assert run.err == '' && run.failed == 0, run.err assert os.stat(version)!.mode & 0o777 == 0o222 os.chmod(version, 0o644)! assert os.read_file(version)! == '9\n' assert !s.lock_left() } fn test_info_accepts_the_source_unsigned_local_version_format() ! { s := fake_system('local_db_numeric_version')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } s.install_local(fake_pkg('app', '1.0-1', []))! path := s.path('db/local/ALPM_DB_VERSION') text := '-${u64(C.SIZE_MAX) - 8} trailing\n' os.write_file(path, text)! run := s.run('', fn () ! { info(ConfigInfo{ fields: 'name,version', query: ['local/app'] })! })! assert run.err == '' && run.failed == 0, run.err assert run.of('info').len == 1 assert os.read_file(path)! == text assert !s.lock_left() } fn test_repository_cache_preserves_initial_and_cached_failure_kinds() ! { s := fake_system('repo_cache_kinds')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } path := s.path('db/sync/core.db') text := '\xff\x00not-an-archive' os.write_file(path, text)! run := s.run('', fn () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } db := handle.register_syncdb('core', 0)! for kind in [alpm.Errno.db_open, .db_invalid] { if _ := pkgcache_of(handle, db) { return error('accepted a corrupt repository') } else { check(handle.errno() == kind, 'repository cache failure kind is preserved')! target_error(err.msg()) } } })! assert run.err == '' && run.failed == 2, run.err errors := target_errors(run) assert errors.len == 2 assert errors[0].contains(alpm.Errno.db_open.strerror()) assert errors[1].contains(alpm.Errno.db_invalid.strerror()) assert !errors[1].contains(alpm.Errno.db_invalid_sig.strerror()) assert run.of('message').any(it['text']!.str().starts_with('could not open file ' + path + ':')) assert os.read_file(path)! == text assert !s.lock_left() } fn test_repository_read_retry_recovers_packages_and_groups() ! { s := fake_system('repo_cache_retry')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } path := s.path('db/sync/core.db') good := archivefixtures.tar_bytes([ archivefixtures.Entry{ name: 'app-1.0-1/desc', text: '%FILENAME%\napp.pkg.tar\n\n%GROUPS%\ntools\n\n' }, archivefixtures.Entry{ name: 'next-1.0-1/desc', text: '%FILENAME%\nnext.pkg.tar\n\n' }, ]) os.write_file_array(path, good[..1124])! run := s.run('', fn [path, good] () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } db := handle.register_syncdb('core', 0)! if _ := pkgcache_of(handle, db) { return error('accepted a truncated repository') } else { check(handle.errno() == .libarchive, 'archive read failure is preserved')! target_error(err.msg()) } check(db.get_valid()!, 'header-read failure permits retry')! if _ := db.get_group('tools') { return error('accepted groups from a truncated repository') } check(handle.errno() == .libarchive, 'failed group load preserves the read error')! os.write_file_array(path, good)! recovered := pkgcache_of(handle, db)! check(recovered.pkgs().len == 2, 'retry recovered both packages')! group := db.get_group('tools') or { return error('retry hid the package group') } check(group.get_name() == 'tools', 'retry recovered the group')! })! assert run.err == '' && run.failed == 1, run.err assert target_errors(run).len == 1 assert os.read_bytes(path)! == good assert !s.lock_left() } fn test_sync_metadata_warnings_and_final_newline_reach_frontends() ! { s := fake_system('sync_metadata_warnings')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } path := s.path('db/sync/core.db') bytes := archivefixtures.tar_bytes([ archivefixtures.Entry{ name: 'app-1.0-1/desc', text: '%NAME%\nwrong\n\n%FUTURE%\nignored\n\n%DESC%\na description\n\n%GROUPS%\ntools\n' }, archivefixtures.Entry{ name: 'loose-1.0-1', text: 'ignored' }, ]) os.write_file_array(path, bytes)! run := s.run('', fn () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } db := handle.register_syncdb('core', 0)! packages := pkgcache_of(handle, db)! check(packages.pkgs().len == 2, 'both archive entries remain available')! pkg := db.get_pkg('app') or { return error('missing repository package') } check(pkg.get_desc() == 'a description', 'warning does not hide package metadata')! check(pkg.get_groups().strs() == ['tools'], 'final newline terminates a metadata list')! })! assert run.err == '' && run.failed == 0, run.err wanted := ['core database is inconsistent: name mismatch on package app', "app: unknown key '%FUTURE%' in sync database", 'unknown database file: loose-1.0-1'] messages := run.of('message').filter(it['text']!.str() in wanted) assert messages.map(it['text']!.str()) == wanted assert messages.all(it['warning']!.bool()) assert messages[0]['error']!.bool() assert !(messages[1]['error'] or { json2.Any(false) }).bool() assert !(messages[2]['error'] or { json2.Any(false) }).bool() assert os.read_bytes(path)! == bytes assert !s.lock_left() } fn test_sync_metadata_errors_report_each_bad_entry_without_a_partial_cache() ! { s := fake_system('sync_metadata_errors')! defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } } path := s.path('db/sync/core.db') bytes := archivefixtures.tar_bytes([ archivefixtures.Entry{ name: 'app-1.0-1/desc', text: '%FILENAME%\n/illegal\n\n' }, archivefixtures.Entry{ name: 'next-1.0-1/desc', text: '%VERSION%\nwrong\n\n%DATA%\ninvalid\n\n' }, archivefixtures.Entry{ name: 'last-1.0-1/desc', text: '%DESC%\nlast package\n\n' }, ]) os.write_file_array(path, bytes)! run := s.run('', fn () ! { mut ui := new_trans_ui() handle := init_handle(ui)! defer { handle.release() or { went_on('release the alpm handle', err) } } defer { ui.stop() } db := handle.register_syncdb('core', 0)! if _ := pkgcache_of(handle, db) { return error('accepted malformed metadata') } else { target_error(err.msg()) } if _ := db.get_pkgcache() { return error('retained a partial repository cache') } check(handle.errno() == .db_invalid, 'malformed metadata keeps the database invalid')! })! assert run.err == '' && run.failed == 1, run.err wanted := ['core database is inconsistent: filename of package app is illegal', "could not parse package description file 'app-1.0-1/desc' from db 'core'", 'core database is inconsistent: version mismatch on package next', "could not parse package description file 'next-1.0-1/desc' from db 'core'"] messages := run.of('message').filter(it['text']!.str() in wanted) assert messages.map(it['text']!.str()) == wanted assert messages.all(it['warning']!.bool() && it['error']!.bool()) assert target_errors(run).len == 1 assert os.read_bytes(path)! == bytes assert !s.lock_left() } fn test_info_scopes_and_satisfiers() ! { s := fake_system('infoscope')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] })! s.publish([fake_pkg('bash', '2.0-1', []), fake_pkg('zsh', '1.0-1', [])])! version_of := fn (run FrontendRun) string { for f in run.of('info')[0]['fields'] or { json2.Any([]json2.Any{}) }.as_array() { m := f.as_map() if m['field'] or { json2.Any('') }.str() == 'version' { return m['value'] or { json2.Any('') }.str() } } return '' } // bare: the installed one; core/: the repo's; a provider resolves for target, version in { 'bash': '1.0-1' 'local/bash': '1.0-1' 'core/bash': '2.0-1' 'sh': '1.0-1' 'bash>=2': '2.0-1' } { run := s.run('', fn [target] () ! { info(ConfigInfo{ noconfirm: true, query: [target] })! })! assert run.failed == 0, target assert version_of(run) == version, target } // local/ never reaches the sync dbs, and an unknown repo is an error for target, msg in { 'local/zsh': 'unknown package: "zsh"' 'nope/bash': 'database not found: nope' } { run := s.run('', fn [target] () ! { info(ConfigInfo{ noconfirm: true, query: [target] })! })! assert target_errors(run) == [msg], target } } fn test_search_local_groups_and_all_members() ! { s := fake_system('localgroups')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(tool('aa'))! s.install_local(fake_pkg('plain', '1.0-1', []))! s.publish([tool('aa'), tool('bb'), FakePkg{ ...fake_pkg('cc', '1.0-1', []) groups: [ 'extras', ] }])! names := fn (run FrontendRun) []string { return run.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().map('${it.as_map()['group'] or { json2.Any('') }.str()} ${it.as_map()['name'] or { json2.Any('') }.str()}') } // -l -g: the local db's groups, the installed members alone local := s.run('', fn () ! { search(ConfigSearch{ local: true, groups: true, query: ['tools'] })! })! assert local.err == '', local.err assert names(local) == ['tools aa'] bare := s.run('', fn () ! { search(ConfigSearch{ local: true, groups: true })! })! groups := bare.of('groups')[0]['groups']!.as_array().map(it.as_map()) assert groups.len == 1 assert groups[0]['repo']!.str() == 'local' && groups[0]['name']!.str() == 'tools' // -gg: every group of the sync dbs with its members all := s.run('', fn () ! { search(ConfigSearch{ remote: true, groups: true, groups_level: 2 })! })! mut got := names(all) got.sort() assert got == ['extras cc', 'tools aa', 'tools bb'] tty := s.run_ui('tty', '', fn () ! { search(ConfigSearch{ local: true, groups: true, groups_level: 2 })! })! assert tty.stdout == 'tools aa\n', tty.stdout // a sync-comparing filter on the sync groups: the dbs are registered // once, and only the installed member can pass native := s.run('', fn () ! { search(ConfigSearch{ remote: true, groups: true, native: true, query: ['tools'] })! })! assert native.err == '', native.err assert names(native) == ['tools aa'] // the terminal's table leads with the group, as the ipc entries carry it named := s.run_ui('tty', '', fn () ! { search(ConfigSearch{ remote: true, groups: true, fields: 'name', query: ['tools'] })! })! assert named.err == '', named.err assert named.stdout.split_into_lines().map(it.fields().join(' ')) == ['tools aa', 'tools bb'], named.stdout } fn test_owner_quiet_names_the_package_alone() ! { s := fake_system('ownerquiet')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! path := s.path('root/usr/share/foo/hello') run := s.run_ui('tty', '', fn [path] () ! { owner(ConfigOwner{ quiet: true, query: [path] })! })! assert run.err == '' assert run.stdout == 'foo\n', run.stdout } fn test_find_regex_and_machinereadable() ! { s := with_file_dbs('findregex', [ FakePkg{ name: 'bar' files: { 'usr/bin/bar': 'bar' 'usr/share/bar/x': 'x' } }, FakePkg{ name: 'baz' files: { 'usr/bin/baz': 'baz' } }, ])! defer { os.rmdir_all(s.tmp) or {} } // without a slash the expression is tried on file names, case ignored names := s.run('', fn () ! { find(ConfigFind{ regex: true, query: ['^BA.$'] })! })! assert providers_of(names)['^BA.$']! == ['bar', 'baz'] // with one, on whole paths paths := s.run('', fn () ! { find(ConfigFind{ regex: true, query: ['share/.*x$', '/usr/bin/ba[rz]'] })! })! got := providers_of(paths) assert got['share/.*x$']! == ['bar'] assert got['/usr/bin/ba[rz]']! == ['bar', 'baz'] // a bad expression is named and nothing is searched bad := s.run('', fn () ! { find(ConfigFind{ regex: true, query: ['(', 'bar'] })! })! assert target_errors(bad) == ["invalid regular expression '('"] assert bad.of('provides').len == 0 // pacman's --machinereadable: repo, package, version, path, NUL parted machine := s.run_ui('tty', '', fn () ! { find(ConfigFind{ regex: true, machinereadable: true, query: ['usr/bin/ba.'] })! })! assert machine.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\ncore\0baz\x001.0-1\0usr/bin/baz\n', machine.stdout.bytes().str() exact := s.run_ui('tty', '', fn () ! { find(ConfigFind{ machinereadable: true, query: ['/usr/bin/bar'] })! })! assert exact.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\n', exact.stdout.bytes().str() list := s.run_ui('tty', '', fn () ! { find(ConfigFind{ list: true, machinereadable: true, query: ['baz'] })! })! assert list.stdout.split('\n')[2] == 'core\0baz\x001.0-1\0usr/bin/baz', list.stdout.bytes().str() // an expression's event names the files it matched, one list a package matched := paths.of('provides').filter(it['path']!.str() == 'share/.*x$') assert matched[0]['files']!.as_array().map(it.as_array().map(it.str())) == [ ['usr/share/bar/x'], ] } fn test_find_names_slashes_and_scoped_lists() ! { s := with_file_dbs('findnames', [ FakePkg{ name: 'bar' files: { 'usr/bin/bar': 'bar' 'usr/share/bar/x': 'x' } }, FakePkg{ name: 'baz' files: { 'usr/bin/baz': 'baz' } }, ])! defer { os.rmdir_all(s.tmp) or {} } // a target with no slash is a file name: the directory usr/share/bar/ // has none, the file usr/bin/bar does name := s.run('', fn () ! { find(ConfigFind{ query: ['bar'] })! })! assert providers_of(name)['bar']! == ['bar'] assert name.of('provides')[0]['files']!.as_array().map(it.as_array().map(it.str())) == [ ['usr/bin/bar'], ] // a trailing slash on a file's path answers the same alone as among // others: the walk and the index match it the same way alone := s.run('', fn () ! { find(ConfigFind{ query: ['/usr/bin/bar/'] })! })! among := s.run('', fn () ! { find(ConfigFind{ query: ['/usr/bin/bar/', '/usr/bin/baz'] })! })! assert providers_of(alone)['/usr/bin/bar/']! == ['bar'] assert providers_of(among)['/usr/bin/bar/']! == ['bar'] // slashes alone never become the empty expression assert find_rel('//') == '/' && find_rel('/usr/bin') == 'usr/bin' && find_rel('x') == 'x' // -l takes repo/package, and lists the package before the path scoped := s.run_ui('tty', '', fn () ! { find(ConfigFind{ list: true, query: ['core/baz'] })! })! assert scoped.err == '', scoped.err assert scoped.stdout.split_into_lines().map(it.fields().join(' ')) == ['baz usr/', 'baz usr/bin/', 'baz usr/bin/baz'], scoped.stdout other := s.run('', fn () ! { find(ConfigFind{ list: true, query: ['nope/baz', 'core/'] })! })! assert other.of('files').len == 0 assert target_errors(other).len == 2 } fn test_clean_levels_and_unused_sync_dbs() ! { s := fake_system('cleandbs')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! for f in ['foo-1.0-1-any.pkg.tar.zst', 'gone-1.0-1-any.pkg.tar.zst'] { os.write_file(s.path('cache/${f}'), 'x')! } // core is configured; old is a repo the config dropped for f in ['core.db', 'core.files', 'old.db', 'old.db.sig', 'old.files', 'vpac.synced'] { os.write_file(s.path('db/sync/${f}'), 'x')! } preview := s.run('', fn () ! { clean(ConfigClean{ print_only: true })! })! assert preview.err == '', preview.err ev := preview.of('clean')[0].clone() assert ev['files']!.as_array().map(os.base(it.str())) == ['gone-1.0-1-any.pkg.tar.zst'] assert ev['dbs']!.as_array().map(os.base(it.str())) == ['old.db', 'old.db.sig', 'old.files'] // -cc is every cached package, the installed one too all := s.run('', fn () ! { clean(ConfigClean{ print_only: true, level: 2 })! })! assert all.of('clean')[0]['files']!.as_array().len == 2 run := s.run('', fn () ! { clean(ConfigClean{ noconfirm: true, level: 1 })! })! assert run.err == '', run.err mut left := os.ls(s.path('db/sync'))! left.sort() assert left == ['core.db', 'core.files', 'vpac.synced'] assert os.ls(s.path('cache'))! == ['foo-1.0-1-any.pkg.tar.zst'] } // dead_mirror aims the repo at a server that has nothing: every refresh // against it fails fn (s FakeSystem) dead_mirror() { cfg_repos = [CfgRepo{ name: 'core' kind: 'sync' servers: ['file://' + s.path('nowhere')] }] } fn test_a_failed_refresh_is_an_error() ! { s := fake_system('deadmirror')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.publish([foo('2.0-1', 'two')])! up := s.run_ui('tty', '', fn [s] () ! { s.dead_mirror() upgrade(ConfigUpgrade{ noconfirm: true, sync_dbs: true })! })! se := s.run('', fn [s] () ! { s.dead_mirror() search(ConfigSearch{ remote: true, sync_dbs: true, query: ['foo'] })! })! fy := s.run('', fn [s] () ! { s.dead_mirror() find(ConfigFind{ refresh: true, query: ['/usr/share/foo/hello'] })! })! assert up.err != '' assert se.err != '' assert fy.err != '' assert s.installed()!['foo']! == '1.0-1' // no server left to fall through to: the held 404 is said, an error said := se.of('message').filter(it['text'] or { json2.Any('') }.str().contains('failed retrieving')) assert said.len == 1 assert said[0]['error'] or { json2.Any(false) }.bool() } // --pkgbuild on an upgrade: the candidates are the locally installed // packages the sync dbs do not carry, the held and ignored ones left out, // and only a pkgbuild version the installed one does not come up to is one fn test_pkgbuild_upgrade_pass_picks_the_foreign_newer_ones() ! { s := fake_system('pkgbuildupgrade')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one')) or { return error('at install_local: ${err.msg()}') } s.install_local(FakePkg{ name: 'aurpkg' version: '1.0-1' files: { 'usr/share/aurpkg/hello': 'one' } }) or { return error('at install_local aurpkg: ${err.msg()}') } s.publish([foo('2.0-1', 'two')]) or { return error('at publish: ${err.msg()}') } mut handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/') or { return error('at initialize: ${err.msg()}') } defer { handle.release() or { went_on('release the alpm handle', err) } } cfg_repos = [CfgRepo{ name: 'core' kind: 'sync' servers: ['file://' + s.path('repo')] }] init_repos(mut handle) or { return error('at init_repos: ${err.msg()}') } // foo is the sync db's to upgrade; aurpkg the repos do not carry mut foreign := foreign_pkgs(handle) or { return error('at foreign_pkgs: ${err.msg()}') } assert foreign.map(it.get_name()) == ['aurpkg'] // the config's held packages stay out, libalpm's own ignore check handle.option_add_ignore_pkg('aurpkg') or { return error('at add_ignore: ${err.msg()}') } assert foreign_pkgs(handle)!.len == 0 handle.option_remove_ignore_pkg('aurpkg') or { return error('at remove_ignore: ${err.msg()}') } foreign = foreign_pkgs(handle) or { return error('at foreign_pkgs2: ${err.msg()}') } assert foreign.map(it.get_name()) == ['aurpkg'] // a newer record is the upgrade; the same and an older are not offered, // and a name the sync dbs carry is no candidate whatever its record says found := { 'aurpkg': PackagePkgbuild{ name: 'aurpkg', version: '1.1-1' } 'foo': PackagePkgbuild{ name: 'foo', version: '9.9-1' } } up := foreign_upgrades(foreign, found) assert up.map(it.info.name) == ['aurpkg'] for v in ['0.9-1', '1.0-1'] { assert foreign_upgrades(foreign, { 'aurpkg': PackagePkgbuild{ name: 'aurpkg', version: v } }).len == 0 } } // a build installs what it makes, so download-only refuses the pkgbuild pass // before any of the run's work, as install's does fn test_upgrade_refuses_download_only_pkgbuild() ! { s := fake_system('pkgupgdownonly')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.publish([foo('2.0-1', 'two')])! up := s.run('', fn () ! { upgrade(ConfigUpgrade{ noconfirm: false, download_only: true, pkgbuild: true })! })! assert up.err.contains('download-only does not build pkgbuild packages'), up.err // nothing of the run went ahead: the upgrade is not half-done assert s.installed()!['foo']! == '1.0-1' } // --noconfirm would skip the per-package verification a pkgbuild build // needs — makepkg runs what the PKGBUILD says — so the pass is refused // before any of the run's work, naming the way to have it anyway fn test_upgrade_refuses_noconfirm_pkgbuild() ! { s := fake_system('pkgupgnoconfirm')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.publish([foo('2.0-1', 'two')])! up := s.run('', fn () ! { upgrade(ConfigUpgrade{ noconfirm: true, pkgbuild: true })! })! assert up.err.contains('the pkgbuild upgrades are asked about'), up.err assert up.err.contains('--nopkgbuildconfirm'), up.err // the refusal is said before the sync upgrade, not after it assert s.installed()!['foo']! == '1.0-1' } // a mirror that lacks the package falls through to the next server: libalpm // tries a repo's servers in order, and a file the first one does not have // moves it on — the way a mirror that has not synced the archive yet is met. // the first server here serves the db alone, the way a lagging mirror does, // and the archive lives on the second fn test_a_mirror_without_the_package_falls_through_to_the_next() ! { s := fake_system('fallback')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.publish([foo('2.0-1', 'two')])! // the lagging mirror: the db the primary serves, none of the archives lag := s.path('lag') os.mkdir_all(lag)! os.cp(s.path('repo/core.db'), os.join_path(lag, 'core.db'))! os.cp(s.path('repo/core.files'), os.join_path(lag, 'core.files'))! up := s.run('', fn [s, lag] () ! { cfg_repos = [CfgRepo{ name: 'core' kind: 'sync' servers: ['file://' + lag, 'file://' + s.path('repo')] }] upgrade(ConfigUpgrade{ noconfirm: true })! })! assert up.err == '', up.err assert s.installed()!['foo']! == '2.0-1' // the fallback is an event a frontend sees: the archive's download says // retry, then completes retries := up.of('download').filter(it['retry'] or { json2.Any(false) }.bool()) assert retries.len == 1 assert (retries[0]['file'] or { json2.Any('') }).str() == 'foo-2.0-1-any.pkg.tar' // the 404 the lagging mirror got is not said: a mirror served the file said := up.of('message').filter(it['text'] or { json2.Any('') }.str().contains('failed retrieving')) assert said.len == 0 } // --verbose says the mirror's 404 as it comes, even when the fallback finds // the file on the next mirror: the verbose log tells a run's whole story fn test_verbose_says_the_fallback_error() ! { s := fake_system('fallbackverbose')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(foo('1.0-1', 'one'))! s.publish([foo('2.0-1', 'two')])! lag := s.path('lag') os.mkdir_all(lag)! os.cp(s.path('repo/core.db'), os.join_path(lag, 'core.db'))! os.cp(s.path('repo/core.files'), os.join_path(lag, 'core.files'))! saved_verbose := verbose_flag defer { verbose_flag = saved_verbose } up := s.run('', fn [s, lag] () ! { verbose_flag = true cfg_repos = [CfgRepo{ name: 'core' kind: 'sync' servers: ['file://' + lag, 'file://' + s.path('repo')] }] upgrade(ConfigUpgrade{ noconfirm: true })! })! assert up.err == '', up.err assert s.installed()!['foo']! == '2.0-1' said := up.of('message').filter(it['text'] or { json2.Any('') }.str().contains('failed retrieving')) assert said.len == 1 assert (said[0]['text'] or { json2.Any('') }).str().contains('from disk') } // check is an assertion inside a run's closure, where a failed assert would // leave the fake system's redirected fds behind: it fails the run instead fn check(ok bool, what string) ! { if !ok { return error('check failed: ${what}') } } fn test_targets_resolve_by_scope_version_and_provision() ! { s := fake_system('targets')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(fake_pkg('app', '1.0-1', ['lib']))! s.install_local(FakePkg{ ...fake_pkg('impl', '1.0-1', []) provides: ['virt=2'] })! s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []), FakePkg{ ...fake_pkg('simpl', '1.0-1', []) provides: ['svirt=3'] }])! run := s.run('', fn () ! { mut ui := new_trans_ui() mut handle := init_handle(ui)! defer { handle.release() or {} } dbs := init_repos(mut handle)! local := local_pkgcache(handle)! // the scope is all the dbs, or the one named; an unknown name is an // error and never a search of everything check(scope_dbs(dbs, '')!.len == 1, 'no scope keeps every db')! check(scope_dbs(dbs, 'core')!.map(it.get_name()) == ['core'], 'core scopes to core')! if _ := scope_dbs(dbs, 'extra') { return error('an unknown repo scoped') } else { check(err.msg() == 'database not found: extra', err.msg())! } if _ := scope_dbs([], 'core') { return error('a repo was found among no dbs') } // installed: by name, by a constraint it meets, and by provision // only where the caller takes providers check(find_local_target(local, 'app', false) != none, 'app by name')! check(find_local_target(local, 'app>=1.0', false) != none, 'app by a met constraint')! check(find_local_target(local, 'app>=2', false) == none, 'app by an unmet constraint')! check(find_local_target(local, 'virt', false) == none, 'a provision without providers')! check(find_local_target(local, 'virt', true) != none, 'a provision with providers')! check(find_local_target(local, 'virt>=3', true) == none, 'a provision too old')! check(find_local_target(local, '', true) == none, 'the empty name')! check(find_local_target(local, 'ap', true) == none, 'a prefix of a name')! // sync: by name, constraint and provision; the empty name is nothing check(find_sync_target(handle, dbs, 'app', false) != none, 'sync app')! check(find_sync_target(handle, dbs, 'app>=2.0', false) != none, 'sync app>=2.0')! check(find_sync_target(handle, dbs, 'app>2.0', false) == none, 'sync app>2.0')! check(find_sync_target(handle, dbs, 'svirt', false) != none, 'sync provision')! check(find_sync_target(handle, dbs, 'svirt=4', false) == none, 'sync provision, wrong version')! check(find_sync_target(handle, dbs, '', false) == none, 'sync empty name')! check(find_sync_target(handle, []&alpm.DB{}, 'app', false) == none, 'no dbs')! // a db not for installing answers a provision only when it was // named with the target, and its usage is put back after dbs[0].set_usage(.sync | .search)! check(find_sync_target(handle, dbs, 'svirt', false) == none, 'usage without install')! check(find_sync_target(handle, dbs, 'svirt', true) != none, 'named db, usage lifted')! usage := dbs[0].get_usage() or { return error('no usage') } check(!usage.has(.install), 'the usage was put back')! // by name it is found either way: the name is asked of the db itself check(find_sync_target(handle, dbs, 'app', false) != none, 'by name whatever the usage')! })! assert run.err == '', run.err } fn test_filters_combine_as_pacmans_query_filters() ! { s := fake_system('filters')! defer { os.rmdir_all(s.tmp) or {} } // app: explicit, in the repos, newer there. lib: a dependency app needs. // own: explicit, in no repo. loose: a dependency nothing needs, older in // the repos than installed. opt-only would need optdepends, which the // level-2 unrequired check is covered with in orphans_test s.install_local(fake_pkg('app', '1.0-1', ['lib']))! s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []) reason: 1 })! s.install_local(fake_pkg('own', '1.0-1', []))! s.install_local(FakePkg{ ...fake_pkg('loose', '2.0-1', []) reason: 1 })! s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []), fake_pkg('loose', '1.0-1', [])])! run := s.run('', fn () ! { mut ui := new_trans_ui() mut handle := init_handle(ui)! defer { handle.release() or {} } dbs := init_repos(mut handle)! mut local := local_pkgcache(handle)! pass := fn [mut local, dbs] (c ConfigSearch) []string { mut names := local.pkgs().filter(pkg_matches_filter(it, c, dbs)).map(it.get_name()) names.sort() return names } check(pass(ConfigSearch{}) == ['app', 'lib', 'loose', 'own'], 'no filter passes all')! check(pass(ConfigSearch{ explicit: true }) == ['app', 'own'], 'explicit')! check(pass(ConfigSearch{ deps: true }) == ['lib', 'loose'], 'deps')! // the two reasons together pass nothing: no package is both check(pass(ConfigSearch{ deps: true, explicit: true }) == [], 'deps and explicit')! check(pass(ConfigSearch{ unrequired: true, unrequired_level: 1 }) == ['app', 'loose', 'own'], 'unrequired')! check(pass(ConfigSearch{ deps: true, unrequired: true, unrequired_level: 1 }) == ['loose'], 'unrequired deps')! check(pass(ConfigSearch{ foreign: true }) == ['own'], 'foreign')! check(pass(ConfigSearch{ native: true }) == ['app', 'lib', 'loose'], 'native')! check(pass(ConfigSearch{ native: true, foreign: true }) == [], 'native and foreign')! // an upgrade is a strictly newer sync version: an equal one, an // older one (loose) and a package in no repo are not check(pass(ConfigSearch{ upgrades: true }) == ['app'], 'upgrades')! check(pass(ConfigSearch{ upgrades: true, deps: true }) == [], 'upgrades among deps')! check(pass(ConfigSearch{ upgrades: true, foreign: true }) == [], 'upgrades of foreign')! // with no sync dbs to compare with, everything is foreign none_synced := local.pkgs().filter(pkg_matches_filter(it, ConfigSearch{ native: true }, []&alpm.DB{})) check(none_synced.len == 0, 'native with no sync dbs')! // the filters that need no sync data never load it check(filter_sync_dbs(mut ui, mut handle, ConfigSearch{ explicit: true, unrequired: true })!.len == 0, 'no sync dbs for local-only filters')! })! assert run.err == '', run.err } fn test_search_groups_take_one_side_and_fuzzy_keeps_its_order() ! { s := fake_system('searchedges')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(tool('aa'))! s.publish([tool('aa'), FakePkg{ ...fake_pkg('zeditor', '1.0-1', []) desc: 'an editor' }, FakePkg{ ...fake_pkg('notes', '1.0-1', []) desc: 'a small editor for notes' }, FakePkg{ ...fake_pkg('editor', '1.0-1', []) desc: 'the editor' }])! // -g with both sides named would drop one of them: refused, before any // db is opened, with or without a group named for query in [[]string{}, ['tools']] { both := s.run('', fn [query] () ! { search(ConfigSearch{ local: true, remote: true, groups: true, query: query })! })! assert both.err.contains('not both at once'), both.err assert both.of('listing').len == 0 && both.of('groups').len == 0 } // each side alone still answers for local in [true, false] { one := s.run('', fn [local] () ! { search(ConfigSearch{ local: local, remote: !local, groups: true, query: ['tools'] })! })! assert one.err == '', one.err assert one.of('listing').len == 1 } // fuzzy: the names that match lead, best first, and a package matched // by its description alone trails them, listed once fuzzy := s.run('', fn () ! { search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, fields: 'name', query: ['editor'] })! })! assert fuzzy.err == '', fuzzy.err names := fuzzy.of('listing')[0]['entries']!.as_array().map(it.as_map()['name']!.str()) assert names == ['editor', 'zeditor', 'notes'], names.str() // a term nothing is near matches nothing, and is no error none_near := s.run('', fn () ! { search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, query: ['qqqqqqqq'] })! })! assert none_near.err == '' assert none_near.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().len == 0 } fn test_info_fields_and_listing_on_real_packages() ! { s := fake_system('formatreal')! defer { os.rmdir_all(s.tmp) or {} } s.install_local(FakePkg{ ...fake_pkg('app', '1.0-1', ['lib>=1', 'glibc']) provides: ['virt=2'] groups: ['tools'] })! s.install_local(fake_pkg('bare', '2.0-1', []))! run := s.run_ui('tty', '', fn () ! { mut ui := new_trans_ui() mut handle := init_handle(ui)! defer { handle.release() or {} } local := local_pkgcache(handle)! app := local.pkg_find('app') or { return error('no app') } bare := local.pkg_find('bare') or { return error('no bare') } // asked for by default, an empty field is left out; named on the // command line it is shown, empty fields := ['name', 'version', 'depends', 'provides', 'groups', 'url'] quiet := info_fields(bare, fields, false) check(quiet.map(it.field) == ['name', 'version'], 'empty fields left out: ${quiet.map(it.field)}')! named := info_fields(bare, fields, true) check(named.map(it.field) == fields, 'named fields all shown')! check(named.filter(it.field == 'depends')[0].value == '', 'an empty value stays empty')! check(named.filter(it.field == 'depends')[0].items.len == 0, 'and has no items')! // a list field carries its items one by one, a plain one none full := info_fields(app, fields, false) check(full.map(it.field) == ['name', 'version', 'depends', 'provides', 'groups'], 'app fields: ${full.map(it.field)}')! deps := full.filter(it.field == 'depends')[0] check(deps.items == ['lib>=1', 'glibc'] && deps.value == 'lib>=1, glibc', 'depends items: ${deps}')! check(full.filter(it.field == 'name')[0].items.len == 0, 'a plain field has no items')! check(full.filter(it.field == 'provides')[0].items == ['virt=2'], 'provides items')! // no fields asked for is nothing to show, not a crash check(info_fields(app, [], true).len == 0, 'no fields')! check(info_table([]) == '', 'an empty table is no text')! // a listing: the default mode holds a value per field, the quiet one // the name alone, and a member carries its group mut l := Listing{ fields: ['name', 'version', 'groups'] } l.add_pkg(app, 'local') l.add_pkg(bare, 'local') check(l.entries[0].values == ['app', '1.0-1', 'tools'], 'values: ${l.entries[0].values}')! check(l.entries[1].values == ['bare', '2.0-1', ''], 'an empty value is kept in its place')! mut q := Listing{ mode: .minimal fields: ['name', 'version'] } q.add_pkg(app, 'local') q.add_member(bare, 'local', 'tools') check(q.entries.all(it.values.len == 0), 'quiet entries hold no values')! check(q.entries[1].group == 'tools' && q.entries[0].group == '', 'the member has its group')! // what the terminal gets: a table with '-' for the empty value, the // names alone for the quiet one, nothing at all for an empty listing l.print() println('--') q.print() println('--') Listing{ fields: ['name'] }.print() println('--') // a collection that failed part way shows what a quiet listing // found, and nothing of a table l.print_found() q.print_found() })! assert run.err == '', run.err parts := run.stdout.split('--\n') assert parts.len == 4, run.stdout assert parts[0].split_into_lines().map(it.fields().join(' ')) == ['app 1.0-1 tools', 'bare 2.0-1 -'], parts[0] assert parts[1] == 'app\nbare\n' assert parts[2] == '' assert parts[3] == 'app\nbare\n' } fn test_pkgbuild_plan_gathers_every_spelling_that_wanted_a_node() ! { s := fake_system('wanted')! defer { os.rmdir_all(s.tmp) or {} } // dep 1.0 is installed, and too old for everything that asks for it s.install_local(fake_pkg('dep', '1.0-1', []))! s.publish([fake_pkg('lib', '1.0-1', [])])! mut server, base := fake_rpc(FakeRpc{ pkgs: { 'top': aur_pkg('top', ['a', 'b', 'dep>=2'], []) 'a': aur_pkg('a', ['dep>=2', 'dep>=3'], []) 'b': aur_pkg('b', ['dep>=3'], ['dep>=2']) 'dep': aur_pkg('dep', [], []) } })! defer { server.stop() } plan := resolve(s, base, 'top')! assert plan.map(it.info.name) == ['dep', 'a', 'b', 'top'] // the node is planned once, and holds each spelling once, in the order // they were met, those that came after it was planned too assert plan[0].wanted == ['dep>=2', 'dep>=3'] assert plan[1].wanted == ['a'] && plan[2].wanted == ['b'] && plan[3].wanted == [] // the plan is made on the local db of this moment: with dep new enough // for everyone installed since, it is planned by nobody os.rmdir_all(s.path('db/local/dep-1.0-1'))! s.install_local(fake_pkg('dep', '3.0-1', []))! again := resolve(s, base, 'top')! assert again.map(it.info.name) == ['a', 'b', 'top'] // new enough for some and not for all, it is still planned, and wanted // by the one spelling it does not meet: a spelling that is met already // plans nothing and is not held os.rmdir_all(s.path('db/local/dep-3.0-1'))! s.install_local(fake_pkg('dep', '2.0-1', []))! partly := resolve(s, base, 'top')! assert partly.map(it.info.name) == ['dep', 'a', 'b', 'top'] assert partly[0].wanted == ['dep>=3'] }