Last active
December 26, 2022 19:18
-
-
Save simanacci/67c2f5a096e1db2012503cc7133c25f0 to your computer and use it in GitHub Desktop.
Mock HN API Request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The test | |
let body = format!( | |
r#" | |
{{ | |
"about" : "This is a test {}", | |
"created" : 1173923446, | |
"delay" : 0, | |
"id" : {}, | |
"karma" : 2937, | |
"submitted" : [ 8265435, 8168423, 4289 ] | |
}} | |
"#, | |
hex, new_hn_username | |
); | |
let mock_server = MockServer::start().await; | |
let template = ResponseTemplate::new(200).set_body_raw(body, "application/json"); | |
let hnpath = format!( | |
"{}/v0/user/{}.json?print=pretty", mock_server.uri(), | |
new_hn_username | |
); | |
Mock::given(method("GET")) | |
.and(matchers::path(&hnpath)) | |
.respond_with(template) | |
.mount(&mock_server) | |
.await; | |
let req = test::TestRequest::post() | |
.uri(&format!("/verify-hn/{}", hex)) | |
.set_form(data) | |
.cookie(cookie) | |
.to_request(); | |
let resp = test::call_service(&app, req).await; | |
assert_eq!(resp.status(), StatusCode::FOUND); | |
// Handler that's being tested /verify-hn/jsliufliflifyeg9879 | |
pub async fn change_hn_username() -> HttpResult { | |
match form.hex.is_some() { | |
let result = user | |
.0 | |
.claim(&pool, redis, config, form) <--- // Function below | |
.await?; | |
} | |
} | |
// Function where HN API is accessed | |
pub async fn claim() -> Result<(bool, Option<String>), CustomError> { | |
let templ_str = &config.user_url; // <---- https://hacker-news.firebaseio.com/v0/user/{username}.json?print=pretty | |
let templ = new_string_template::template::Template::new(templ_str); | |
let mut map = HashMap::new(); | |
map.insert("username", new_hn_username.as_ref().unwrap()); | |
let rendered = templ.render(&map).expect("Expected Result to be Ok"); | |
println!("{:?}", rendered); | |
let map = reqwest::get(&rendered) // <--- This is never mocked. | |
.await? | |
.json::<extractor::User>() | |
.await | |
.ok(); | |
println!("{:?}", map); // <---- None during tests. It's fetching from firebaseio.com | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment