Skip to content

Commit

Permalink
test: CORS preflight
Browse files Browse the repository at this point in the history
  • Loading branch information
jondot committed Nov 22, 2024
1 parent eb622b0 commit e553e23
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/controller/middleware/cors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,49 @@ mod tests {
);
}

#[tokio::test]
async fn cors_options() {
let mut middleware = Cors::empty();
middleware.allow_origins = vec![
"http://localhost:8080".to_string(),
"http://example.com".to_string(),
];

let app = Router::new().route("/", get(|| async {}));
let app = middleware
.apply(app)
.expect("apply middleware")
.with_state(tests_cfg::app::get_app_context().await);

let req = Request::builder()
.uri("/")
.header("Origin", "http://example.com")
.method(Method::OPTIONS)
.body(Body::empty())
.expect("request");

let response = app.oneshot(req).await.expect("valid response");

assert_debug_snapshot!(
format!("cors_OPTIONS_[allow_origins]"),
(
format!(
"access-control-allow-origin: {:?}",
response.headers().get("access-control-allow-origin")
),
format!("vary: {:?}", response.headers().get("vary")),
format!(
"access-control-allow-methods: {:?}",
response.headers().get("access-control-allow-methods")
),
format!(
"access-control-allow-headers: {:?}",
response.headers().get("access-control-allow-headers")
),
format!("allow: {:?}", response.headers().get("allow")),
)
);
}
#[test]
fn should_be_disabled() {
let middleware = Cors::default();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
source: src/controller/middleware/cors.rs
expression: "(format!(\"access-control-allow-origin: {:?}\",\nresponse.headers().get(\"access-control-allow-origin\")),\nformat!(\"vary: {:?}\", response.headers().get(\"vary\")),\nformat!(\"access-control-allow-methods: {:?}\",\nresponse.headers().get(\"access-control-allow-methods\")),\nformat!(\"access-control-allow-headers: {:?}\",\nresponse.headers().get(\"access-control-allow-headers\")),\nformat!(\"allow: {:?}\", response.headers().get(\"allow\")),)"
snapshot_kind: text
---
(
"access-control-allow-origin: Some(\"http://example.com\")",
"vary: Some(\"origin, access-control-request-method, access-control-request-headers\")",
"access-control-allow-methods: Some(\"*\")",
"access-control-allow-headers: Some(\"*\")",
"allow: Some(\"GET,HEAD\")",
)

0 comments on commit e553e23

Please sign in to comment.