summaryrefslogtreecommitdiffstats
path: root/tests/common/mod.rs
blob: b598b80975c2f5a0f90750002d2be331503879df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
//! Shared test scaffolding: an isolated server root in a tempdir with a migrated
//! database and a running writer actor.

#![allow(dead_code)]

use std::path::{Path, PathBuf};

use aur_build::config::Config;
use aur_build::db::{self, Db};

pub struct Env {
    pub tmp: tempfile::TempDir,
    pub cfg: Config,
    pub db: Db,
}

impl Env {
    pub fn new() -> Self {
        let tmp = tempfile::tempdir().expect("tempdir");
        let cfg = Config {
            root: tmp.path().to_path_buf(),
            signing_key_id: "TESTKEY".into(),
            ..Config::default()
        };
        cfg.ensure_dirs().expect("ensure_dirs");
        db::migrate(&cfg.db_path()).expect("migrate");
        let db = Db::open_migrated(&cfg.db_path()).expect("open db");
        let rid = db::ensure_repo(
            &db.writer,
            &cfg.repo_name,
            &cfg.repo_arch_dir().display().to_string(),
            &cfg.arch,
            &cfg.signing_key_id,
        )
        .expect("repo row");
        assert!(rid > 0);
        Self { tmp, cfg, db }
    }

    pub fn root(&self) -> &Path {
        self.tmp.path()
    }

    pub fn path(&self, p: &str) -> PathBuf {
        self.tmp.path().join(p)
    }

    /// Insert a pkgbase + active subscription and return the pkgbase id.
    pub fn subscribe(&self, name: &str) -> i64 {
        let rid = db::repo_id(&self.db).unwrap();
        let url = format!("file://{}/aur/{}.git", self.root().display(), name);
        db::subscribe(&self.db.writer, rid, name, &url).unwrap();
        db::get_pkgbase(&self.db, name).unwrap().unwrap().id
    }

    /// Drop a row back in via raw SQL (tests need to construct states the API
    /// only reaches through several steps).
    pub fn exec(&self, sql: &str, params: &[P]) -> usize {
        let sql = sql.to_string();
        let params: Vec<P> = params.to_vec();
        self.db
            .writer
            .tx(move |tx| {
                let refs: Vec<&dyn rusqlite::ToSql> = params
                    .iter()
                    .map(|p| match p {
                        P::I(i) => i as &dyn rusqlite::ToSql,
                        P::S(s) => s as &dyn rusqlite::ToSql,
                    })
                    .collect();
                Ok(tx.execute(&sql, rusqlite::params_from_iter(refs.iter()))?)
            })
            .unwrap()
    }

    /// Stand in for the build+publish path: turn an approved candidate into a
    /// published release and move the accepted pointer. The real path lives in
    /// `pipeline`; detection tests need an accepted base without a build.
    pub fn accept_as_release(&self, candidate_id: i64) -> i64 {
        let at = "2026-01-01T00:00:00Z";
        self.db
            .writer
            .tx(move |tx| {
                tx.execute(
                    "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision,
                                           risk_level, diff_digest, identity_hash)
                     SELECT id, base_release_id, ?2, 'approved', risk_level, diff_digest, identity_hash
                     FROM candidate WHERE id=?1",
                    rusqlite::params![candidate_id, at],
                )?;
                let approval_id = tx.last_insert_rowid();
                tx.execute(
                    "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash,
                                          upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel,
                                          state, published_at, created_at)
                     SELECT c.pkgbase_id, c.id, ?2, s.aur_commit, s.recipe_hash, c.upstream_pins_json,
                            c.source_digests_json, c.epoch, c.pkgver, c.pkgrel,
                            'published', ?3, ?3
                     FROM candidate c JOIN snapshot s ON s.id = c.snapshot_id WHERE c.id=?1",
                    rusqlite::params![candidate_id, approval_id, at],
                )?;
                let release_id = tx.last_insert_rowid();
                tx.execute(
                    "UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2",
                    rusqlite::params![at, candidate_id],
                )?;
                tx.execute(
                    "INSERT INTO package (repo_id, release_id, name, arch, version, state)
                     SELECT (SELECT id FROM repo ORDER BY id LIMIT 1), ?1,
                            b.name, 'x86_64', c.pkgver || '-' || c.pkgrel, 'in_index'
                     FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?2",
                    rusqlite::params![release_id, candidate_id],
                )?;
                tx.execute(
                    "UPDATE pkgbase SET current_accepted_release_id=?1
                     WHERE id=(SELECT pkgbase_id FROM candidate WHERE id=?2)",
                    rusqlite::params![release_id, candidate_id],
                )?;
                Ok(release_id)
            })
            .unwrap()
    }

    pub fn query_i64(&self, sql: &str, params: &[P]) -> Option<i64> {
        let sql = sql.to_string();
        let params: Vec<P> = params.to_vec();
        self.db
            .read(move |c| {
                let refs: Vec<&dyn rusqlite::ToSql> = params
                    .iter()
                    .map(|p| match p {
                        P::I(i) => i as &dyn rusqlite::ToSql,
                        P::S(s) => s as &dyn rusqlite::ToSql,
                    })
                    .collect();
                use rusqlite::OptionalExtension;
                Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0))
                    .optional()?)
            })
            .unwrap()
    }
}

/// A test parameter. Owned so it can cross the writer-actor channel.
#[derive(Debug, Clone)]
pub enum P {
    I(i64),
    S(String),
}

impl From<i64> for P {
    fn from(i: i64) -> Self {
        P::I(i)
    }
}
impl From<&str> for P {
    fn from(s: &str) -> Self {
        P::S(s.to_string())
    }
}
impl From<String> for P {
    fn from(s: String) -> Self {
        P::S(s)
    }
}

/// Shorthand for building a parameter slice.
pub fn params(v: Vec<impl Into<P>>) -> Vec<P> {
    v.into_iter().map(Into::into).collect()
}

impl Drop for Env {
    fn drop(&mut self) {
        self.db.writer.shutdown();
    }
}

/// A minimal PKGBUILD for tests that need recipe bytes without a fixture dir.
pub fn pkgbuild(pkgbase: &str, pkgver: &str, pkgrel: &str, extra: &str) -> String {
    format!(
        "pkgbase={pkgbase}\npkgver={pkgver}\npkgrel={pkgrel}\npkgdesc=test\narch=(x86_64)\nurl=https://example.invalid\nlicense=(MIT)\n{extra}\nbuild() {{ :\n}}\npackage_{pkgbase}() {{ :\n}}\n"
    )
}

/// Build a throwaway git repo with the given files and return its path.
pub fn make_git_repo(dir: &Path, files: &[(&str, &str)], msg: &str) -> String {
    std::fs::create_dir_all(dir).unwrap();
    git(dir, &["init", "-q", "-b", "master"]);
    git(dir, &["config", "user.email", "t@example.invalid"]);
    git(dir, &["config", "user.name", "t"]);
    for (name, body) in files {
        let p = dir.join(name);
        if let Some(parent) = p.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(p, body).unwrap();
    }
    git(dir, &["add", "-A"]);
    git(dir, &["commit", "-q", "-m", msg]);
    git(dir, &["rev-parse", "HEAD"])
}

pub fn git_add_commit(dir: &Path, files: &[(&str, &str)], msg: &str) -> String {
    for (name, body) in files {
        std::fs::write(dir.join(name), body).unwrap();
    }
    git(dir, &["add", "-A"]);
    git(dir, &["commit", "-q", "-m", msg]);
    git(dir, &["rev-parse", "HEAD"])
}

pub fn git(dir: &Path, args: &[&str]) -> String {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .expect("git");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout).trim().to_string()
}