use core::str;
use crate::{
command::{Command, CommandLevel},
error::Result,
permission::PermissionLevel,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SetMinerTargetFreq {
pub freq: i32,
}
impl SetMinerTargetFreq {
pub const fn new(freq: i32) -> Self {
Self { freq }
}
}
impl Command for SetMinerTargetFreq {
type Response = String;
const CMD_NAME: &'static str = "set.miner.target_freq";
const LEVEL: CommandLevel = CommandLevel::Secured;
const MINIMAL_PERMISSIONS: PermissionLevel = PermissionLevel::ReadWrite;
fn params(&self) -> Result<Option<impl serde::Serialize>> {
Ok(Some(self.freq))
}
}
#[cfg(test)]
mod tests {
use crate::account::Account;
use crate::auth_data::AuthData;
use super::*;
const RESPONSE_JSON: &str =
r#"{"code":0,"when":1692685512,"msg":"ok","desc":"set.miner.target_freq"}"#;
#[test]
fn request_has_param() {
let cmd = SetMinerTargetFreq::new(78);
assert!(cmd.is_secured());
assert!(!cmd.is_encrypted());
let auth = AuthData::new::<SetMinerTargetFreq>(Account::Super, "pass", "salt").unwrap();
let encoded = cmd.encode(Some(auth)).unwrap();
let json: serde_json::Value = serde_json::from_slice(&encoded.0).unwrap();
assert_eq!(json["cmd"], "set.miner.target_freq");
assert_eq!(json["param"], 78);
assert_eq!(json["account"], "super");
assert!(json["ts"].as_u64().unwrap() > 0);
assert_eq!(json["token"].as_str().unwrap().len(), 8);
}
#[test]
fn request_negative_value() {
let cmd = SetMinerTargetFreq::new(-50);
let auth = AuthData::new::<SetMinerTargetFreq>(Account::Super, "pass", "salt").unwrap();
let encoded = cmd.encode(Some(auth)).unwrap();
let json: serde_json::Value = serde_json::from_slice(&encoded.0).unwrap();
assert_eq!(json["param"], -50);
}
#[test]
fn request_without_auth_omits_token() {
let cmd = SetMinerTargetFreq::new(50);
let encoded = cmd.encode(None).unwrap();
let json: serde_json::Value = serde_json::from_slice(&encoded.0).unwrap();
assert!(json.get("token").is_none());
assert_eq!(json["param"], 50);
}
#[test]
fn deserialize_response_fixture() {
let response = SetMinerTargetFreq::parse_response(RESPONSE_JSON.as_bytes()).unwrap();
assert!(response.code.is_success());
assert_eq!(response.desc, "set.miner.target_freq");
assert_eq!(response.when, 1692685512);
assert_eq!(response.msg, "ok");
}
}