Making requests

To make GET requests, we will use the test_get function, which creates a Client of the reqwest crate, sets a path, executes a send request, and deserializes the response from JSON:

fn test_get<T>(path: &str) -> T
where
T: for <'de> Deserialize<'de>,
{
let client = Client::new();
let data = client.get(&test_url(path))
.send()
.unwrap()
.text()
.unwrap();
serde_json::from_str(&data).unwrap()
}

If you are familiar with the reqwest crate, you may ask why we get text values, since Client has the json method that deserializes JSON? If we do that, we can't see the original value if we have deserialization issues, but using the original text of a response, we can log it for investigation.

To generate URLs, we use the following function:

fn test_url(path: &str) -> String {
format!("http://127.0.0.1:8080/api{}", path)
}

This adds the address of a server to which we bind it, but for large projects, it's better to use dynamic addresses, especially if you want to use a fresh server instance in every test.

For POST requests, we will use similar method, but we won't deserialize the result because we don't need it and will check the status of a response only:

fn test_post<T>(path: &str, data: &T)
where
T: Serialize,
{
setup();
let client = Client::new();
let resp = client.post(&test_url(path))
.form(data)
.send()
.unwrap();
let status = resp.status();
assert!(status.is_success());
}

We have all the necessary functions to implement unit tests for every handler.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.226.255