matroskin 0.1.0

whatsminer api client lib
Documentation
//! Implement `set.system.hostname` command
//!
//! Sets the device's hostname. The new configuration takes effect
//! after a system restart.
//!
//! - Command: [SetSystemHostname]
//! - ApiDoc: <https://apidoc.whatsminer.com/#api-System-system_set_hostname>
use core::str;

use serde::Serialize;

use crate::{
    command::{Command, CommandLevel},
    error::Result,
};

/// This command represents the `set.system.hostname` operation.
///
/// Sets the device's hostname. The new configuration takes effect
/// after a system restart.
///
/// - ApiDoc: <https://apidoc.whatsminer.com/#api-System-system_set_hostname>
///
/// # Example
/// ```rust,no_run
/// use matroskin::actor::Actor;
/// use matroskin::account::Account;
/// use matroskin::password::Password;
/// use matroskin::command::set_system_hostname::SetSystemHostname;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let actor = Actor::new("1.1.1.1:4433", Account::Super, Password::Super);
///     actor.connect()?;
///
///     let cmd = SetSystemHostname::new("WhatsMiner-Dev");
///     let res = actor.send(cmd).await?;
///     println!("res: {:#?}", res);
///     Ok(())
/// }
/// ```
#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
pub struct SetSystemHostname {
    /// The new hostname for the device.
    pub hostname: String,
}

impl SetSystemHostname {
    /// Create a new `set.system.hostname` command.
    pub fn new(hostname: impl Into<String>) -> Self {
        Self {
            hostname: hostname.into(),
        }
    }
}

impl Command for SetSystemHostname {
    type Response = String;
    const CMD_NAME: &'static str = "set.system.hostname";
    const LEVEL: CommandLevel = CommandLevel::Secured;
    fn params(&self) -> Result<Option<impl serde::Serialize>> {
        Ok(Some(self))
    }
}

#[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.system.hostname"}"#;

    #[test]
    fn request_has_hostname_param() {
        let cmd = SetSystemHostname::new("WhatsMiner-Dev");
        assert!(cmd.is_secured());
        assert!(!cmd.is_encrypted());

        let auth = AuthData::new::<SetSystemHostname>(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.system.hostname");
        assert_eq!(json["account"], "super");
        assert!(json["ts"].as_u64().unwrap() > 0);
        assert_eq!(json["token"].as_str().unwrap().len(), 8);
        assert_eq!(json["param"]["hostname"], "WhatsMiner-Dev");
    }

    #[test]
    fn request_without_auth_returns_no_token() {
        let cmd = SetSystemHostname::new("test");
        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"]["hostname"], "test");
    }

    #[test]
    fn deserialize_response_fixture() {
        let response = SetSystemHostname::parse_response(RESPONSE_JSON.as_bytes()).unwrap();
        assert!(response.code.is_success());
        assert_eq!(response.desc, "set.system.hostname");
        assert_eq!(response.when, 1692685512);
        assert_eq!(response.msg, "ok");
    }
}