module main import alpm import crypto.sha256 import json2 import net.http import net.urllib import os import testdb import time #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_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_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_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_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() } // 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'].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'].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'] }