http-request-zabbix 0.2.1

A Rust client library for the Zabbix API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! A Rust library for interacting with the Zabbix API.
//!
//! This crate provides a convenient and idiomatic way to communicate with a Zabbix server,
//! handling authentication, version checking, and raw API requests.
//!
//! # Example
//!
//! ```no_run
//! use http_request_zabbix::{ZabbixInstance, AuthType};
//!
//! let zabbix = ZabbixInstance::builder("http://zabbix.example.com/zabbix")
//!     .build()
//!     .unwrap()
//!     .login(AuthType::UsernamePassword("Admin".to_string(), "zabbix".to_string()))
//!     .unwrap();
//!
//! println!("Zabbix Version: {}", zabbix.get_version().unwrap());
//! ```

use reqwest::blocking::Client;
use semver::{Version, VersionReq};
use serde_json::Value;
use thiserror::Error;
use uuid::Uuid;

/// Enum representing the type of authentication to use.
///
/// # Examples
///
/// ```no_run
/// use http_request_zabbix::AuthType;
///
/// let auth_type = AuthType::UsernamePassword("Admin".to_string(), "zabbix".to_string());
/// ```
///
/// ```no_run
/// use http_request_zabbix::AuthType;
///
/// let auth_type = AuthType::Token("817dc89d0ae1d347fbcacdd6c00f322d0ec0651a8df60115304216dc768205db".to_string());
/// ```
pub enum AuthType {
    /// Token authentication.
    /// Use it if you have a token from Zabbix. More info: https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/users/api_tokens  
    Token(String),
    /// Username and password authentication.
    /// Use it if you have a username and password for Zabbix.
    UsernamePassword(String, String),
}

/// An enum representing the types of parameters that can be passed to the Zabbix API.
///
/// # Examples
///
/// ```no_run
/// use http_request_zabbix::{ApiRequestParams, AuthType, ZabbixInstance};
///
/// let params_json = ApiRequestParams::from(serde_json::json!({"output": ["host", "name"], "limit": 1}));
/// let params_string = ApiRequestParams::from("{\"output\": [\"host\", \"name\"], \"limit\": 1}");
/// ```
pub enum ApiRequestParams {
    /// A raw pre-parsed JSON Value.
    Json(Value),
    /// A raw JSON string.
    String(String),
}

impl From<Value> for ApiRequestParams {
    fn from(v: Value) -> Self {
        ApiRequestParams::Json(v)
    }
}

impl From<&str> for ApiRequestParams {
    fn from(s: &str) -> Self {
        ApiRequestParams::String(s.to_string())
    }
}

impl From<String> for ApiRequestParams {
    fn from(s: String) -> Self {
        ApiRequestParams::String(s)
    }
}

/// Error type for Zabbix interactions.
///
/// # Errors
///
/// This method will return a `ZabbixError` if:
/// * The provided URL is invalid or unreachable (`ZabbixError::Network`).
/// * The server responds with invalid JSON (`ZabbixError::Json`).
/// * The server returns a version string that cannot be parsed by semantic versioning rules (`ZabbixError::VersionParse`).
/// * The server returns an API error (`ZabbixError::ApiError`). If future Zabbix versions return a different error format, this enum variant may need to be updated.
#[derive(Error, Debug)]
pub enum ZabbixError {
    #[error("Network error: {0}")]
    Network(#[from] reqwest::Error),
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("Version parse error: {0}")]
    VersionParse(#[from] semver::Error),
    #[error("Zabbix API Error: {message} {data}")]
    ApiError { message: String, data: String },
    #[error("Unknown error: {0}")]
    Other(String),
}

/// Represents an active connection to a Zabbix server.
pub struct ZabbixInstance {
    id: String,
    url: String,
    token: String,
    request_client: Client,
    need_auth_in_body: bool,
    version: String,
    need_logout: bool,
}

impl ZabbixInstance {
    /// Creates a new `ZabbixInstanceBuilder` to configure the connection.
    ///
    /// The URL should be the base URL of the Zabbix server, without the `/api_jsonrpc.php` suffix.
    ///
    /// # Examples
    ///
    /// ```
    /// use http_request_zabbix::ZabbixInstance;
    ///
    /// let builder = ZabbixInstance::builder("http://localhost/zabbix");
    /// ```
    pub fn builder(url: &str) -> ZabbixInstanceBuilder {
        ZabbixInstanceBuilder::new(url)
    }
}

/// A builder for creating a `ZabbixInstance`.
pub struct ZabbixInstanceBuilder {
    url: String,
    accept_invalid_certs: bool,
    client: Option<Client>,
    need_auth_in_body: bool,
    version: String,
}

impl ZabbixInstanceBuilder {
    /// Creates a new builder with the given Zabbix URL.
    ///
    /// The URL should be the base URL of the Zabbix server, without the `/api_jsonrpc.php` suffix.
    ///
    /// # Examples
    ///
    /// ```
    /// use http_request_zabbix::ZabbixInstance;
    ///
    /// let builder = ZabbixInstance::builder("http://localhost/zabbix");
    /// ```
    pub fn new(url: &str) -> Self {
        Self {
            url: url.to_string(),
            accept_invalid_certs: false,
            client: None,
            need_auth_in_body: false,
            version: "".to_string(),
        }
    }

    /// Configures whether the client should verify the server's TLS certificates.
    ///
    /// Setting this to `true` is dangerous and should only be used for testing
    /// or when using self-signed certificates in a trusted environment.
    ///
    /// # Examples
    ///
    /// ```
    /// use http_request_zabbix::ZabbixInstance;
    ///
    /// let builder = ZabbixInstance::builder("http://localhost/zabbix/api_jsonrpc.php")
    ///     .danger_accept_invalid_certs(true);
    /// ```
    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
        self.accept_invalid_certs = accept;
        self
    }

    /// Builds the `ZabbixInstance` by connecting to the server and verifying the API version.
    ///
    /// This method will make an initial unauthenticated request to the Zabbix server
    /// to determine its version (using `apiinfo.version`). This is required because
    /// Zabbix >= 6.4 changed the authentication flow (using Bearer tokens instead of
    /// passing auth in the request body).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use http_request_zabbix::ZabbixInstance;
    ///
    /// let zabbix_result = ZabbixInstance::builder("http://zabbix.example.com/api_jsonrpc.php")
    ///     .danger_accept_invalid_certs(true)
    ///     .build();
    ///     
    /// assert!(zabbix_result.is_ok());
    /// ```
    pub fn build(mut self) -> Result<Self, ZabbixError> {
        let client = Client::builder()
            .danger_accept_invalid_certs(self.accept_invalid_certs)
            .build()?;

        let v6_4_req = VersionReq::parse(">=6.4")?;

        let version_str_raw = ZabbixInstance::zabbix_raw_request(
            &client,
            &self.url,
            "apiinfo.version",
            serde_json::json!([]),
            "",
            false,
        )?;
        let version_str = version_str_raw.trim_matches('"');

        let current_v = Version::parse(version_str)?;

        self.need_auth_in_body = !(v6_4_req.matches(&current_v));

        self.client = Some(client);

        self.version = version_str.to_string();

        Ok(self)
    }

    /// Logs in to the Zabbix server using the provided authentication type.
    ///
    /// # Arguments
    ///
    /// * `auth_type` - The authentication type to use for logging in.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use http_request_zabbix::{ZabbixInstance, AuthType};
    ///
    /// let auth_type = AuthType::UsernamePassword("Admin".to_string(), "zabbix".to_string());
    ///
    /// let zabbix = ZabbixInstance::builder("http://zabbix.example.com/zabbix")
    ///     .build()
    ///     .unwrap()
    ///     .login(auth_type)
    ///     .unwrap();
    /// ```
    ///
    /// ```no_run
    /// use http_request_zabbix::{ZabbixInstance, AuthType};
    ///
    /// let auth_type = AuthType::Token("817dc89d0ae1...".to_string());
    ///
    /// let zabbix = ZabbixInstance::builder("http://zabbix.example.com/zabbix")
    ///     .build()
    ///     .unwrap()
    ///     .login(auth_type)
    ///     .unwrap();
    /// ```
    pub fn login(self, auth_type: AuthType) -> Result<ZabbixInstance, ZabbixError> {
        match auth_type {
            AuthType::Token(token) => self.login_with_token(token),
            AuthType::UsernamePassword(username, password) => {
                self.login_with_username_password(username, password)
            }
        }
    }

    fn login_with_token(self, token: String) -> Result<ZabbixInstance, ZabbixError> {
        let client = self.client.ok_or_else(|| {
            ZabbixError::Other("Client not initialized. Did you call build()?".to_string())
        })?;

        match ZabbixInstance::zabbix_raw_request(
            &client,
            &self.url,
            "user.checkAuthentication",
            serde_json::json!({"token": token}),
            "",
            self.need_auth_in_body,
        ) {
            Ok(_) => {
                return Ok(ZabbixInstance {
                    id: Uuid::new_v4().to_string(),
                    need_auth_in_body: self.need_auth_in_body,
                    token: token,
                    request_client: client,
                    url: self.url,
                    version: self.version,
                    need_logout: false,
                });
            }
            Err(e) => {
                return Err(ZabbixError::ApiError {
                    message: "Invalid token".to_string(),
                    data: e.to_string(),
                });
            }
        }
    }

    fn login_with_username_password(
        self,
        username: String,
        password: String,
    ) -> Result<ZabbixInstance, ZabbixError> {
        let v5_2 = Version::parse("5.2.0")?;
        let current_v = Version::parse(&self.version)?;
        let user_param = if current_v <= v5_2 {
            "user"
        } else {
            "username"
        };

        let client = self.client.ok_or_else(|| {
            ZabbixError::Other("Client not initialized. Did you call build()?".to_string())
        })?;

        let token = ZabbixInstance::zabbix_raw_request(
            &client,
            &self.url,
            "user.login",
            serde_json::json!({user_param: username, "password": password}),
            "",
            self.need_auth_in_body,
        )?;

        Ok(ZabbixInstance {
            id: Uuid::new_v4().to_string(),
            need_auth_in_body: self.need_auth_in_body,
            token: token,
            request_client: client,
            url: self.url,
            version: self.version,
            need_logout: true,
        })
    }
}

impl ZabbixInstance {
    /// Returns the internally generated UUID for this instance.
    ///
    /// You can use it to identify the instance in your logs.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use http_request_zabbix::{ZabbixInstance, AuthType};
    ///
    /// let zabbix = ZabbixInstance::builder("http://zabbix.example.com/zabbix")
    ///     .build()
    ///     .unwrap()
    ///     .login(AuthType::UsernamePassword("Admin".to_string(), "zabbix".to_string()))
    ///     .unwrap();
    /// println!("Instance ID: {}", zabbix.id());
    /// ```
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Returns the Zabbix API URL this instance connects to (without the `/api_jsonrpc.php` suffix).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use http_request_zabbix::{ZabbixInstance, AuthType};
    ///
    /// let zabbix = ZabbixInstance::builder("http://zabbix.example.com/zabbix")
    ///     .build()
    ///     .unwrap()
    ///     .login(AuthType::UsernamePassword("Admin".to_string(), "zabbix".to_string()))
    ///     .unwrap();
    /// println!("Instance URL: {}", zabbix.url());
    /// ```
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Logs out of the Zabbix server and invalidates the current token.
    ///
    /// Call automatically when the instance is dropped.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use http_request_zabbix::{ZabbixInstance, AuthType};
    ///
    /// let mut zabbix = ZabbixInstance::builder("http://zabbix.example.com/zabbix")
    ///     .build()
    ///     .unwrap()
    ///     .login(AuthType::UsernamePassword("Admin".to_string(), "zabbix".to_string()))
    ///     .unwrap();
    /// zabbix.logout().unwrap();
    /// ```
    pub fn logout(&mut self) -> Result<&mut Self, ZabbixError> {
        if !self.need_logout {
            return Ok(self);
        }

        match Self::zabbix_raw_request(
            &self.request_client,
            &self.url,
            "user.logout",
            serde_json::json!([]),
            self.token.as_ref(),
            self.need_auth_in_body,
        ) {
            Ok(_) => {
                self.token = "".to_string();
                self.need_logout = false;
                Ok(self)
            }
            Err(e) => Err(e),
        }
    }

    /// Retrieves the Zabbix server API version.
    ///
    /// Use this method to check the version instead of directly calling `zabbix_request` with `apiinfo.version`,
    /// because this method requires no authentication.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use http_request_zabbix::{ZabbixInstance, AuthType};
    ///
    /// let zabbix = ZabbixInstance::builder("http://zabbix.example.com/zabbix")
    ///     .build()
    ///     .unwrap()
    ///     .login(AuthType::UsernamePassword("Admin".to_string(), "zabbix".to_string()))
    ///     .unwrap();
    /// println!("Zabbix Version: {}", zabbix.get_version().unwrap());
    /// ```
    pub fn get_version(&self) -> Result<String, ZabbixError> {
        let version_str = Self::zabbix_raw_request(
            &self.request_client,
            &self.url,
            "apiinfo.version",
            serde_json::json!([]),
            "",
            false,
        )?;

        Ok(version_str)
    }

    /// Checks if the connected Zabbix server's version matches a semantic version requirement.
    /// Example requirement: `>=6.4, <7.0`
    ///
    /// You can use this method to quickly check if the connected Zabbix server's version satisfies your requirements.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use http_request_zabbix::{ZabbixInstance, AuthType};
    ///
    /// let zabbix = ZabbixInstance::builder("http://zabbix.example.com/zabbix")
    ///     .build()
    ///     .unwrap()
    ///     .login(AuthType::UsernamePassword("Admin".to_string(), "zabbix".to_string()))
    ///     .unwrap();
    /// println!("Is >= 6.4: {}", zabbix.check_version(">=6.4").unwrap());
    /// ```
    pub fn check_version(&self, version_req: &str) -> Result<bool, ZabbixError> {
        let version_req = VersionReq::parse(version_req)?;
        let current_v = Version::parse(&self.version)?;

        Ok(version_req.matches(&current_v))
    }

    /// Makes a raw JSON-RPC request to the Zabbix API.
    ///
    /// `params` can be either a `serde_json::Value` (like `json!({...})`), a string slice `&str`, or a `String`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use http_request_zabbix::{ApiRequestParams, AuthType, ZabbixInstance};
    ///
    /// let zabbix = ZabbixInstance::builder("http://zabbix.example.com/zabbix").build().unwrap()
    ///     .login(AuthType::UsernamePassword("Admin".to_string(), "zabbix".to_string())).unwrap();
    ///
    /// let params_json = ApiRequestParams::from(serde_json::json!({"output": ["host", "name"], "limit": 1}));
    /// let params_string = ApiRequestParams::from("{\"output\": [\"host\", \"name\"], \"limit\": 1}");
    ///
    /// let result_json = zabbix.zabbix_request("host.get", params_json).unwrap();
    /// let result_string = zabbix.zabbix_request("host.get", params_string).unwrap();
    /// ```
    pub fn zabbix_request<P: Into<ApiRequestParams>>(
        &self,
        method: &str,
        params: P,
    ) -> Result<String, ZabbixError> {
        let params_val = match params.into() {
            ApiRequestParams::Json(val) => val,
            ApiRequestParams::String(s) => serde_json::from_str(&s).map_err(ZabbixError::from)?,
        };

        Self::zabbix_raw_request(
            &self.request_client,
            &self.url,
            method,
            params_val,
            &self.token,
            self.need_auth_in_body,
        )
    }

    fn zabbix_raw_request(
        client: &Client,
        url: &str,
        method: &str,
        params: Value,
        token: &str,
        need_auth_in_body: bool,
    ) -> Result<String, ZabbixError> {
        let mut request_builder = client
            .post(format!("{}/api_jsonrpc.php", url))
            .header("Content-Type", "application/json-rpc");

        let mut payload = serde_json::json!({
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
            "id": Uuid::new_v4().to_string()
        });

        if token != "" {
            if !need_auth_in_body {
                request_builder =
                    request_builder.header("Authorization", format!("Bearer {}", token));
            } else {
                if let Some(obj) = payload.as_object_mut() {
                    obj.insert("auth".to_string(), Value::String(String::from(token)));
                }
            }
        }

        let response = request_builder.json(&payload).send()?;

        if !response.status().is_success() {
            return Err(ZabbixError::Other(format!(
                "HTTP Error: {}",
                response.status()
            )));
        }

        let text = response.text()?;

        let json: Value = serde_json::from_str(&text)?;

        if let Some(error) = json.get("error") {
            if error.is_object() {
                let msg = error
                    .get("message")
                    .and_then(|v| v.as_str())
                    .unwrap_or("Unknown error");
                let data = error.get("data").and_then(|v| v.as_str()).unwrap_or("");
                return Err(ZabbixError::ApiError {
                    message: msg.to_string(),
                    data: data.to_string(),
                });
            }
            return Err(ZabbixError::Other(error.to_string()));
        }

        if let Some(result) = json.get("result") {
            if let Some(s) = result.as_str() {
                return Ok(s.to_string());
            }
            return Ok(result.to_string());
        }

        Err(ZabbixError::Other("Unknown response format".to_string()))
    }
}

impl Drop for ZabbixInstance {
    fn drop(&mut self) {
        if self.need_logout {
            self.logout().ok();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockito::Server;

    #[test]
    fn test_login_with_token_success() {
        let mut server = Server::new();
        let url = server.url();

        let mock_version = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"7.0.0","id":1}"#)
            .create();

        let mock_auth = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"dummy_token","id":1}"#)
            .create();

        let builder = ZabbixInstanceBuilder::new(&url).build().unwrap();
        let result = builder.login(AuthType::Token("test_token".to_string()));

        assert!(result.is_ok());
        mock_version.assert();
        mock_auth.assert();
    }

    #[test]
    fn test_login_with_password_success() {
        let mut server = Server::new();
        let url = server.url();

        let mock_version = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"7.0.0","id":1}"#)
            .create();

        let mock_auth = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"dummy_token","id":1}"#)
            .create();

        let builder = ZabbixInstanceBuilder::new(&url).build().unwrap();
        let result = builder.login(AuthType::UsernamePassword(
            "Admin".to_string(),
            "zabbix".to_string(),
        ));

        assert!(result.is_ok());
        mock_version.assert();
        mock_auth.assert();
    }

    #[test]
    fn test_login_with_password_failure() {
        let mut server = Server::new();
        let url = server.url();

        let mock_version = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"7.0.0","id":1}"#)
            .create();

        let mock_auth = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(401)
            .with_body(r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params","data":"Invalid username or password"},"id":1}"#)
            .create();

        let builder = ZabbixInstanceBuilder::new(&url).build().unwrap();
        let result = builder.login(AuthType::UsernamePassword(
            "Admin".to_string(),
            "zabbix".to_string(),
        ));

        assert!(result.is_err());
        mock_version.assert();
        mock_auth.assert();
    }

    #[test]
    fn test_login_with_token_failure() {
        let mut server = Server::new();
        let url = server.url();

        let mock_version = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"7.0.0","id":1}"#)
            .create();

        let mock_auth = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params","data":"Token is invalid"},"id":1}"#)
            .create();

        let builder = ZabbixInstanceBuilder::new(&url).build().unwrap();
        let result = builder.login(AuthType::Token("test_token".to_string()));

        assert!(result.is_err());
        mock_version.assert();
        mock_auth.assert();
    }

    #[test]
    fn test_request_json_success() {
        let mut server = Server::new();
        let url = server.url();

        let mock_version = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"7.0.0","id":1}"#)
            .create();

        let mock_auth = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"dummy_token","id":1}"#)
            .create();

        let mock_request = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"dummy_result","id":1}"#)
            .create();

        let builder = ZabbixInstanceBuilder::new(&url).build().unwrap();
        let result = builder.login(AuthType::Token("test_token".to_string()));
        let host_get = result.unwrap().zabbix_request(
            "host.get",
            serde_json::json!({"output": ["host", "name"], "limit": 1}),
        );

        assert!(host_get.is_ok());
        mock_version.assert();
        mock_auth.assert();
        mock_request.assert();
    }

    #[test]
    fn test_request_json_failure() {
        let mut server = Server::new();
        let url = server.url();

        let mock_version = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"7.0.0","id":1}"#)
            .create();

        let mock_auth = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"dummy_token","id":1}"#)
            .create();

        let mock_request = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params","data":"BlahBlahBlah"},"id":1}"#)
            .create();

        let builder = ZabbixInstanceBuilder::new(&url).build().unwrap();
        let result = builder.login(AuthType::Token("test_token".to_string()));
        let host_get = result.unwrap().zabbix_request(
            "host.get",
            serde_json::json!({"output": ["host", "name"], "limit": 1}),
        );

        assert!(host_get.is_err());
        mock_version.assert();
        mock_auth.assert();
        mock_request.assert();
    }

    #[test]
    fn test_request_string_success() {
        let mut server = Server::new();
        let url = server.url();

        let mock_version = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"7.0.0","id":1}"#)
            .create();

        let mock_auth = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"dummy_token","id":1}"#)
            .create();

        let mock_request = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"dummy_result","id":1}"#)
            .create();

        let builder = ZabbixInstanceBuilder::new(&url).build().unwrap();
        let result = builder.login(AuthType::Token("test_token".to_string()));
        let host_get = result
            .unwrap()
            .zabbix_request("host.get", r#"{"output": ["host", "name"], "limit": 1}"#);

        assert!(host_get.is_ok());
        mock_version.assert();
        mock_auth.assert();
        mock_request.assert();
    }

    #[test]
    fn test_request_string_failure() {
        let mut server = Server::new();
        let url = server.url();

        let mock_version = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"7.0.0","id":1}"#)
            .create();

        let mock_auth = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","result":"dummy_token","id":1}"#)
            .create();

        let mock_request = server
            .mock("POST", "/api_jsonrpc.php")
            .with_status(200)
            .with_body(r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params","data":"BlahBlahBlah"},"id":1}"#)
            .create();

        let builder = ZabbixInstanceBuilder::new(&url).build().unwrap();
        let result = builder.login(AuthType::Token("test_token".to_string()));
        let host_get = result
            .unwrap()
            .zabbix_request("host.get", r#"{"output": ["host", "name"], "limit": 1}"#);

        assert!(host_get.is_err());
        mock_version.assert();
        mock_auth.assert();
        mock_request.assert();
    }
}