taubyte_sdk/http/client/
new.rs

1use super::{imports, Client};
2use crate::errno::Error;
3
4fn new_client(id: *mut u32) -> Error {
5    #[allow(unused_unsafe)]
6    unsafe {
7        imports::newHttpClient(id)
8    }
9}
10
11impl Client {
12    pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
13        let mut id: u32 = 0;
14        let err0 = new_client(&mut id);
15        if err0.is_err() {
16            Err(format!("Creating client failed with: {}", err0).into())
17        } else {
18            Ok(Client { id: id })
19        }
20    }
21}
22
23// TODO split out as unit tests and mocks
24#[cfg(test)]
25pub mod test {
26    use std::io::Read;
27
28    use crate::http::Client;
29    pub static CLIENT_ID: u32 = 1;
30    pub static REQUEST_ID: u32 = 2;
31    pub static METHOD_ID: u32 = 1;
32
33    pub static HEADER_KEY: &str = "content-type";
34    pub static HEADER_VALUE: &str = "application/json";
35    pub static SEND_URL: &str = "https://google.com/";
36    pub static RESPONSE_BODY: &str = "Hello, world!";
37
38    #[test]
39    fn test_client() {
40        let client = Client::new().unwrap_or_else(|err| {
41            panic!("Creating client failed with: {}", err);
42        });
43
44        assert_eq!(client.id, CLIENT_ID);
45
46        let request = http::Request::builder()
47            .header(HEADER_KEY, HEADER_VALUE)
48            .uri(SEND_URL);
49
50        let mut response = client.send_without_body(request).unwrap_or_else(|err| {
51            panic!("Sending request failed with: {}", err);
52        });
53
54        // handle response
55        let mut buffer = String::new();
56        let err = response.read_to_string(&mut buffer);
57        if err.is_err() {
58            panic!("Reading response failed with: {}", err.err().unwrap());
59        }
60
61        assert_eq!(buffer, RESPONSE_BODY)
62    }
63
64    #[test]
65    fn test_get() {
66        let mut response = Client::get(SEND_URL).unwrap_or_else(|err| {
67            panic!("Sending request failed with: {}", err);
68        });
69
70        // handle response
71        let mut buffer = String::new();
72        let err = response.read_to_string(&mut buffer);
73        if err.is_err() {
74            panic!("Reading response failed with: {}", err.err().unwrap());
75        }
76
77        assert_eq!(buffer, RESPONSE_BODY)
78    }
79}