forge
Explore
Log in

Don't you dare go Hollow

Page tests use the shared send/send_form/next_event harness where it fits

Browse files at this commit

3cdd79469c2c7f81443a9130bb7872fdba73a501Ahmet Kaan GümüşParent: c3c44bb
Checks pending
Show checks
  • refactor
    • page tests use the shared send/send_form/next_event harness where it fits
    • helpers needing headers, raw bytes or SSE streams stay local
Show full message
♻️ refactor: page tests use the shared send/send_form/next_event harness where it fits; helpers needing headers, raw bytes or SSE streams stay local
crates/forge-web-account/src/pages/account_tools_tests.rsmodified+49 -92
@@ -4,6 +4,7 @@ use topcoat::router::request::Request;
4 use topcoat::router::{Body, Router, to_bytes};4 use topcoat::router::{Body, Router, to_bytes};
5 5
6 use crate::auth::SESSION_COOKIE;6 use crate::auth::SESSION_COOKIE;
7+use crate::test_support::fixture::{send, send_form};
7 use crate::test_support::{app_router, create_session, test_state};8 use crate::test_support::{app_router, create_session, test_state};
8 9
9 const ADMIN_TOKEN: &str = "tools-admin-session";10 const ADMIN_TOKEN: &str = "tools-admin-session";
@@ -40,28 +41,8 @@ async fn fixture(dir: &std::path::Path, banner: Option<BannerConfig>) -> Fx {
40 }41 }
41 }42 }
42 43
43-async fn send(44+fn session_cookie(token: &str) -> String {
44- router: &Router,45+ format!("__Host-{SESSION_COOKIE}={token}")
45- method: &str,
46- uri: &str,
47- token: Option<&str>,
48- form: Option<String>,
49-) -> (u16, String) {
50- let mut builder = Request::builder().method(method).uri(uri);
51- if let Some(token) = token {
52- builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
53- }
54- let body = match form {
55- Some(form) => {
56- builder = builder.header("content-type", "application/x-www-form-urlencoded");
57- Body::from(form)
58- }
59- None => Body::empty(),
60- };
61- let res = router.handle(builder.body(body).unwrap()).await;
62- let status = res.status().as_u16();
63- let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
64- (status, String::from_utf8_lossy(&bytes).into_owned())
65 }46 }
66 47
67 fn csrf(extra: &str) -> Option<String> {48 fn csrf(extra: &str) -> Option<String> {
@@ -75,103 +56,94 @@ async fn admin_account_tools() {
75 56
76 let detail = format!("/admin/users/{}", fx.user_id);57 let detail = format!("/admin/users/{}", fx.user_id);
77 for uri in ["/admin/health", detail.as_str()] {58 for uri in ["/admin/health", detail.as_str()] {
59+ let user = session_cookie(USER_TOKEN);
60+ let admin = session_cookie(ADMIN_TOKEN);
78 assert_eq!(61 assert_eq!(
79- send(&fx.router, "GET", uri, Some(USER_TOKEN), None).await.0,62+ send(&fx.router, "GET", uri, Some(&user), None).await.status,
80 40463 404
81 );64 );
82- assert_eq!(send(&fx.router, "GET", uri, None, None).await.0, 404);65+ assert_eq!(send(&fx.router, "GET", uri, None, None).await.status, 404);
83 assert_eq!(66 assert_eq!(
84- send(&fx.router, "GET", uri, Some(ADMIN_TOKEN), None)67+ send(&fx.router, "GET", uri, Some(&admin), None)
85 .await68 .await
86- .0,69+ .status,
87 20070 200
88 );71 );
89 }72 }
90 let suspend = format!("{detail}/suspend");73 let suspend = format!("{detail}/suspend");
74+ let user = session_cookie(USER_TOKEN);
91 assert_eq!(75 assert_eq!(
92- send(&fx.router, "POST", &suspend, Some(USER_TOKEN), csrf(""))76+ send_form(&fx.router, "POST", &suspend, Some(&user), csrf(""))
93 .await77 .await
94- .0,78+ .status,
95 40479 404
96 );80 );
97 81
82+ let admin = session_cookie(ADMIN_TOKEN);
98 let uri = format!("/admin/users/{}/suspend", fx.user_id);83 let uri = format!("/admin/users/{}/suspend", fx.user_id);
99- let (status, _) = send(84+ let reply = send_form(
100 &fx.router,85 &fx.router,
101 "POST",86 "POST",
102 &uri,87 &uri,
103- Some(ADMIN_TOKEN),88+ Some(&admin),
104 Some("csrf=wrong&reason=spam".into()),89 Some("csrf=wrong&reason=spam".into()),
105 )90 )
106 .await;91 .await;
107- assert_eq!(status, 403);92+ assert_eq!(reply.status, 403);
108 assert!(fx.store.suspension(&fx.user_id).await.unwrap().is_none());93 assert!(fx.store.suspension(&fx.user_id).await.unwrap().is_none());
109 94
110- let (status, _) = send(95+ let reply = send_form(&fx.router, "POST", &uri, Some(&admin), csrf("&reason=spam")).await;
111- &fx.router,96+ assert_eq!(reply.status, 303);
112- "POST",
113- &uri,
114- Some(ADMIN_TOKEN),
115- csrf("&reason=spam"),
116- )
117- .await;
118- assert_eq!(status, 303);
119 let suspension = fx.store.suspension(&fx.user_id).await.unwrap().unwrap();97 let suspension = fx.store.suspension(&fx.user_id).await.unwrap().unwrap();
120 assert_eq!(suspension.reason, "spam");98 assert_eq!(suspension.reason, "spam");
121- let (status, _) = send(99+ let reply = send(&fx.router, "GET", "/settings/security", Some(&user), None).await;
122- &fx.router,100+ assert_ne!(reply.status, 200);
123- "GET",
124- "/settings/security",
125- Some(USER_TOKEN),
126- None,
127- )
128- .await;
129- assert_ne!(status, 200);
130 let page = send(101 let page = send(
131 &fx.router,102 &fx.router,
132 "GET",103 "GET",
133 &format!("/admin/users/{}", fx.user_id),104 &format!("/admin/users/{}", fx.user_id),
134- Some(ADMIN_TOKEN),105+ Some(&admin),
135 None,106 None,
136 )107 )
137 .await108 .await
138- .1;109+ .body;
139 assert!(page.contains("spam"));110 assert!(page.contains("spam"));
140 111
141- let (status, _) = send(112+ let reply = send_form(
142 &fx.router,113 &fx.router,
143 "POST",114 "POST",
144 &format!("/admin/users/{}/unsuspend", fx.user_id),115 &format!("/admin/users/{}/unsuspend", fx.user_id),
145- Some(ADMIN_TOKEN),116+ Some(&admin),
146 csrf(""),117 csrf(""),
147 )118 )
148 .await;119 .await;
149- assert_eq!(status, 303);120+ assert_eq!(reply.status, 303);
150 assert!(fx.store.suspension(&fx.user_id).await.unwrap().is_none());121 assert!(fx.store.suspension(&fx.user_id).await.unwrap().is_none());
151 122
152 let base = format!("/admin/users/{}", fx.admin_id);123 let base = format!("/admin/users/{}", fx.admin_id);
153- let (status, body) = send(124+ let reply = send_form(
154 &fx.router,125 &fx.router,
155 "POST",126 "POST",
156 &format!("{base}/admin"),127 &format!("{base}/admin"),
157- Some(ADMIN_TOKEN),128+ Some(&admin),
158 csrf("&admin=0"),129 csrf("&admin=0"),
159 )130 )
160 .await;131 .await;
161- assert_eq!(status, 200);132+ assert_eq!(reply.status, 200);
162- assert!(body.contains("last administrator"), "{body}");133+ assert!(reply.body.contains("last administrator"), "{}", reply.body);
163 let me = fx.store.user_by_id(&fx.admin_id).await.unwrap().unwrap();134 let me = fx.store.user_by_id(&fx.admin_id).await.unwrap().unwrap();
164 assert!(me.is_admin);135 assert!(me.is_admin);
165 136
166- let (status, body) = send(137+ let reply = send_form(
167 &fx.router,138 &fx.router,
168 "POST",139 "POST",
169 &format!("/admin/users/{}/reset-link", fx.user_id),140 &format!("/admin/users/{}/reset-link", fx.user_id),
170- Some(ADMIN_TOKEN),141+ Some(&admin),
171 csrf(""),142 csrf(""),
172 )143 )
173 .await;144 .await;
174- assert_eq!(status, 200);145+ assert_eq!(reply.status, 200);
146+ let body = reply.body;
175 let at = body.find("https://forge.test/reset/").expect("reset link");147 let at = body.find("https://forge.test/reset/").expect("reset link");
176 let token: String = body[at + "https://forge.test/reset/".len()..]148 let token: String = body[at + "https://forge.test/reset/".len()..]
177 .chars()149 .chars()
@@ -194,15 +166,15 @@ async fn admin_account_tools() {
194 .enable_totp(&fx.user_id, 1, &["h1".to_owned()])166 .enable_totp(&fx.user_id, 1, &["h1".to_owned()])
195 .await167 .await
196 .unwrap();168 .unwrap();
197- let (status, _) = send(169+ let reply = send_form(
198 &fx.router,170 &fx.router,
199 "POST",171 "POST",
200 &format!("/admin/users/{}/disable-2fa", fx.user_id),172 &format!("/admin/users/{}/disable-2fa", fx.user_id),
201- Some(ADMIN_TOKEN),173+ Some(&admin),
202 csrf(""),174 csrf(""),
203 )175 )
204 .await;176 .await;
205- assert_eq!(status, 303);177+ assert_eq!(reply.status, 303);
206 assert!(178 assert!(
207 !fx.store179 !fx.store
208 .account_facts(&fx.user_id)180 .account_facts(&fx.user_id)
@@ -251,18 +223,9 @@ async fn suspended_user_sees_the_reason_on_the_login_page() {
251 let precsrf = &html[start..start + html[start..].find('"').unwrap()];223 let precsrf = &html[start..start + html[start..].find('"').unwrap()];
252 let form =224 let form =
253 format!("username=tahinli&password=correct%20horse%20battery&next=%2F&precsrf={precsrf}");225 format!("username=tahinli&password=correct%20horse%20battery&next=%2F&precsrf={precsrf}");
254- let req = Request::builder()226+ let reply = send_form(&router, "POST", "/login", Some(&cookie), Some(form)).await;
255- .method("POST")227+ assert_eq!(reply.status, 200);
256- .uri("/login")228+ assert!(reply.body.contains("abuse of CI"), "{}", reply.body);
257- .header("cookie", cookie)
258- .header("content-type", "application/x-www-form-urlencoded")
259- .body(Body::from(form))
260- .unwrap();
261- let res = router.handle(req).await;
262- assert_eq!(res.status().as_u16(), 200);
263- let html =
264- String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned();
265- assert!(html.contains("abuse of CI"), "{html}");
266 assert!(store.list_sessions(&user.id).await.unwrap().is_empty());229 assert!(store.list_sessions(&user.id).await.unwrap().is_empty());
267 }230 }
268 231
@@ -276,22 +239,16 @@ async fn banner_shows_on_pages_and_a_dismissal_hides_it() {
276 };239 };
277 let fx = fixture(dir.path(), Some(banner)).await;240 let fx = fixture(dir.path(), Some(banner)).await;
278 for token in [None, Some(USER_TOKEN)] {241 for token in [None, Some(USER_TOKEN)] {
279- let (status, body) = send(&fx.router, "GET", "/explore", token, None).await;242+ let cookie = token.map(session_cookie);
280- assert_eq!(status, 200);243+ let reply = send(&fx.router, "GET", "/explore", cookie.as_deref(), None).await;
281- assert!(body.contains("site-banner warning"), "{body}");244+ assert_eq!(reply.status, 200);
282- assert!(body.contains("Maintenance tonight"));245+ assert!(reply.body.contains("site-banner warning"), "{}", reply.body);
246+ assert!(reply.body.contains("Maintenance tonight"));
283 }247 }
284 let hash = crate::views::banner_hash("Maintenance tonight", BannerLevel::Warning);248 let hash = crate::views::banner_hash("Maintenance tonight", BannerLevel::Warning);
285- let req = Request::builder()249+ let dismissed = format!("forge_banner={hash}");
286- .method("GET")250+ let reply = send(&fx.router, "GET", "/explore", Some(&dismissed), None).await;
287- .uri("/explore")251+ assert!(!reply.body.contains("Maintenance tonight"));
288- .header("cookie", format!("forge_banner={hash}"))
289- .body(Body::empty())
290- .unwrap();
291- let res = fx.router.handle(req).await;
292- let body =
293- String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned();
294- assert!(!body.contains("Maintenance tonight"));
295 252
296 let req = Request::builder()253 let req = Request::builder()
297 .method("POST")254 .method("POST")
@@ -319,6 +276,6 @@ async fn expired_banner_is_not_shown() {
319 expires: "2020-01-01 00:00".into(),276 expires: "2020-01-01 00:00".into(),
320 };277 };
321 let fx = fixture(dir.path(), Some(banner)).await;278 let fx = fixture(dir.path(), Some(banner)).await;
322- let (_, body) = send(&fx.router, "GET", "/explore", None, None).await;279+ let reply = send(&fx.router, "GET", "/explore", None, None).await;
323- assert!(!body.contains("Old news"));280+ assert!(!reply.body.contains("Old news"));
324 }281 }
crates/forge-web-account/src/pages/admin_live_tests.rsmodified+34 -23
@@ -1,9 +1,6 @@
1-use std::fmt::Debug;
2-
3 use forge_core::AuditAction;1 use forge_core::AuditAction;
4 use forge_core::store::backup_runs::RunKind;2 use forge_core::store::backup_runs::RunKind;
5 use forge_core::store::replication::DB_SUBJECT;3 use forge_core::store::replication::DB_SUBJECT;
6-use futures_util::Stream;
7 use serde_json::Value;4 use serde_json::Value;
8 use topcoat::router::request::Request;5 use topcoat::router::request::Request;
9 use topcoat::router::{Body, Router};6 use topcoat::router::{Body, Router};
@@ -12,7 +9,7 @@ use crate::audit::{self, Actor, Target};
12 use crate::auth::SESSION_COOKIE;9 use crate::auth::SESSION_COOKIE;
13 use crate::live::{Topic, admin};10 use crate::live::{Topic, admin};
14 use crate::state::AppState;11 use crate::state::AppState;
15-use crate::test_support::fixture::{next_event as next_event_or_end, next_frame};12+use crate::test_support::fixture::{next_event, next_frame};
16 use crate::test_support::{app_router, create_session, test_state};13 use crate::test_support::{app_router, create_session, test_state};
17 14
18 const ADMIN_TOKEN: &str = "admin-live-admin-session";15 const ADMIN_TOKEN: &str = "admin-live-admin-session";
@@ -75,16 +72,6 @@ async fn open(app: &Router, uri: &str, token: Option<&str>) -> topcoat::router::
75 .await72 .await
76 }73 }
77 74
78-async fn next_event<S, E>(frames: &mut S) -> Vec<u8>
79-where
80- S: Stream<Item = Result<bytes::Bytes, E>> + Unpin,
81- E: Debug,
82-{
83- next_event_or_end(frames)
84- .await
85- .expect("an event before the end")
86-}
87-
88 fn changed(data: &str) -> Vec<u8> {75 fn changed(data: &str) -> Vec<u8> {
89 format!("event: changed\ndata: {data}\n\n").into_bytes()76 format!("event: changed\ndata: {data}\n\n").into_bytes()
90 }77 }
@@ -151,7 +138,11 @@ async fn account_list_account_page_and_audit_send_for_their_changes() {
151 Value::Null,138 Value::Null,
152 )139 )
153 .await;140 .await;
154- assert_eq!(next_event(&mut list).await, changed("1"), "account list");141+ assert_eq!(
142+ next_event(&mut list).await,
143+ Some(changed("1")),
144+ "account list"
145+ );
155 146
156 fx.state147 fx.state
157 .store148 .store
@@ -171,7 +162,11 @@ async fn account_list_account_page_and_audit_send_for_their_changes() {
171 Value::Null,162 Value::Null,
172 )163 )
173 .await;164 .await;
174- assert_eq!(next_event(&mut page).await, changed("1"), "account page");165+ assert_eq!(
166+ next_event(&mut page).await,
167+ Some(changed("1")),
168+ "account page"
169+ );
175 170
176 audit::record(171 audit::record(
177 &fx.state.store,172 &fx.state.store,
@@ -182,7 +177,11 @@ async fn account_list_account_page_and_audit_send_for_their_changes() {
182 Value::Null,177 Value::Null,
183 )178 )
184 .await;179 .await;
185- assert_eq!(next_event(&mut audit).await, changed("1"), "audit log");180+ assert_eq!(
181+ next_event(&mut audit).await,
182+ Some(changed("1")),
183+ "audit log"
184+ );
186 }185 }
187 186
188 #[tokio::test]187 #[tokio::test]
@@ -210,7 +209,7 @@ async fn backups_replication_health_and_server_send_for_their_changes() {
210 .into_data_stream();209 .into_data_stream();
211 assert_eq!(210 assert_eq!(
212 next_event(&mut restarting).await,211 next_event(&mut restarting).await,
213- changed("restarted"),212+ Some(changed("restarted")),
214 "a restart"213 "a restart"
215 );214 );
216 let mut settings = open(&fx.app, "/admin/server/events", Some(ADMIN_TOKEN))215 let mut settings = open(&fx.app, "/admin/server/events", Some(ADMIN_TOKEN))
@@ -223,9 +222,17 @@ async fn backups_replication_health_and_server_send_for_their_changes() {
223 .jobs222 .jobs
224 .claim(RunKind::Backup)223 .claim(RunKind::Backup)
225 .expect("the slot is free");224 .expect("the slot is free");
226- assert_eq!(next_event(&mut backups).await, changed("1"), "run start");225+ assert_eq!(
226+ next_event(&mut backups).await,
227+ Some(changed("1")),
228+ "run start"
229+ );
227 drop(guard);230 drop(guard);
228- assert_eq!(next_event(&mut backups).await, changed("1"), "run end");231+ assert_eq!(
232+ next_event(&mut backups).await,
233+ Some(changed("1")),
234+ "run end"
235+ );
229 236
230 let outcome = crate::replication::worker::record(237 let outcome = crate::replication::worker::record(
231 &fx.state.store,238 &fx.state.store,
@@ -234,7 +241,11 @@ async fn backups_replication_health_and_server_send_for_their_changes() {
234 )241 )
235 .await;242 .await;
236 assert!(outcome.is_err());243 assert!(outcome.is_err());
237- assert_eq!(next_event(&mut replication).await, changed("1"), "copy");244+ assert_eq!(
245+ next_event(&mut replication).await,
246+ Some(changed("1")),
247+ "copy"
248+ );
238 249
239 crate::alerts::raise(250 crate::alerts::raise(
240 &fx.state,251 &fx.state,
@@ -244,12 +255,12 @@ async fn backups_replication_health_and_server_send_for_their_changes() {
244 "silent for an hour",255 "silent for an hour",
245 )256 )
246 .await;257 .await;
247- assert_eq!(next_event(&mut health).await, changed("1"), "alert");258+ assert_eq!(next_event(&mut health).await, Some(changed("1")), "alert");
248 259
249 admin().bump(&Topic::AdminServer);260 admin().bump(&Topic::AdminServer);
250 assert_eq!(261 assert_eq!(
251 next_event(&mut settings).await,262 next_event(&mut settings).await,
252- changed("settings"),263+ Some(changed("settings")),
253 "setting"264 "setting"
254 );265 );
255 }266 }
crates/forge-web-account/src/pages/import_tests.rsmodified+24 -40
@@ -1,8 +1,8 @@
1 use forge_core::Store;1 use forge_core::Store;
2-use topcoat::router::request::Request;2+use topcoat::router::Router;
3-use topcoat::router::{Body, Router, to_bytes};
4 3
5 use crate::auth::SESSION_COOKIE;4 use crate::auth::SESSION_COOKIE;
5+use crate::test_support::fixture::{send, send_form};
6 use crate::test_support::{app_router, create_session, test_state};6 use crate::test_support::{app_router, create_session, test_state};
7 7
8 const TOKEN: &str = "import-session";8 const TOKEN: &str = "import-session";
@@ -41,31 +41,12 @@ async fn fixture() -> Fixture {
41 }41 }
42 }42 }
43 43
44-async fn send(44+fn session_cookie(token: &str) -> String {
45- router: &Router,45+ format!("__Host-{SESSION_COOKIE}={token}")
46- method: &str,
47- uri: &str,
48- token: Option<&str>,
49- form: Option<String>,
50-) -> (u16, String) {
51- let mut builder = Request::builder().method(method).uri(uri);
52- if let Some(token) = token {
53- builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
54- }
55- let body = match form {
56- Some(form) => {
57- builder = builder.header("content-type", "application/x-www-form-urlencoded");
58- Body::from(form)
59- }
60- None => Body::empty(),
61- };
62- let res = router.handle(builder.body(body).expect("request")).await;
63- let status = res.status().as_u16();
64- let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
65- (status, String::from_utf8_lossy(&bytes).into_owned())
66 }46 }
67 47
68 async fn scenario_pages_render(fx: &Fixture) {48 async fn scenario_pages_render(fx: &Fixture) {
49+ let cookie = session_cookie(TOKEN);
69 for (uri, needle) in [50 for (uri, needle) in [
70 ("/new/import?source=git", "Import a repository"),51 ("/new/import?source=git", "Import a repository"),
71 ("/new/import?source=github", "Import a repository"),52 ("/new/import?source=github", "Import a repository"),
@@ -77,9 +58,9 @@ async fn scenario_pages_render(fx: &Fixture) {
77 ("/import", "Import history"),58 ("/import", "Import history"),
78 ("/settings/export", "Export your data"),59 ("/settings/export", "Export your data"),
79 ] {60 ] {
80- let (status, body) = send(&fx.router, "GET", uri, Some(TOKEN), None).await;61+ let reply = send(&fx.router, "GET", uri, Some(&cookie), None).await;
81- assert_eq!(status, 200, "{uri}: {body}");62+ assert_eq!(reply.status, 200, "{uri}: {}", reply.body);
82- assert!(body.contains(needle), "{uri} lacks {needle}");63+ assert!(reply.body.contains(needle), "{uri} lacks {needle}");
83 }64 }
84 }65 }
85 66
@@ -90,15 +71,16 @@ async fn scenario_need_session(fx: &Fixture) {
90 "/import",71 "/import",
91 "/settings/export",72 "/settings/export",
92 ] {73 ] {
93- let (status, body) = send(&fx.router, "GET", uri, None, None).await;74+ let reply = send(&fx.router, "GET", uri, None, None).await;
94- assert_ne!(status, 200, "{uri}: {body}");75+ assert_ne!(reply.status, 200, "{uri}: {}", reply.body);
95 }76 }
96 }77 }
97 78
98 async fn scenario_csrf(fx: &Fixture) {79 async fn scenario_csrf(fx: &Fixture) {
80+ let cookie = session_cookie(TOKEN);
99 let form = "source=git&remote=https%3A%2F%2Fexample.org%2Fa.git&csrf=wrong".to_owned();81 let form = "source=git&remote=https%3A%2F%2Fexample.org%2Fa.git&csrf=wrong".to_owned();
100- let (status, _) = send(&fx.router, "POST", "/new/import", Some(TOKEN), Some(form)).await;82+ let reply = send_form(&fx.router, "POST", "/new/import", Some(&cookie), Some(form)).await;
101- assert_ne!(status, 303, "a bad token must not redirect to a job");83+ assert_ne!(reply.status, 303, "a bad token must not redirect to a job");
102 assert!(84 assert!(
103 fx.store85 fx.store
104 .list_import_jobs(&fx.user_id, 10)86 .list_import_jobs(&fx.user_id, 10)
@@ -106,15 +88,15 @@ async fn scenario_csrf(fx: &Fixture) {
106 .expect("jobs")88 .expect("jobs")
107 .is_empty()89 .is_empty()
108 );90 );
109- let (status, _) = send(91+ let reply = send_form(
110 &fx.router,92 &fx.router,
111 "POST",93 "POST",
112 "/settings/export",94 "/settings/export",
113- Some(TOKEN),95+ Some(&cookie),
114 Some("csrf=wrong".into()),96 Some("csrf=wrong".into()),
115 )97 )
116 .await;98 .await;
117- assert_ne!(status, 303);99+ assert_ne!(reply.status, 303);
118 assert!(100 assert!(
119 fx.store101 fx.store
120 .list_exports(&fx.user_id)102 .list_exports(&fx.user_id)
@@ -125,11 +107,12 @@ async fn scenario_csrf(fx: &Fixture) {
125 }107 }
126 108
127 async fn scenario_private_address(fx: &Fixture) {109 async fn scenario_private_address(fx: &Fixture) {
110+ let cookie = session_cookie(TOKEN);
128 let form = format!(111 let form = format!(
129 "csrf={CSRF}&source=git&remote=https%3A%2F%2F127.0.0.1%2Fa.git&owner=tahinli&visibility=private"112 "csrf={CSRF}&source=git&remote=https%3A%2F%2F127.0.0.1%2Fa.git&owner=tahinli&visibility=private"
130 );113 );
131- let (status, body) = send(&fx.router, "POST", "/new/import", Some(TOKEN), Some(form)).await;114+ let reply = send_form(&fx.router, "POST", "/new/import", Some(&cookie), Some(form)).await;
132- assert_ne!(status, 500, "{body}");115+ assert_ne!(reply.status, 500, "{}", reply.body);
133 assert!(116 assert!(
134 fx.store117 fx.store
135 .list_import_jobs(&fx.user_id, 10)118 .list_import_jobs(&fx.user_id, 10)
@@ -151,10 +134,11 @@ async fn scenario_archive(fx: &Fixture) {
151 .await134 .await
152 .expect("ready");135 .expect("ready");
153 let uri = format!("/settings/export/{}/download", export.id);136 let uri = format!("/settings/export/{}/download", export.id);
154- let (status, _) = send(&fx.router, "GET", &uri, Some(OTHER), None).await;137+ let other = session_cookie(OTHER);
155- assert_eq!(status, 404, "a stranger gets not found");138+ let reply = send(&fx.router, "GET", &uri, Some(&other), None).await;
156- let (status, _) = send(&fx.router, "GET", &uri, None, None).await;139+ assert_eq!(reply.status, 404, "a stranger gets not found");
157- assert_ne!(status, 200);140+ let reply = send(&fx.router, "GET", &uri, None, None).await;
141+ assert_ne!(reply.status, 200);
158 }142 }
159 143
160 #[tokio::test]144 #[tokio::test]
crates/forge-web-account/src/pages/settings_gpg_tests.rsmodified+20 -23
@@ -2,7 +2,7 @@ use forge_core::Store;
2 use topcoat::router::Router;2 use topcoat::router::Router;
3 3
4 use crate::auth::SESSION_COOKIE;4 use crate::auth::SESSION_COOKIE;
5-use crate::test_support::fixture::{Reply, send};5+use crate::test_support::fixture::send;
6 6
7 const CSRF: &str = "gpg-test-csrf";7 const CSRF: &str = "gpg-test-csrf";
8 const TOKEN: &str = "gpg-test-token";8 const TOKEN: &str = "gpg-test-token";
@@ -36,16 +36,6 @@ async fn sign_in(store: &Store, user_id: &str) -> String {
36 format!("__Host-{SESSION_COOKIE}={TOKEN}")36 format!("__Host-{SESSION_COOKIE}={TOKEN}")
37 }37 }
38 38
39-async fn call(
40- site: &Site,
41- method: &str,
42- uri: &str,
43- cookie: Option<&str>,
44- fields: Option<&[(&str, &str)]>,
45-) -> Reply {
46- send(&site.router, method, uri, cookie, fields).await
47-}
48-
49 #[tokio::test]39 #[tokio::test]
50 async fn gpg_refusals_and_the_listing_share_one_site() {40 async fn gpg_refusals_and_the_listing_share_one_site() {
51 let (site, available) = site().await;41 let (site, available) = site().await;
@@ -55,7 +45,7 @@ async fn gpg_refusals_and_the_listing_share_one_site() {
55 .await45 .await
56 .unwrap();46 .unwrap();
57 47
58- let reply = call(&site, "GET", "/settings/gpg", None, None).await;48+ let reply = send(&site.router, "GET", "/settings/gpg", None, None).await;
59 assert_eq!(reply.status, 303, "anonymous page");49 assert_eq!(reply.status, 303, "anonymous page");
60 assert!(50 assert!(
61 reply51 reply
@@ -67,12 +57,19 @@ async fn gpg_refusals_and_the_listing_share_one_site() {
67 );57 );
68 58
69 let fields = [("csrf", CSRF), ("armored", "junk")];59 let fields = [("csrf", CSRF), ("armored", "junk")];
70- let reply = call(&site, "POST", "/settings/gpg", None, Some(&fields)).await;60+ let reply = send(&site.router, "POST", "/settings/gpg", None, Some(&fields)).await;
71 assert_eq!(reply.status, 303, "anonymous add");61 assert_eq!(reply.status, 303, "anonymous add");
72 62
73 let cookie = sign_in(&site.store, &tahinli.id).await;63 let cookie = sign_in(&site.store, &tahinli.id).await;
74 let bad = [("csrf", "wrong"), ("armored", "junk")];64 let bad = [("csrf", "wrong"), ("armored", "junk")];
75- let reply = call(&site, "POST", "/settings/gpg", Some(&cookie), Some(&bad)).await;65+ let reply = send(
66+ &site.router,
67+ "POST",
68+ "/settings/gpg",
69+ Some(&cookie),
70+ Some(&bad),
71+ )
72+ .await;
76 assert_eq!(reply.status, 403, "add with a bad csrf token");73 assert_eq!(reply.status, 403, "add with a bad csrf token");
77 74
78 let key = site75 let key = site
@@ -86,8 +83,8 @@ async fn gpg_refusals_and_the_listing_share_one_site() {
86 .await83 .await
87 .unwrap();84 .unwrap();
88 let anon_fields = [("csrf", CSRF), ("id", key.id.as_str())];85 let anon_fields = [("csrf", CSRF), ("id", key.id.as_str())];
89- let anon = call(86+ let anon = send(
90- &site,87+ &site.router,
91 "POST",88 "POST",
92 "/settings/gpg/delete",89 "/settings/gpg/delete",
93 None,90 None,
@@ -96,8 +93,8 @@ async fn gpg_refusals_and_the_listing_share_one_site() {
96 .await;93 .await;
97 assert_eq!(anon.status, 303, "anonymous delete");94 assert_eq!(anon.status, 303, "anonymous delete");
98 let bad_delete = [("csrf", "wrong"), ("id", key.id.as_str())];95 let bad_delete = [("csrf", "wrong"), ("id", key.id.as_str())];
99- let reply = call(96+ let reply = send(
100- &site,97+ &site.router,
101 "POST",98 "POST",
102 "/settings/gpg/delete",99 "/settings/gpg/delete",
103 Some(&cookie),100 Some(&cookie),
@@ -111,7 +108,7 @@ async fn gpg_refusals_and_the_listing_share_one_site() {
111 "the key survives refused deletes"108 "the key survives refused deletes"
112 );109 );
113 110
114- let reply = call(&site, "GET", "/settings/gpg", Some(&cookie), None).await;111+ let reply = send(&site.router, "GET", "/settings/gpg", Some(&cookie), None).await;
115 assert_eq!(reply.status, 200, "listing page");112 assert_eq!(reply.status, 200, "listing page");
116 assert!(113 assert!(
117 reply.body.contains(FINGERPRINT),114 reply.body.contains(FINGERPRINT),
@@ -161,8 +158,8 @@ async fn owners_delete_their_own_keys_and_no_one_elses() {
161 let cookie = sign_in(&site.store, &tahinli.id).await;158 let cookie = sign_in(&site.store, &tahinli.id).await;
162 159
163 let fields = [("csrf", CSRF), ("id", bob_key.id.as_str())];160 let fields = [("csrf", CSRF), ("id", bob_key.id.as_str())];
164- let reply = call(161+ let reply = send(
165- &site,162+ &site.router,
166 "POST",163 "POST",
167 "/settings/gpg/delete",164 "/settings/gpg/delete",
168 Some(&cookie),165 Some(&cookie),
@@ -173,8 +170,8 @@ async fn owners_delete_their_own_keys_and_no_one_elses() {
173 assert_eq!(site.store.list_gpg_keys(&bob.id).await.unwrap().len(), 1);170 assert_eq!(site.store.list_gpg_keys(&bob.id).await.unwrap().len(), 1);
174 171
175 let fields = [("csrf", CSRF), ("id", own_key.id.as_str())];172 let fields = [("csrf", CSRF), ("id", own_key.id.as_str())];
176- let reply = call(173+ let reply = send(
177- &site,174+ &site.router,
178 "POST",175 "POST",
179 "/settings/gpg/delete",176 "/settings/gpg/delete",
180 Some(&cookie),177 Some(&cookie),
crates/forge-web-app/src/ci/api_tests.rsmodified+1 -1
@@ -1123,7 +1123,7 @@ async fn runner_binary_needs_runner_auth_and_self_update() {
1123 let (_, secret) = runner(&env, &[]).await;1123 let (_, secret) = runner(&env, &[]).await;
1124 let uri = "/api/v1/ci/runners/binary";1124 let uri = "/api/v1/ci/runners/binary";
1125 1125
1126- let sent = send(&env.router, "GET", uri, &[], Vec::new()).await;1126+ let sent = crate::test_support::fixture::send(&env.router, "GET", uri, None, None).await;
1127 assert_eq!(sent.status, 401);1127 assert_eq!(sent.status, 401);
1128 let sent = send(&env.router, "GET", uri, &[bearer(&secret)], Vec::new()).await;1128 let sent = send(&env.router, "GET", uri, &[bearer(&secret)], Vec::new()).await;
1129 assert_eq!(sent.status, 404);1129 assert_eq!(sent.status, 404);
crates/forge-web-app/src/lfs/route_tests.rsmodified+3 -3
@@ -237,12 +237,12 @@ async fn public_reads_need_no_credentials_and_private_ones_get_the_challenge() {
237 .await;237 .await;
238 assert_eq!(batch.status, 401);238 assert_eq!(batch.status, 401);
239 assert_eq!(batch.headers["lfs-authenticate"], "Basic realm=\"forge\"");239 assert_eq!(batch.headers["lfs-authenticate"], "Basic realm=\"forge\"");
240- let get = send(240+ let get = crate::test_support::fixture::send(
241 &private.router,241 &private.router,
242 "GET",242 "GET",
243 &objects_uri(&format!("/{oid}")),243 &objects_uri(&format!("/{oid}")),
244- &[],244+ None,
245- Vec::new(),245+ None,
246 )246 )
247 .await;247 .await;
248 assert_eq!(get.status, 401);248 assert_eq!(get.status, 401);
crates/forge-web-repo/src/pages/browse_tests.rsmodified+2 -9
@@ -114,15 +114,8 @@ async fn scenario_split_view(fx: &Fixture) {
114 assert!(cookie.starts_with("forge_diff=split"));114 assert!(cookie.starts_with("forge_diff=split"));
115 115
116 let plain = format!("/{OWNER}/{REPO}/commit/{}", fx.modified);116 let plain = format!("/{OWNER}/{REPO}/commit/{}", fx.modified);
117- let req = Request::builder()117+ let (_, _, html) = send(&fx.router, "GET", &plain, Some("forge_diff=split"), &[]).await;
118- .method("GET")118+ assert!(html.contains("diff-split-row"));
119- .uri(&plain)
120- .header("cookie", "forge_diff=split")
121- .body(Body::empty())
122- .unwrap();
123- let res = fx.router.handle(req).await;
124- let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
125- assert!(String::from_utf8_lossy(&bytes).contains("diff-split-row"));
126 let (_, _, body) = get(&fx.router, &format!("{plain}?view=unified")).await;119 let (_, _, body) = get(&fx.router, &format!("{plain}?view=unified")).await;
127 assert!(!String::from_utf8(body).unwrap().contains("diff-split-row"));120 assert!(!String::from_utf8(body).unwrap().contains("diff-split-row"));
128 }121 }
crates/forge-web-repo/src/pages/repo_settings_live_tests.rsmodified+10 -8
@@ -7,6 +7,7 @@ use topcoat::router::{Body, Router};
7 7
8 use crate::auth::SESSION_COOKIE;8 use crate::auth::SESSION_COOKIE;
9 use crate::live::{LiveHub, Topic};9 use crate::live::{LiveHub, Topic};
10+use crate::test_support::fixture::send_form;
10 11
11 const CSRF: &str = "settings-live-test-csrf";12 const CSRF: &str = "settings-live-test-csrf";
12 13
@@ -47,14 +48,15 @@ async fn get(site: &Site, uri: &str, cookie: Option<&str>) -> topcoat::router::r
47 }48 }
48 49
49 async fn post_form(site: &Site, uri: &str, cookie: &str, form: &str) -> u16 {50 async fn post_form(site: &Site, uri: &str, cookie: &str, form: &str) -> u16 {
50- let request = Request::builder()51+ send_form(
51- .method("POST")52+ &site.router,
52- .uri(uri)53+ "POST",
53- .header("cookie", cookie)54+ uri,
54- .header("content-type", "application/x-www-form-urlencoded")55+ Some(cookie),
55- .body(Body::from(form.to_owned()))56+ Some(form.to_owned()),
56- .expect("request");57+ )
57- site.router.handle(request).await.status().as_u16()58+ .await
59+ .status
58 }60 }
59 61
60 async fn fixture(site: &Site) -> (String, String) {62 async fn fixture(site: &Site) -> (String, String) {
crates/forge-web-repo/src/pages/security_tab_tests.rsmodified+34 -20
@@ -1,10 +1,10 @@
1 use std::sync::Arc;1 use std::sync::Arc;
2 2
3 use forge_core::{Role, Store, Visibility};3 use forge_core::{Role, Store, Visibility};
4-use topcoat::router::request::Request;4+use topcoat::router::Router;
5-use topcoat::router::{Body, Router, to_bytes};
6 5
7 use crate::auth::SESSION_COOKIE;6 use crate::auth::SESSION_COOKIE;
7+use crate::test_support::fixture::{Reply, send};
8 8
9 const SECURITY_TAB: &str = "href=\"/owner/proj/security\"";9 const SECURITY_TAB: &str = "href=\"/owner/proj/security\"";
10 const CSRF: &str = "security-tab-test-csrf";10 const CSRF: &str = "security-tab-test-csrf";
@@ -35,20 +35,6 @@ async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
35 format!("__Host-{SESSION_COOKIE}={token}")35 format!("__Host-{SESSION_COOKIE}={token}")
36 }36 }
37 37
38-async fn get(site: &Site, uri: &str, cookie: Option<&str>) -> (u16, String) {
39- let mut builder = Request::builder().method("GET").uri(uri);
40- if let Some(cookie) = cookie {
41- builder = builder.header("cookie", cookie);
42- }
43- let res = site
44- .router
45- .handle(builder.body(Body::from(String::new())).expect("request"))
46- .await;
47- let status = res.status().as_u16();
48- let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
49- (status, String::from_utf8_lossy(&bytes).into_owned())
50-}
51-
52 async fn fixture(site: &Site) -> (String, String) {38 async fn fixture(site: &Site) -> (String, String) {
53 let owner = site39 let owner = site
54 .store40 .store
@@ -74,7 +60,14 @@ async fn security_tab_follows_the_role_while_advisories_are_on() {
74 let site = site(true).await;60 let site = site(true).await;
75 let (owner_cookie, reader_cookie) = fixture(&site).await;61 let (owner_cookie, reader_cookie) = fixture(&site).await;
76 62
77- let (status, body) = get(&site, "/owner/proj/issues", Some(&owner_cookie)).await;63+ let Reply { status, body, .. } = send(
64+ &site.router,
65+ "GET",
66+ "/owner/proj/issues",
67+ Some(&owner_cookie),
68+ None,
69+ )
70+ .await;
78 assert_eq!(status, 200, "owner page");71 assert_eq!(status, 200, "owner page");
79 assert!(72 assert!(
80 body.contains(SECURITY_TAB),73 body.contains(SECURITY_TAB),
@@ -98,14 +91,28 @@ async fn security_tab_follows_the_role_while_advisories_are_on() {
98 .await91 .await
99 .unwrap();92 .unwrap();
100 let writer_cookie = sign_in(&site.store, &writer.id, "writer-token").await;93 let writer_cookie = sign_in(&site.store, &writer.id, "writer-token").await;
101- let (status, body) = get(&site, "/owner/proj/issues", Some(&writer_cookie)).await;94+ let Reply { status, body, .. } = send(
95+ &site.router,
96+ "GET",
97+ "/owner/proj/issues",
98+ Some(&writer_cookie),
99+ None,
100+ )
101+ .await;
102 assert_eq!(status, 200, "writer page");102 assert_eq!(status, 200, "writer page");
103 assert!(103 assert!(
104 body.contains(SECURITY_TAB),104 body.contains(SECURITY_TAB),
105 "a Write collaborator should see the tab"105 "a Write collaborator should see the tab"
106 );106 );
107 107
108- let (status, body) = get(&site, "/owner/proj/issues", Some(&reader_cookie)).await;108+ let Reply { status, body, .. } = send(
109+ &site.router,
110+ "GET",
111+ "/owner/proj/issues",
112+ Some(&reader_cookie),
113+ None,
114+ )
115+ .await;
109 assert_eq!(status, 200, "reader page");116 assert_eq!(status, 200, "reader page");
110 assert!(117 assert!(
111 !body.contains(SECURITY_TAB),118 !body.contains(SECURITY_TAB),
@@ -117,7 +124,14 @@ async fn security_tab_follows_the_role_while_advisories_are_on() {
117 async fn security_tab_is_hidden_when_advisories_are_off() {124 async fn security_tab_is_hidden_when_advisories_are_off() {
118 let site = site(false).await;125 let site = site(false).await;
119 let (owner_cookie, _) = fixture(&site).await;126 let (owner_cookie, _) = fixture(&site).await;
120- let (status, body) = get(&site, "/owner/proj/issues", Some(&owner_cookie)).await;127+ let Reply { status, body, .. } = send(
128+ &site.router,
129+ "GET",
130+ "/owner/proj/issues",
131+ Some(&owner_cookie),
132+ None,
133+ )
134+ .await;
121 assert_eq!(status, 200);135 assert_eq!(status, 200);
122 assert!(136 assert!(
123 !body.contains(SECURITY_TAB),137 !body.contains(SECURITY_TAB),