0

I'm currently trying to test an API endpoint using actix-web and reqwest.

I can insert some records (using sqlx), and then make the request and check it returned a 200 HTTP status, and corroborate that the returned data belongs to the user created - the endpoint returned what's expected. But, doing so it's "order dependent", otherwise I receive the following error:

borrow of moved value: response
value borrowed here after move rustc(E0382)

This is what gives the error:

let inserted_user = sqlx::query!(
    r#"
    INSERT INTO users (name)
    VALUES ($1)
    RETURNING id
    "#,
    String::from("john"),
)
.fetch_one(&app.db_pool)
.await
.unwrap();

let response = client
    .get(&format!("{}/", &app.address))
    .send()
    .await?;

let users: Vec<User> = response.json().await?;
assert_eq!(inserted_user.id, users[0].id);
assert!(response.status().is_success());

If I swap the order of the assertion on response.status(), with the assert_eq! it works. But I think isn't the best way, as it should be explicitly stated, with comments or further knowledge that this work in this specific way.

Is there I can do to avoid relying on the order of the assertions if I can't clone a reqwest response? Or how could I clone it?

1 Answers1

3

To be honest, I think the assertion makes more sense right after you get the response. Why are you parsing the response and only then asserting that the response was even OK? If the response wasn't OK in the first place, the parsing will most likely fail anyway and you wouldn't even reach the assertion, wouldn't it?

But if you really want to do the assertion at that point, you can just put response.status() into a temporary before consuming the response:

let status = respons.status();
let users: Vec<User> = response.json().await?;
assert_eq!(inserted_user.id, users[0].id);
assert!(status.is_success());
isaactfa
  • 5,461
  • 1
  • 10
  • 24
  • The answer works, thank you. And yes, you're right, maybe the status checking is superfluous, but, strictly speaking nothing forbids me on returning any other HTTP status code even while I'm returning also the expected JSON body, isn't it? This way the status code assertion would make more sense? – Johann Esburgo Jul 12 '21 at 08:12
  • No, nothing stops you from returning a json body with a 404 status code, but the question is, why would you try to parse the response if it wasn't successful? Even if it is valid json, you're just gonna throw it away once the assertion panics. I would check if the status was OK with a conditional, parse the response if it was, and return an error if it wasn't. (Oh and if the answer works you can acdept it so other people will see it as well) – isaactfa Jul 12 '21 at 08:22