Skip to content

Commit 6cb7b98

Browse files
authored
tests: don't base64 encode text/plain request payloads when recording (#6603)
In #6326, `text/plain` request payloads were decoded into... well, plain text, and `record::replay_http` was updated to handle them accordingly. The code that records those request payloads was not updated, however, so any updated test payload will now result in failures, since a base64 encoded string will be compared against a plain text string. This adds the same logic to `record::record_http` to ensure newly recorded cassettes match.
1 parent e389cb6 commit 6cb7b98

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

src/tests/record.rs

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use std::{
1414
use base64::{engine::general_purpose, Engine};
1515
use futures_channel::oneshot;
1616
use futures_util::future;
17-
use http::header::CONTENT_TYPE;
17+
use http::{header::CONTENT_TYPE, HeaderMap, HeaderValue};
1818
use hyper::{
1919
body::to_bytes, server::conn::AddrStream, Body, Error, Request, Response, Server, StatusCode,
2020
Uri,
@@ -278,7 +278,11 @@ async fn record_http(req: Request<Body>, client: Client) -> Result<ResponseAndEx
278278
.filter(|h| !IGNORED_HEADERS.contains(&h.0.as_str()))
279279
.map(|h| (h.0.as_str().to_string(), h.1.to_str().unwrap().to_string()))
280280
.collect(),
281-
body: general_purpose::STANDARD.encode(&body),
281+
body: if is_plain_text(&headers) {
282+
String::from_utf8_lossy(&body).into()
283+
} else {
284+
general_purpose::STANDARD.encode(&body)
285+
},
282286
};
283287

284288
let (status, headers, body) = if let Ok("passthrough") = dotenvy::var("RECORD").as_deref() {
@@ -366,18 +370,14 @@ fn replay_http(
366370
async {
367371
let _ = &exchange;
368372

369-
let content_type = req.headers().get(CONTENT_TYPE).cloned();
370-
373+
let plain_text = is_plain_text(req.headers());
371374
let body = to_bytes(req.into_body()).await.unwrap();
372-
match content_type {
373-
Some(t) if t == "text/plain" => {
374-
let body = String::from_utf8_lossy(&body);
375-
assert_eq!(body, exchange.request.body);
376-
}
377-
_ => {
378-
let body = general_purpose::STANDARD.encode(body);
379-
assert_eq!(body, exchange.request.body);
380-
}
375+
if plain_text {
376+
let body = String::from_utf8_lossy(&body);
377+
assert_eq!(body, exchange.request.body);
378+
} else {
379+
let body = general_purpose::STANDARD.encode(body);
380+
assert_eq!(body, exchange.request.body);
381381
}
382382

383383
let mut builder = Response::builder();
@@ -394,3 +394,12 @@ fn replay_http(
394394
Ok(response)
395395
}
396396
}
397+
398+
fn is_plain_text(headers: &HeaderMap<HeaderValue>) -> bool {
399+
if let Some(header_value) = headers.get(CONTENT_TYPE) {
400+
if let Ok(value) = header_value.to_str() {
401+
return value == "text/plain";
402+
}
403+
}
404+
false
405+
}

0 commit comments

Comments
 (0)