use core::str;
use serde::Deserialize;
use crate::{error::Result, permission::PermissionLevel, request::Request};
#[derive(Debug, Default, Clone, Copy)]
pub struct GetLogDownload;
impl GetLogDownload {
pub const CMD_NAME: &'static str = "get.log.download";
pub const MINIMAL_PERMISSIONS: PermissionLevel = PermissionLevel::ReadOnly;
pub fn encode_request() -> Result<Vec<u8>> {
let req = Request::new(Self::CMD_NAME, None, None::<()>);
Ok(serde_json::to_vec(&req)?)
}
}
fn deserialize_u64_from_string<'de, D>(deserializer: D) -> std::result::Result<u64, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
let s = String::deserialize(deserializer)?;
s.parse::<u64>().map_err(serde::de::Error::custom)
}
#[derive(Debug, Default, Deserialize)]
pub struct GetLogDownloadResponse {
#[serde(deserialize_with = "deserialize_u64_from_string")]
pub logsize: u64,
}
#[cfg(test)]
mod tests {
use super::*;
const RESPONSE_JSON: &str =
r#"{"code":0,"when":1672281726,"msg":{"logsize":"12345"},"desc":"get.log.download"}"#;
#[test]
fn request_no_params_no_auth() {
let bytes = GetLogDownload::encode_request().unwrap();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(json["cmd"], "get.log.download");
assert!(json.get("param").is_none());
assert!(json.get("token").is_none());
}
#[test]
fn deserialize_response_fixture() {
let response: crate::response::Response<GetLogDownloadResponse> =
serde_json::from_str(RESPONSE_JSON).unwrap();
assert!(response.code.is_success());
assert_eq!(response.desc, "get.log.download");
assert_eq!(response.when, 1672281726);
assert_eq!(response.msg.logsize, 12345);
}
#[test]
fn deserialize_u64_from_string_helper() {
#[derive(Deserialize)]
struct Wrapper {
#[serde(deserialize_with = "deserialize_u64_from_string")]
value: u64,
}
let json = r#"{"value":"9876543210"}"#;
let w: Wrapper = serde_json::from_str(json).unwrap();
assert_eq!(w.value, 9876543210);
}
}