forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

issue_close_e2e.rs289 lines, 9.8 KiBHistoryRawDownload
1//! End-to-end: pushes over HTTPS close and reference issues from commit messages.
2//!
3//! The server runs as a subprocess. Issues are created through the store on the same database
4//! file, and every push is a real `git push` through the git HTTP endpoints.
5
6use crate::common::{
7 Http, bin, input_value, launch, login, pick_ports, relaunch, tool_on_path, write_config,
8};
9use std::fs;
10use std::future::Future;
11use std::path::Path;
12use std::process::{Command, Output};
13use std::time::{Duration, Instant};
14
15use forge_core::Store;
16
17const TAHINLI_PW: &str = "tahinli-password-123";
18const BOB_PW: &str = "bob-password-4567";
19
20fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
21 let out = Command::new(bin())
22 .arg("--config")
23 .arg(config)
24 .args(["admin", "create-user", username])
25 .args(extra)
26 .env("FORGE_PASSWORD", password)
27 .output()
28 .expect("run admin create-user");
29 assert!(
30 out.status.success(),
31 "create-user {username} failed:\n{}",
32 String::from_utf8_lossy(&out.stderr)
33 );
34}
35
36/// Runs git with credential helpers disabled and returns stdout, trimmed. Panics on failure.
37fn git(cwd: &Path, args: &[&str]) -> String {
38 let out = git_output(cwd, args, &[]);
39 assert!(
40 out.status.success(),
41 "git {args:?} failed:\n{}",
42 String::from_utf8_lossy(&out.stderr)
43 );
44 String::from_utf8_lossy(&out.stdout).trim().to_owned()
45}
46
47fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
48 let mut cmd = Command::new("git");
49 cmd.current_dir(cwd)
50 .args(["-c", "credential.helper="])
51 .args(args)
52 .env("GIT_TERMINAL_PROMPT", "0");
53 for (key, value) in env {
54 cmd.env(key, value);
55 }
56 cmd.output().expect("run git")
57}
58
59/// Writes `name`, commits it as tahinli, and returns the new HEAD.
60fn commit_file(repo: &Path, name: &str, message: &str) -> String {
61 fs::write(repo.join(name), message).expect("write file");
62 git(repo, &["add", name]);
63 git(
64 repo,
65 &[
66 "-c",
67 "user.name=tahinli",
68 "-c",
69 "user.email=tahinli@example.test",
70 "-c",
71 "commit.gpgsign=false",
72 "commit",
73 "-q",
74 "-m",
75 message,
76 ],
77 );
78 git(repo, &["rev-parse", "HEAD"])
79}
80
81/// Creates an access token through `/settings/tokens` and returns the token shown once.
82async fn create_token(http: &Http, session: &str, name: &str) -> String {
83 let page = http.get_cookie("/settings/keys", session).await;
84 assert_eq!(page.status, 200, "GET /settings/keys");
85 let csrf = input_value(&page.body, "csrf");
86 let res = http
87 .post_form(
88 "/settings/tokens",
89 &[("csrf", &csrf), ("name", name), ("expires", "30")],
90 Some(session),
91 )
92 .await;
93 assert_eq!(res.status, 200, "create token: {}", res.body);
94 let doc = scraper::Html::parse_document(&res.body);
95 let selector = scraper::Selector::parse("pre.code code").expect("selector");
96 let token: String = doc
97 .select(&selector)
98 .next()
99 .expect("token shown after creation")
100 .text()
101 .collect();
102 let token = token.trim().to_owned();
103 assert!(token.starts_with("forge_"), "unexpected token shape");
104 token
105}
106
107/// Creates a public repo through `/new`.
108async fn create_repo(http: &Http, session: &str, name: &str) {
109 let page = http.get_cookie("/new", session).await;
110 assert_eq!(page.status, 200, "GET /new");
111 let csrf = input_value(&page.body, "csrf");
112 let res = http
113 .post_form(
114 "/new",
115 &[
116 ("csrf", &csrf),
117 ("name", name),
118 ("description", ""),
119 ("visibility", "public"),
120 ("default_branch", "main"),
121 ],
122 Some(session),
123 )
124 .await;
125 assert_eq!(res.status, 303, "create repo {name}: {}", res.body);
126 assert_eq!(
127 res.location().as_deref(),
128 Some(format!("/tahinli/{name}").as_str())
129 );
130}
131
132/// Polls `check` every 100ms until it returns true, failing after 5 seconds.
133async fn eventually<F, Fut>(what: &str, mut check: F)
134where
135 F: FnMut() -> Fut,
136 Fut: Future<Output = bool>,
137{
138 let deadline = Instant::now() + Duration::from_secs(5);
139 while !check().await {
140 assert!(
141 Instant::now() < deadline,
142 "timed out after 5s waiting for {what}"
143 );
144 tokio::time::sleep(Duration::from_millis(100)).await;
145 }
146}
147
148/// The issue page for `number`, read as `session`.
149async fn issue_page(http: &Http, session: &str, number: u32) -> String {
150 let res = http
151 .get_cookie(&format!("/tahinli/pub/issues/{number}"), session)
152 .await;
153 assert_eq!(res.status, 200, "GET issue {number}");
154 res.body
155}
156
157/// Text of the state badge on an issue page, e.g. `Open` or `Closed`.
158fn state_badge(body: &str) -> String {
159 let doc = scraper::Html::parse_document(body);
160 let selector = scraper::Selector::parse(".issue-badge").expect("selector");
161 doc.select(&selector)
162 .next()
163 .map(|el| el.text().collect::<String>().trim().to_owned())
164 .unwrap_or_default()
165}
166
167#[tokio::test]
168async fn pushes_close_and_reference_issues() {
169 if !tool_on_path("git") {
170 eprintln!("SKIP issue_close_e2e: `git` was not found on PATH");
171 return;
172 }
173
174 // Keep the path short: the internal unix socket path is limited to 108 bytes.
175 let root = tempfile::Builder::new()
176 .prefix("ice2e")
177 .tempdir_in("/tmp")
178 .expect("temp dir");
179 let dir = root.path().to_path_buf();
180 let ports = pick_ports();
181 let config = write_config(&dir, ports);
182 let log_path = dir.join("serve.log");
183
184 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
185 run_admin(&config, "bob", &[], BOB_PW);
186
187 // Web setup: log in, make a token and create the repo.
188 let (mut server, ports) = launch(&dir, ports).await;
189 let http_port = ports.http;
190 let http = Http::new(http_port);
191 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
192 let token = create_token(&http, &tahinli, "issue-close-token").await;
193 create_repo(&http, &tahinli, "pub").await;
194
195 // The database file is locked while the server runs, so stop it, create the issues through
196 // the store, and start the server again on the same ports.
197 drop(server);
198 {
199 let store = Store::open(&dir.join("forge.db"))
200 .await
201 .expect("open store");
202 let author = store
203 .user_by_username("tahinli")
204 .await
205 .expect("user lookup")
206 .expect("tahinli exists");
207 let repo = store
208 .repo_by_owner_and_name("tahinli", "pub")
209 .await
210 .expect("repo lookup")
211 .expect("repo exists");
212 for n in 1..=3 {
213 store
214 .create_issue(&repo.id, &author.id, &format!("issue {n}"), "body")
215 .await
216 .expect("create issue");
217 }
218 }
219 server = relaunch(&config, &log_path, ports).await;
220 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
221
222 // Push over HTTPS with the token.
223 let url = format!("http://tahinli:{token}@127.0.0.1:{http_port}/tahinli/pub.git");
224 let work = dir.join("work");
225 git(
226 &dir,
227 &["clone", "-q", &url, work.to_str().expect("utf-8 path")],
228 );
229 let base = commit_file(&work, "base.txt", "base commit");
230 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
231
232 // A commit that references #3 on a non-default branch must not close it.
233 git(&work, &["checkout", "-q", "-b", "topic"]);
234 let topic_oid = commit_file(&work, "topic.txt", "fixes #3 on a topic branch");
235 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/topic"]);
236
237 // Default branch: one closing reference and one plain reference.
238 git(&work, &["checkout", "-q", "-B", "mainline", &base]);
239 let main_oid = commit_file(&work, "main.txt", "Fixes #1, refs #2");
240 // The same commit goes to another branch first. That push is not processed, so the
241 // push to main below must produce exactly one referenced event.
242 git(
243 &work,
244 &["push", "-q", "origin", "HEAD:refs/heads/dup-of-main"],
245 );
246 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
247
248 let commit_link = format!("/commit/{main_oid}");
249 let link_ref = commit_link.as_str();
250 let (http_ref, tahinli_ref) = (&http, tahinli.as_str());
251 eventually("#1 closed by the push", || async move {
252 state_badge(&issue_page(http_ref, tahinli_ref, 1).await) == "Closed"
253 })
254 .await;
255 let page1 = issue_page(&http, &tahinli, 1).await;
256 assert!(
257 page1.contains(&commit_link),
258 "#1 timeline should link the closing commit"
259 );
260
261 eventually("#2 referenced by the push", || async move {
262 let page = issue_page(http_ref, tahinli_ref, 2).await;
263 page.contains("referenced this") && page.contains(link_ref)
264 })
265 .await;
266 let page2 = issue_page(&http, &tahinli, 2).await;
267 assert_eq!(state_badge(&page2), "Open", "#2 is only referenced");
268
269 // Nothing observable marks the end of a background run for a non-matching push, so give the
270 // topic and dup-branch work time to finish before checking the counts again.
271 tokio::time::sleep(Duration::from_secs(2)).await;
272 let page2 = issue_page(&http, &tahinli, 2).await;
273 assert_eq!(
274 page2.matches("referenced this").count(),
275 1,
276 "referenced event must not be duplicated"
277 );
278 let page3 = issue_page(&http, &tahinli, 3).await;
279 assert_eq!(
280 state_badge(&page3),
281 "Open",
282 "#3 must not be closed from topic"
283 );
284 assert!(
285 !page3.contains(&format!("/commit/{topic_oid}")),
286 "non-default branch pushes are not processed"
287 );
288 drop(server);
289}