OXYGENHUB
# e8e7158bbc73 oxygenhub / crates / oh / tests / cli.rs
10.2 KiB · Rust · last changed oh issue edit, and oh dies quietly on a closed pipe 1 month ago source blame history raw
1
//! `oh` against a real hub: signing in, finding the repository from a
2
//! checkout's remote, issues, Flow runs, releases and their trust report,
3
//! and the raw API.
4
5
use oxy_core::repo::{IdentityScope, Repo};
6
use oxygenhub::config::Config;
7
use oxygenhub::repos::RepoName;
8
use oxygenhub::{db, Shared};
9
use std::path::{Path, PathBuf};
10
11
const ROOTFS: &str = "36fc4e3238044e424219a2b9002bf61bbe1805fec14d52cf37e17fae77c9ff16";
12
13
fn hermetic() -> PathBuf {
14
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
15
    let d = DIR.get_or_init(|| tempfile::tempdir().unwrap());
16
    std::env::set_var("OXY_HOME", d.path());
17
    d.path().to_path_buf()
18
}
19
20
struct Hub {
21
    app: Shared,
22
    base: String,
23
    _dir: tempfile::TempDir,
24
}
25
26
async fn hub() -> Hub {
27
    hermetic();
28
    let dir = tempfile::tempdir().unwrap();
29
    let mut config = Config::load(dir.path()).unwrap();
30
    config.auth.push_tokens = vec!["site".into()];
31
    config.flow.repos = vec!["andy/*".into()];
32
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
33
    let port = listener.local_addr().unwrap().port();
34
    config.server.base_url = format!("http://127.0.0.1:{port}");
35
    let app = oxygenhub::build(config).await.unwrap();
36
    let router = oxygenhub::router(app.clone());
37
    tokio::spawn(async move { axum_serve(listener, router).await });
38
    Hub { app, base: format!("http://127.0.0.1:{port}"), _dir: dir }
39
}
40
41
async fn axum_serve(listener: tokio::net::TcpListener, router: axum::Router) {
42
    axum::serve(listener, router).await.unwrap();
43
}
44
45
/// Run `oh` in `dir` with `env`; (exit code, stdout, stderr).
46
async fn oh(dir: &Path, env: &[(&str, &str)], args: &[&str]) -> (i32, String, String) {
47
    let (dir, env, args): (PathBuf, Vec<(String, String)>, Vec<String>) = (
48
        dir.to_path_buf(),
49
        env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
50
        args.iter().map(|a| a.to_string()).collect(),
51
    );
52
    tokio::task::spawn_blocking(move || {
53
        let out = std::process::Command::new(env!("CARGO_BIN_EXE_oh"))
54
            .args(&args)
55
            .current_dir(&dir)
56
            .env_remove("OH_TOKEN")
57
            .env_remove("OXY_TOKEN")
58
            .env_remove("OH_HUB")
59
            .envs(env)
60
            .output()
61
            .unwrap();
62
        (
63
            out.status.code().unwrap_or(-1),
64
            String::from_utf8_lossy(&out.stdout).into_owned(),
65
            String::from_utf8_lossy(&out.stderr).into_owned(),
66
        )
67
    })
68
    .await
69
    .unwrap()
70
}
71
72
fn write(root: &Path, rel: &str, content: &str) {
73
    let p = root.join(rel);
74
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
75
    std::fs::write(p, content).unwrap();
76
}
77
78
#[tokio::test(flavor = "multi_thread")]
79
async fn oh_drives_issues_runs_and_releases() {
80
    let h = hub().await;
81
    // The site token acts as the first site administrator.
82
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
83
    h.app.repos.create(&RepoName::parse("andy/demo").unwrap(), None).unwrap();
84
    let demo = db::repos::create(&h.app.db, "andy", "demo", "A demo", hub_api::Visibility::Public).await.unwrap();
85
    db::issues::upsert_label(&h.app.db, demo.id, "bug", "#d73a4a", "").await.unwrap();
86
87
    // A checkout whose origin is the hub: `oh` needs nothing else.
88
    let work = tempfile::tempdir().unwrap();
89
    let mut c = Repo::init(work.path()).unwrap();
90
    c.config.set("remote.origin.url", &format!("{}/andy/demo", h.base)).unwrap();
91
    c.config.set("remote.origin.token", "site").unwrap();
92
    c.save_config().unwrap();
93
    c.create_identity("Andy", "[email protected]", IdentityScope::Repo).unwrap();
94
    write(
95
        work.path(),
96
        ".flow/pipeline.kdl",
97
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"test\" {{\n    sandbox \"alpine\"\n    exec \"true\"\n}}\n"),
98
    );
99
    c.snapshot("test").unwrap();
100
    c.commit("Add a pipeline", &[]).unwrap();
101
    let heads = c.bookmark_heads().unwrap();
102
    c.tag_create("v1", &heads, "first").unwrap();
103
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
104
    let w = work.path();
105
106
    let (code, out, err) = oh(w, &[], &["repo", "view", "--plain"]).await;
107
    assert_eq!(code, 0, "{err}");
108
    assert!(out.contains("andy/demo") && out.contains("A demo") && out.contains("oxy clone"), "{out}");
109
110
    // Issues.
111
    let (code, out, err) = oh(w, &[], &["issue", "create", "--title", "Broken thing", "--body", "It breaks."]).await;
112
    assert_eq!(code, 0, "{err}");
113
    assert!(out.contains("opened #1"), "{out}");
114
    let (_, out, _) = oh(w, &[], &["issue", "list", "--json"]).await;
115
    let list: serde_json::Value = serde_json::from_str(&out).unwrap();
116
    assert_eq!((list[0]["number"].as_i64(), list[0]["title"].as_str()), (Some(1), Some("Broken thing")));
117
    let (code, out, err) =
118
        oh(w, &[], &["issue", "edit", "1", "--title", "Broken thing, badly", "--label", "bug", "--assignee", "andy"]).await;
119
    assert_eq!(code, 0, "{err}");
120
    assert!(out.contains("edited #1"), "{out}");
121
    let (_, out, _) = oh(w, &[], &["issue", "view", "1", "--json"]).await;
122
    let i: serde_json::Value = serde_json::from_str(&out).unwrap();
123
    assert_eq!(i["title"], "Broken thing, badly");
124
    assert_eq!(i["labels"][0]["name"], "bug");
125
    assert_eq!(i["assignees"][0], "andy");
126
    let (code, _, err) = oh(w, &[], &["issue", "edit", "1"]).await;
127
    assert_eq!(code, 2);
128
    assert!(err.contains("say what to change"), "{err}");
129
    let (_, out, _) = oh(w, &[], &["issue", "edit", "1", "--no-labels", "--no-assignees", "--json"]).await;
130
    let i: serde_json::Value = serde_json::from_str(&out).unwrap();
131
    assert!(i["labels"].as_array().unwrap().is_empty() && i["assignees"].as_array().unwrap().is_empty(), "{out}");
132
    let (_, out, _) = oh(w, &[], &["issue", "comment", "1", "--body", "Seen it too."]).await;
133
    assert!(out.contains("commented on #1"));
134
    let (_, out, _) = oh(w, &[], &["issue", "view", "1", "--plain"]).await;
135
    assert!(out.contains("It breaks.") && out.contains("Seen it too."), "{out}");
136
    let (_, out, _) = oh(w, &[], &["issue", "close", "1"]).await;
137
    assert!(out.contains("closed #1"));
138
    let (_, out, _) = oh(w, &[], &["issue", "list", "--plain"]).await;
139
    assert!(out.contains("No open issues."), "{out}");
140
141
    // Flow: the push started run 1; start another without a push.
142
    let (code, out, err) = oh(w, &[], &["run", "start"]).await;
143
    assert_eq!(code, 0, "{err}");
144
    assert!(out.contains("started run #2"), "{out}");
145
    let (_, out, _) = oh(w, &[], &["run", "list", "--json"]).await;
146
    let runs: serde_json::Value = serde_json::from_str(&out).unwrap();
147
    assert_eq!(runs.as_array().unwrap().len(), 2);
148
    let (_, out, _) = oh(w, &[], &["run", "view", "2", "--plain"]).await;
149
    assert!(out.contains("test") && out.contains("#2"), "{out}");
150
151
    // Releases, an asset, and the trust report.
152
    let (code, out, err) = oh(w, &[], &["release", "create", "v1", "--title", "One", "--notes", "First."]).await;
153
    assert_eq!(code, 0, "{err}");
154
    assert!(out.contains("released v1"), "{out}");
155
    let asset = w.join("tool.bin");
156
    std::fs::write(&asset, b"bytes").unwrap();
157
    let (code, out, err) = oh(w, &[], &["release", "upload", "v1", asset.to_str().unwrap()]).await;
158
    assert_eq!(code, 0, "{err}");
159
    assert!(out.contains("attached tool.bin to v1"));
160
    std::fs::remove_file(&asset).unwrap();
161
    let (_, out, _) = oh(w, &[], &["release", "list", "--json"]).await;
162
    let rel: serde_json::Value = serde_json::from_str(&out).unwrap();
163
    assert_eq!(rel[0]["assets"][0]["name"], "tool.bin");
164
    let (code, out, _) = oh(w, &[], &["release", "trust", "v1", "--plain"]).await;
165
    assert_eq!(code, 0, "warnings only: {out}");
166
    assert!(out.contains("Tag v1 is signed") && out.contains("tool.bin: no build found"), "{out}");
167
168
    // A proposal from a bookmark, landed from the command line.
169
    c.bookmark_create("topic", None).unwrap();
170
    c.bookmark_switch("topic", false).unwrap();
171
    write(w, "topic.txt", "more\n");
172
    c.snapshot("test").unwrap();
173
    c.commit("Add topic", &[]).unwrap();
174
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
175
    let (code, out, err) = oh(w, &[], &["proposal", "create", "--title", "Topic", "--from", "topic"]).await;
176
    assert_eq!(code, 0, "{err}");
177
    let n: String = out.split("proposed #").nth(1).unwrap().chars().take_while(|c| c.is_ascii_digit()).collect();
178
    let (_, out, _) = oh(w, &[], &["proposal", "view", &n, "--plain"]).await;
179
    assert!(out.contains("topic → main") && out.contains("Add topic"), "{out}");
180
    let (code, out, err) = oh(w, &[], &["proposal", "land", &n]).await;
181
    assert_eq!(code, 0, "{err}");
182
    assert!(out.contains(&format!("landed #{n} on main")), "{out}");
183
    let (code, _, err) = oh(w, &[], &["proposal", "land", &n]).await;
184
    assert_ne!(code, 0);
185
    assert!(err.contains("HTTP 409") && err.contains("landed"), "{err}");
186
187
    // Outside a checkout: --repo and a saved login.
188
    let elsewhere = tempfile::tempdir().unwrap();
189
    let cfg = elsewhere.path().join("oh.toml");
190
    let cfg_s = cfg.to_str().unwrap();
191
    let (code, _, err) = oh(elsewhere.path(), &[("OH_CONFIG", cfg_s)], &["issue", "list"]).await;
192
    assert_ne!(code, 0);
193
    assert!(err.contains("--repo"), "{err}");
194
    let (code, out, err) =
195
        oh(elsewhere.path(), &[("OH_CONFIG", cfg_s)], &["auth", "login", "--with-hub", &h.base, "--token", "site"]).await;
196
    assert_eq!(code, 0, "{err}");
197
    assert!(out.contains("signed in"), "{out}");
198
    #[cfg(unix)]
199
    {
200
        use std::os::unix::fs::PermissionsExt;
201
        assert_eq!(std::fs::metadata(&cfg).unwrap().permissions().mode() & 0o777, 0o600, "tokens are owner-only");
202
    }
203
    let (code, out, _) =
204
        oh(elsewhere.path(), &[("OH_CONFIG", cfg_s)], &["issue", "list", "--state", "all", "--repo", "andy/demo", "--plain"]).await;
205
    assert_eq!(code, 0);
206
    assert!(out.contains("Broken thing"), "{out}");
207
    let (code, out, _) = oh(elsewhere.path(), &[("OH_CONFIG", cfg_s)], &["api", "/repos/andy/demo/labels"]).await;
208
    assert_eq!(code, 0);
209
    assert!(out.trim_start().starts_with('['), "{out}");
210
    // A bad token says what to do.
211
    let (code, _, err) = oh(w, &[("OXY_TOKEN", "nope")], &["issue", "create", "--title", "x"]).await;
212
    assert_ne!(code, 0);
213
    assert!(err.contains("HTTP 401") && err.contains("oh auth login"), "{err}");
214
}