zoho-crm 0.3.1

Library to help interact with v2 of the Zoho CRM 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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
use crate::client_error::ClientError;
use crate::token_record::TokenRecord;
use reqwest;
use crate::response;
use std::collections::HashMap;
use std::time::Duration;

#[cfg(test)]
use mockito;

/// Default network timeout for API requests.
const DEFAULT_TIMEOUT: u64 = 30;

/// Handles making requests to v2 of the Zoho CRM API.
///
/// You can either create a client with a preset access token, or fetch a new one later on.
/// This can be useful if you are keeping track of you access tokens in a database, for example. You will need an API client ID, secret, and refresh token.
///
/// You can read more information here:
/// [https://www.zoho.com/crm/developer/docs/api/oauth-overview.html](https://www.zoho.com/crm/developer/docs/api/oauth-overview.html)
///
/// ### Example
///
/// You should create a [`Client`](struct.Client) with the [`with_creds()`](struct.Client.html#method.with_creds) method.
///
/// ```
/// use zoho_crm::Client;
///
/// let client_id = "YOUR_CLIENT_ID";
/// let client_secret = "YOUR_CLIENT_SECRET";
/// let refresh_token = "YOUR_REFRESH_TOKEN";
///
/// let client = Client::with_creds(
///     None, // access token
///     None, // api domain
///     String::from(client_id),
///     String::from(client_secret),
///     String::from(refresh_token)
/// );
/// ```
///
/// API methods will automatically fetch a new token if one has not been set. This token is then
/// saved internally to be used on all future requests.
pub struct Client {
    access_token: Option<String>,
    api_domain: Option<String>,
    client_id: String,
    client_secret: String,
    refresh_token: String,
    sandbox: bool,
    timeout: u64,
}

impl Client {
    /// Create a new client.
    ///
    /// You can supply an optional access token and/or api domain. However, you must supply
    /// a client ID, secret, and refresh token.
    pub fn with_creds(
        access_token: Option<String>,
        api_domain: Option<String>,
        client_id: String,
        client_secret: String,
        refresh_token: String
    ) -> Client {
        Client {
            access_token,
            api_domain,
            client_id,
            client_secret,
            refresh_token,
            sandbox: false,
            timeout: DEFAULT_TIMEOUT,
        }
    }
}

impl Client {
    /// Get the sandbox configuration.
    pub fn sandbox(&self) -> bool {
        self.sandbox
    }

    /// Have the client use sandbox URLs.
    pub fn set_sandbox(&mut self, sandbox: bool) {
        self.sandbox = sandbox
    }

    /// Get the timeout (in seconds) for API requests.
    pub fn timeout(&self) -> u64 {
        self.timeout
    }

    /// Set the timeout for API requests. Default is 30 seconds.
    pub fn set_timeout(&mut self, timeout: u64) {
        self.timeout = timeout;
    }

    /// Get the access token.
    pub fn access_token(&self) -> Option<String> {
        self.access_token.clone()
    }

    /// Get the API domain URL.
    pub fn api_domain(&self) -> Option<String> {
        if self.sandbox() {
            Some(String::from("https://crmsandbox.zoho.com"))
        } else {
            self.api_domain.clone()
        }
    }

    /// Get an abbreviated version of the access token. This is a (slightly) safer version
    /// of the access token should you need to print it out.
    ///
    /// ```
    /// # use zoho_crm::Client;
    /// let token = "1000.ad8f97a9sd7f9a7sdf7a89s7df87a9s8.a77fd8a97fa89sd7f89a7sdf97a89df3";
    /// # let client_id = String::from("YOUR_CLIENT_ID");
    /// # let client_secret = String::from("YOUR_CLIENT_SECRET");
    /// # let refresh_token = String::from("YOUR_REFRESH_TOKEN");
    ///
    /// # let mut client = Client::with_creds(Some(token.to_string()), None, client_id, client_secret, refresh_token);
    ///
    /// assert_eq!("1000.ad8f..9df3", &client.abbreviated_access_token().unwrap());
    /// ```
    pub fn abbreviated_access_token(&self) -> Option<String> {
        match &self.access_token {
            Some(access_token) => {
                let prefix = &access_token[0..9];
                let suffix = &access_token.chars()
                    .rev()
                    .collect::<String>()[0..4]
                    .chars()
                    .rev()
                    .collect::<String>();
                let abbreviated_token = format!("{}..{}", prefix, suffix);

                Some(abbreviated_token)
            },
            None => None
        }
    }
}

impl Client {
    /// Get the API base path, which changes depending on the current environment.
    ///
    /// This is primarily used to allow for HTTP test mocking of API calls.
    fn get_api_base_path() -> String {
        #[cfg(test)]
        return mockito::server_url();

        #[cfg(not(test))]
        return String::from("https://accounts.zoho.com");
    }

    /// Get a new access token from Zoho. Guarantees an access token when it returns
    /// an `Result::Ok`.
    ///
    /// The access token is saved to the [`Client`](struct.Client), so you don't
    /// need to retrieve the token and set it in different steps. But a copy
    /// of it is returned by this method.
    pub fn get_new_token(&mut self) -> Result<TokenRecord, ClientError> {
        let url = format!(
            "{}/oauth/v2/token?grant_type=refresh_token&client_id={}&client_secret={}&refresh_token={}",
            Client::get_api_base_path(),
            self.client_id,
            self.client_secret,
            self.refresh_token
        );

        let client = reqwest::Client::new();
        let mut response = client.post(url.as_str()).send()?;
        let raw_response = response.text()?;

        // TODO: refactor this with a more idiomatic pattern
        if let Ok(response) = serde_json::from_str::<response::AuthErrorResponse>(&raw_response) {
            return Err(ClientError::General(response.error));
        }

        let api_response: TokenRecord = serde_json::from_str(&raw_response)?;

        self.access_token = api_response.access_token.clone();
        self.api_domain = api_response.api_domain.clone();

        match &self.access_token {
            Some(_) => Ok(api_response),
            None => Err(ClientError::from("No token received"))
        }
    }

    /// Fetches a record from Zoho.
    ///
    /// Zoho returns a data array with this method, even though that array will always be of
    /// length-1. We return the data array, so you must treat the response accordingly.
    ///
    /// If an error occurred, and we are given a response code back, this method will return a
    /// [`ClientError::ApiError`](enum.ClientError.html#variant.ApiError) with the response code
    /// and message. Otherwise, a [`ClientError::General`](enum.ClientError.html#variant.General)
    /// error will be returned with the raw response text.
    ///
    /// ### Example
    ///
    /// ```no_run
    /// # use serde::Deserialize;
    /// # use std::collections::HashMap;
    /// use zoho_crm::Client;
    ///
    /// #[derive(Deserialize)]
    /// struct Account {
    ///     name: String,
    /// }
    ///
    /// # let client_id = String::from("");
    /// # let client_secret = String::from("");
    /// # let refresh_token = String::from("");
    /// let mut client = Client::with_creds(None, None, client_id, client_secret, refresh_token);
    ///
    /// let response = client.get::<Account>("Accounts", "ZOHO_ID_HERE").unwrap();
    ///
    /// let account = response.data.get(0).unwrap();
    /// assert_eq!(account.name, "Account name");
    /// ```
    pub fn get<T: serde::de::DeserializeOwned>(&mut self, module: &str, id: &str) -> Result<response::ApiGetResponse<T>, ClientError> {
        if self.access_token.is_none() {
            self.get_new_token()?;
        }

        // we are guaranteed a token when we reach this line
        let token = self.access_token.clone().unwrap();

        let timeout = Duration::from_secs(self.timeout);
        let client = reqwest::Client::builder().timeout(timeout).build()?;

        let url = format!("{}/crm/v2/{}/{}", self.api_domain().unwrap(), module, id);

        let mut response = client
            .get(url.as_str())
            .header("Authorization", format!("Zoho-oauthtoken {}", token))
            .send()?;
        let raw_response = response.text()?;

        if let Ok(response) = serde_json::from_str::<response::ApiErrorResponse>(&raw_response) {
            return Err(ClientError::ApiError(response));
        }

        match serde_json::from_str::<response::ApiGetResponse<T>>(&raw_response) {
            Ok(data) => Ok(data),
            Err(_) => {
                if raw_response.len() > 0 {
                    Err(ClientError::UnexpectedResponseType(raw_response))
                } else {
                    Err(ClientError::General(String::from("Empty response")))
                }
            },
        }
    }

    /// Fetches a page of records from Zoho.
    ///
    /// Zoho API function documentation:
    /// [https://www.zoho.com/crm/developer/docs/api/get-records.html](https://www.zoho.com/crm/developer/docs/api/get-records.html)
    ///
    /// ### Example
    ///
    /// ```no_run
    /// # use serde::Deserialize;
    /// # use std::collections::HashMap;
    /// use zoho_crm::Client;
    ///
    /// #[derive(Deserialize)]
    /// struct Account {
    ///     name: String,
    /// }
    ///
    /// # let client_id = String::from("");
    /// # let client_secret = String::from("");
    /// # let refresh_token = String::from("");
    /// let mut client = Client::with_creds(None, None, client_id, client_secret, refresh_token);
    ///
    /// let accounts = client.get_many::<Account>("Accounts", None).unwrap();
    /// ```
    ///
    /// ### Example with parameters
    ///
    /// ```no_run
    /// # use serde::Deserialize;
    /// # use std::collections::HashMap;
    /// use zoho_crm::{parse_params, Client};
    ///
    /// #[derive(Deserialize)]
    /// struct Account {
    ///     name: String,
    /// }
    ///
    /// # let client_id = String::from("");
    /// # let client_secret = String::from("");
    /// # let refresh_token = String::from("");
    ///
    /// # let mut client = Client::with_creds(None, None, client_id, client_secret, refresh_token);
    ///
    /// let mut params: HashMap<&str, &str> = HashMap::new();
    /// params.insert("cvid", "YOUR_VIEW_ID_HERE");
    /// params.insert("page", "2");
    /// params.insert("per_page", "50");
    ///
    /// let params = parse_params(params).unwrap();
    /// let accounts = client.get_many::<Account>("Accounts", Some(params)).unwrap();
    /// ```
    pub fn get_many<T: serde::de::DeserializeOwned>(&mut self, module: &str, params: Option<String>) -> Result<response::ApiGetManyResponse<T>, ClientError> {
        if self.access_token.is_none() {
            self.get_new_token()?;
        }

        // we are guaranteed a token when we reach this line
        let token = self.access_token().unwrap();
        let api_domain = self.api_domain().unwrap();

        let timeout = Duration::from_secs(self.timeout);
        let client = reqwest::Client::builder().timeout(timeout).build()?;

        let mut url = format!("{}/crm/v2/{}", api_domain, module);

        if params.is_none() == false {
            url = url + &format!("?{}", params.unwrap());
        }

        let mut response = client
            .get(url.as_str())
            .header("Authorization", String::from("Zoho-oauthtoken ") + &token)
            .send()?;
        let raw_response = response.text()?;

        if let Ok(response) = serde_json::from_str::<response::ApiErrorResponse>(&raw_response) {
            return Err(ClientError::ApiError(response));
        }

        match serde_json::from_str::<response::ApiGetManyResponse<T>>(&raw_response) {
            Ok(data) => Ok(data),
            Err(_) => {
                if raw_response.len() > 0 {
                    Err(ClientError::UnexpectedResponseType(raw_response))
                } else {
                    Err(ClientError::General(String::from("Empty response")))
                }
            },
        }
    }

    /// Insert multiple records in Zoho.
    ///
    /// Zoho API function documentation:
    /// [https://www.zoho.com/crm/developer/docs/api/insert-records.html](https://www.zoho.com/crm/developer/docs/api/insert-records.html)
    ///
    /// It is important to note that this method *may* mask errors with a successful response.
    /// That is because record specific errors will be shown alongside the record in the response.
    /// We do not want to assume this is an *unsuccessful* response, and so it is up to you to
    /// handle them.
    ///
    /// The `params` argument accepts any serializable data type.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// # use zoho_crm::Client;
    /// # let client_id = String::from("");
    /// # let client_secret = String::from("");
    /// # let refresh_token = String::from("");
    /// # let mut zoho_client = Client::with_creds(None, None, client_id, client_secret, refresh_token);
    /// let mut record: HashMap<&str, &str> = HashMap::new();
    /// record.insert("name", "sample");
    ///
    /// let response = zoho_client.insert("Accounts", vec![record]).unwrap();
    ///
    /// for record in response.data {
    ///     match record.code.as_str() {
    ///         "SUCCESS" => println!("Record was successful"),
    ///         _ => println!("Record was NOT successful"),
    ///     }
    /// }
    /// ```
    pub fn insert<T>(&mut self, module: &str, data: Vec<T>) -> Result<response::ApiSuccessResponse, ClientError>
        where T: serde::ser::Serialize
    {
        if self.access_token.is_none() {
           self.get_new_token()?;
       }

       // we are guaranteed a token when we reach this line
       let token = self.access_token().unwrap();
       let api_domain = self.api_domain().unwrap();

       let client = reqwest::Client::builder()
           .timeout(Duration::from_secs(self.timeout))
           .build()?;

       let url = format!("{}/crm/v2/{}", api_domain, module);

       // Zoho requires incoming data to be sent via a `data` field
       let mut params: HashMap<&str, Vec<T>> = HashMap::new();
       params.insert("data", data);

       let mut response = client
           .post(url.as_str())
           .header("Authorization", String::from("Zoho-oauthtoken ") + &token)
           .json(&params)
           .send()?;
       let raw_response = response.text()?;

       if let Ok(response) = serde_json::from_str::<response::ApiErrorResponse>(&raw_response) {
           return Err(ClientError::ApiError(response));
       }

       match serde_json::from_str::<response::ApiSuccessResponse>(&raw_response) {
           Ok(response) => Ok(response),
           Err(_) => {
               if raw_response.len() > 0 {
                    Err(ClientError::UnexpectedResponseType(raw_response))
               } else {
                   Err(ClientError::General(String::from("Empty response")))
               }
           },
       }
   }

    /// Updates multiple records in Zoho.
    ///
    /// Zoho API function documentation:
    /// [https://www.zoho.com/crm/developer/docs/api/update-records.html](https://www.zoho.com/crm/developer/docs/api/update-records.html)
    ///
    /// It is important to note that this method *may* mask errors with a successful response.
    /// That is because record specific errors will be shown alongside the record in the response.
    /// We do not want to assume this is an *unsuccessful* response, and so it is up to you to
    /// handle them.
    ///
    /// The `params` argument accepts any serializable data type.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// # use zoho_crm::Client;
    /// # let client_id = String::from("");
    /// # let client_secret = String::from("");
    /// # let refresh_token = String::from("");
    /// # let mut zoho_client = Client::with_creds(None, None, client_id, client_secret, refresh_token);
    /// let mut record: HashMap<&str, &str> = HashMap::new();
    /// record.insert("id", "ZOHO_RECORD_ID_HERE");
    /// record.insert("name", "sample");
    ///
    /// let response = zoho_client.update_many("Accounts", vec![record]).unwrap();
    ///
    /// for record in response.data {
    ///     match record.code.as_str() {
    ///         "SUCCESS" => println!("Record was successful"),
    ///         _ => println!("Record was NOT successful"),
    ///     }
    /// }
    /// ```
    pub fn update_many<T>(&mut self, module: &str, data: Vec<T>)-> Result<response::ApiSuccessResponse, ClientError>
        where T: serde::ser::Serialize
    {
        if self.access_token.is_none() {
            self.get_new_token()?;
        }

        // we are guaranteed a token when we reach this line
        let token = self.access_token().unwrap();
        let api_domain = self.api_domain().unwrap();

        let timeout = Duration::from_secs(self.timeout);
        let client = reqwest::Client::builder().timeout(timeout).build()?;

        let url = format!("{}/crm/v2/{}", api_domain, module);

        // Zoho requires incoming data to be sent via a `data` field
        let mut params: HashMap<&str, Vec<T>> = HashMap::new();
        params.insert("data", data);

        let mut response = client
            .put(url.as_str())
            .header("Authorization", String::from("Zoho-oauthtoken ") + &token)
            .json(&params)
            .send()?;
        let raw_response = response.text()?;

        if let Ok(response) = serde_json::from_str::<response::ApiErrorResponse>(&raw_response) {
            return Err(ClientError::ApiError(response));
        }

        match serde_json::from_str::<response::ApiSuccessResponse>(&raw_response) {
            Ok(response) => Ok(response),
            Err(_) => {
                if raw_response.len() > 0 {
                    Err(ClientError::UnexpectedResponseType(raw_response))
                } else {
                    Err(ClientError::General(String::from("Empty response")))
                }
            },
        }
    }
}

/// Utility function to help a parameter list into a URL-encoded string.
///
/// This should be passed into any method that supports URL-encoded parameters, such as
/// [`get_many`](struct.Client.html#method.get_many).
///
/// ### Example
///
/// ```no_run
/// # use serde::Deserialize;
/// # use std::collections::HashMap;
/// # use zoho_crm::{parse_params, Client};
/// # #[derive(Deserialize)]
/// # struct Record {
/// #     id: String,
/// # }
/// # let mut client = Client::with_creds(None, None, String::from(""), String::from(""), String::from(""));
/// let mut params: HashMap<&str, &str> = HashMap::new();
/// params.insert("page", "2");
///
/// let params = parse_params(params).unwrap();
/// assert_eq!("page=2", &params);
///
/// client.get_many::<Record>("Accounts", Some(params)).unwrap();
/// ```
#[allow(dead_code)]
pub fn parse_params(params: impl serde::ser::Serialize) -> Result<String, serde_urlencoded::ser::Error> {
    serde_urlencoded::to_string(params)
}

#[cfg(test)]
mod tests {
    extern crate mockito;

    use mockito::{mock, Matcher, Mock};
    use super::*;
    use serde::Deserialize;
    use std::collections::HashMap;

    #[derive(Debug, Deserialize)]
    struct ResponseRecord {
        id: String,
    }

    /// Get a `Client` with an access token.
    fn get_client(access_token: Option<String>, api_domain: Option<String>) -> Client {
        let id = String::from("id");
        let secret = String::from("secret");
        let refresh_token = String::from("refresh_token");

        Client::with_creds(access_token, api_domain, id, secret, refresh_token)
    }

    /// Get an HTTP mocker.
    fn get_mocker<T: Into<Matcher>>(method: &str, url: T, body: Option<&str>) -> Mock {
        let mut mocker = mock(method, url)
            .with_status(200)
            .with_header("Content-Type", "application/json;charset=UTF-8");

        if let Some(body) = body {
            mocker = mocker
                .with_header("Content-Length", &body.to_string().len().to_string())
                .with_body(body);
        }

        mocker = mocker.create();

        mocker
    }

    #[test]
    /// Tests that using no preset access token works.
    fn no_access_token() {
        let client = get_client(None, Some(String::from("api_domain")));

        assert_eq!(client.access_token(), None);
    }

    #[test]
    /// Tests that using no preset API domain works.
    fn no_domain() {
        let client = get_client(Some(String::from("access_token")), None);

        assert_eq!(client.api_domain(), None);
    }

    #[test]
    /// Tests that using a preset access token works.
    fn preset_access_token() {
        let access_token = String::from("access_token");
        let client = get_client(Some(access_token.clone()), None);

        assert_eq!(client.access_token(), Some(access_token));
    }

    #[test]
    /// Tests that using a preset API domain works.
    fn preset_api_domain() {
        let domain = String::from("api_domain");
        let client = get_client(None, Some(domain.clone()));

        assert_eq!(client.api_domain(), Some(domain));
    }

    #[test]
    /// Tests that the `valid_abbreviated_token()` method works without an access token.
    fn empty_abbreviated_token() {
        let client = get_client(None, None);

        assert_eq!(client.abbreviated_access_token(), None);
    }

    #[test]
    /// Tests that the `valid_abbreviated_token()` method works with an access token.
    fn valid_abbreviated_token() {
        let access_token = String::from("12345678901234567890");
        let client = get_client(Some(access_token), None);

        assert_ne!(client.access_token().unwrap().len(), 15);
        assert_eq!(client.abbreviated_access_token().unwrap().len(), 15);
    }

    #[test]
    fn api_domain() {
        let api_domain = "https://test.com";
        let client = get_client(None, Some(api_domain.to_string()));

        assert_eq!(api_domain, client.api_domain().unwrap());
    }

    #[test]
    fn api_domain_sandbox() {
        let api_domain = "https://test.com";
        let sandbox_api_domain = "https://crmsandbox.zoho.com";

        let id = String::from("id");
        let secret = String::from("secret");
        let refresh_token = String::from("refresh_token");

        let mut client = Client::with_creds(None, Some(api_domain.to_string()), id, secret, refresh_token);
        client.set_sandbox(true);

        assert_eq!(sandbox_api_domain, client.api_domain().unwrap());
    }

    #[test]
    /// Tests that a valid token is set after calling the `Client` `get_new_token()` method.
    fn get_new_token_success() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = "https://www.zohoapis.com";
        let body = format!("{{\"access_token\":\"{}\",\"expires_in_sec\":3600,\"api_domain\":\"{}\",\"token_type\":\"Bearer\",\"expires_in\":3600000}}", access_token, api_domain);
        let mocker = get_mocker("POST", Matcher::Any, Some(&body));
        let mut client = get_client(None, None);

        match client.get_new_token() {
            Ok(e) => println!("Good: {:#?}", e),
            Err(error) => println!("Bad: {:#?}", error),
        }

        mocker.assert();
        assert_eq!(client.access_token(), Some(access_token.to_string()));
    }

    #[test]
    /// Tests that a valid API domain is set after calling the `Client` `get_new_token()` method.
    fn get_new_api_domain_success() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = "https://www.zohoapis.com";
        let body = format!(r#"{{"access_token":"{}","expires_in_sec":3600,"api_domain":"{}","token_type":"Bearer","expires_in":3600000}}"#, access_token, api_domain);
        let mocker = get_mocker("POST", Matcher::Any, Some(&body));
        let mut client = get_client(None, None);

        client.get_new_token().unwrap();

        mocker.assert();
        assert_eq!(client.api_domain(), Some(api_domain.to_string()));
    }

    #[test]
    /// Tests that an error is return after calling the `Client` `get_new_token()` method with an
    /// invalid refresh token.
    fn get_new_token_invalid_token() {
        let error_message = "invalid_token";
        let body = format!(r#"{{"error":"{}"}}"#, error_message);
        let mocker = get_mocker("POST", Matcher::Any, Some(&body));
        let mut client = get_client(None, None);

        match client.get_new_token() {
            Ok(_) => panic!("Error was not thrown"),
            Err(error) => {
                assert_eq!(error_message.to_string(), error.to_string());
            }
        }

        mocker.assert();
    }

    #[test]
    /// Tests that a `TokenRecord` with a valid access token is returned from the `Client`
    /// `get_new_token()` method.
    fn return_new_token_success() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = "https://www.zohoapis.com";
        let body = format!(r#"{{"access_token":"{}","expires_in_sec":3600,"api_domain":"{}","token_type":"Bearer","expires_in":3600000}}"#, access_token, api_domain);
        let mocker = get_mocker("POST", Matcher::Any, Some(&body));
        let mut client = get_client(None, None);

        let token = client.get_new_token().unwrap();

        mocker.assert();
        assert_eq!(token.access_token, Some(access_token.to_string()));
    }

    #[test]
    /// Tests that a `TokenRecord` with a valid API domain is returned from the `Client`
    /// `get_new_token()` method.
    fn return_api_domain_success() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = "https://www.zohoapis.com";
        let body = format!(r#"{{"access_token":"{}","expires_in_sec":3600,"api_domain":"{}","token_type":"Bearer","expires_in":3600000}}"#, access_token, api_domain);
        let mocker = get_mocker("POST", Matcher::Any, Some(&body));
        let mut client = get_client(None, None);

        let token = client.get_new_token().unwrap();

        mocker.assert();
        assert_eq!(token.api_domain, Some(api_domain.to_string()));
    }

    #[test]
    /// Tests that fetching a record via the `get()` method works.
    fn get_success() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = mockito::server_url();
        let record_id = "40000000123456789";
        let body = format!(r#"{{"data":[{{"id":"{}"}}],"info":{{"more_records":true,"per_page":1,"count":1,"page":1}}}}"#, record_id);
        let mocker = get_mocker("GET", Matcher::Any, Some(&body));
        let mut client = get_client(Some(String::from(access_token)), Some(String::from(api_domain)));

        let response = client.get::<ResponseRecord>("Accounts", record_id).unwrap();

        mocker.assert();
        assert_eq!(response.data.get(0).unwrap().id, record_id);
    }

    #[test]
    /// Tests that an error code returned via the `get()` method returns an error.
    fn get_regular_error() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = mockito::server_url();
        let error_code = "INVALID_URL_PATTERN";
        let body = format!(r#"{{"code":"{}","details":{{}},"message":"Please check if the URL trying to access is a correct one","status":"error"}}"#, error_code);
        let mocker = get_mocker("GET", Matcher::Any, Some(&body));
        let mut client = get_client(Some(String::from(access_token)), Some(String::from(api_domain)));

        match client.get::<ResponseRecord>("INVALID_MODULE", "00000") {
            Ok(_) => panic!("Response did not return an error"),
            Err(err) => {
                match err {
                    ClientError::ApiError(error) => assert_eq!(error.code, error_code),
                    _ => panic!("Wrong error type"),
                }
            }
        }

        mocker.assert();
    }

    #[test]
    /// Tests that a plain error message returned via the `get()` method returns an error.
    fn get_text_error() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = mockito::server_url();
        let error_code = "invalid_client";
        let body = format!("{}", error_code);
        let mocker = get_mocker("GET", Matcher::Any, Some(&body));
        let mut client = get_client(Some(String::from(access_token)), Some(String::from(api_domain)));

        match client.get::<ResponseRecord>("INVALID_MODULE", "00000") {
            Ok(_) => panic!("Response did not return an error"),
            Err(err) => {
                assert_eq!(err.to_string(), error_code.to_string());
            }
        }

        mocker.assert();
    }

    #[test]
    /// Tests that inserting a record via the `insert()` method works.
    fn insert_many_success() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = mockito::server_url();
        let record_id = "40000000123456789";
        let body = format!(r#"{{
            "data": [
                {{
                    "code": "SUCCESS",
                    "details": {{
                        "Modified_Time": "2019-05-02T11:17:33+05:30",
                        "Modified_By": {{
                            "name": "Patricia Boyle",
                            "id": "554023000000235011"
                        }},
                        "Created_Time": "2019-05-02T11:17:33+05:30",
                        "id": "{}",
                        "Created_By": {{
                            "name": "Patricia Boyle",
                            "id": "554023000000235011"
                        }}
                    }},
                    "message": "record added",
                    "status": "success"
                }}
            ]
        }}"#, record_id);
        let mocker = get_mocker("POST", Matcher::Any, Some(&body));
        let mut client = get_client(Some(access_token.to_string()), Some(api_domain.to_string()));

        let mut record: HashMap<&str, &str> = HashMap::new();
        record.insert("name", "New Record Name");

        let response = client.insert("Accounts", vec![record]).unwrap();
        let response = response.data.get(0).unwrap();

        let details = match &response.details {
            response::ResponseDataItemDetails::Error(_) => {
                panic!("Experienced an unexpected error");
            },
            response::ResponseDataItemDetails::Success(details) => details,
        };

        mocker.assert();
        assert_eq!(details.id, record_id);
    }

    #[test]
    /// Tests that an error code returned via the `insert()` method returns an error.
    fn insert_regular_error() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = mockito::server_url();
        let error_code = "INVALID_MODULE";
        let body = format!(r#"{{
            "code": "{}",
            "details": {{}},
            "message": "Please check if the URL trying to access is a correct one",
            "status": "error"
        }}"#, error_code);
        let mocker = get_mocker("POST", Matcher::Any, Some(&body));
        let mut client = get_client(Some(String::from(access_token)), Some(String::from(api_domain)));

        let mut record: HashMap<&str, &str> = HashMap::new();
        record.insert("name", "New Record Name");

        match client.insert("INVALID_MODULE", vec![record]) {
            Ok(_) => panic!("Response did not return an error"),
            Err(err) => {
                match err {
                    ClientError::ApiError(error) => assert_eq!(error.code, error_code),
                    _ => panic!("Wrong error type"),
                }
            }
        }

        mocker.assert();
    }

    #[test]
    /// Tests that a plain error message returned via the `insert()` method returns an error.
    fn insert_many_text_error() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = mockito::server_url();
        let error_code = "invalid_client";
        let body = format!("{}", error_code);
        let mocker = get_mocker("POST", Matcher::Any, Some(&body));
        let mut client = get_client(Some(String::from(access_token)), Some(String::from(api_domain)));

        let mut record: HashMap<&str, &str> = HashMap::new();
        record.insert("name", "New Record Name");

        match client.insert("INVALID_MODULE", vec![record]) {
            Ok(_) => panic!("Response did not return an error"),
            Err(err) => {
                assert_eq!(err.to_string(), error_code.to_string());
            }
        }

        mocker.assert();
    }

    #[test]
    /// Tests that updating a record via the `update_many()` method works.
    fn update_many_success() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = mockito::server_url();
        let record_id = "40000000123456789";
        let body = format!(r#"{{
            "data": [
                {{
                    "code": "SUCCESS",
                    "details": {{
                      "Modified_Time": "2019-05-02T11:17:33+05:30",
                      "Modified_By": {{
                        "name": "Patricia Boyle",
                        "id": "554023000000235011"
                      }},
                      "Created_Time": "2019-05-02T11:17:33+05:30",
                      "id": "{}",
                      "Created_By": {{
                        "name": "Patricia Boyle",
                        "id": "554023000000235011"
                      }}
                    }},
                    "message": "record updated",
                    "status": "success"
                }}
            ]
        }}"#, record_id);
        let mocker = get_mocker("PUT", Matcher::Any, Some(&body));
        let mut client = get_client(Some(access_token.to_string()), Some(api_domain.to_string()));

        let mut record: HashMap<&str, &str> = HashMap::new();
        record.insert("name", "New Record Name");

        let response = client.update_many("Accounts", vec![record]).unwrap();
        let response = response.data.get(0).unwrap();

        let details = match &response.details {
            response::ResponseDataItemDetails::Error(_) => {
                panic!("Experienced an unexpected error");
            },
            response::ResponseDataItemDetails::Success(details) => details,
        };

        mocker.assert();
        assert_eq!(details.id, record_id);
    }

    #[test]
    /// Tests that an error code returned via the `update_many()` method returns an error.
    fn update_regular_error() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = mockito::server_url();
        let error_code = "INVALID_MODULE";
        let body = format!(r#"{{
            "code": "{}",
            "details": {{}},
            "message": "Please check if the URL trying to access is a correct one",
            "status": "error"
        }}"#, error_code);
        let mocker = get_mocker("PUT", Matcher::Any, Some(&body));
        let mut client = get_client(Some(String::from(access_token)), Some(String::from(api_domain)));

        let mut record: HashMap<&str, &str> = HashMap::new();
        record.insert("name", "New Record Name");

        match client.update_many("INVALID_MODULE", vec![record]) {
            Ok(_) => panic!("Response did not return an error"),
            Err(err) => {
                match err {
                    ClientError::ApiError(error) => assert_eq!(error.code, error_code),
                    _ => panic!("Wrong error type"),
                }
            }
        }

        mocker.assert();
    }

    #[test]
    /// Tests that a plain error message returned via the `update_many()` method returns an error.
    fn update_many_text_error() {
        let access_token = "9999.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let api_domain = mockito::server_url();
        let error_code = "invalid_client";
        let body = format!("{}", error_code);
        let mocker = get_mocker("PUT", Matcher::Any, Some(&body));
        let mut client = get_client(Some(String::from(access_token)), Some(String::from(api_domain)));

        let mut record: HashMap<&str, &str> = HashMap::new();
        record.insert("name", "New Record Name");

        match client.update_many("INVALID_MODULE", vec![record]) {
            Ok(_) => panic!("Response did not return an error"),
            Err(err) => {
                assert_eq!(err.to_string(), error_code.to_string());
            }
        }

        mocker.assert();
    }

    #[test]
    fn test_parse_params() {
        let mut params: HashMap<&str, &str> = HashMap::new();
        params.insert("cvid", "00000");
        params.insert("page", "2");

        let converted = parse_params(params).unwrap();

        match converted.as_str() {
            "page=2&cvid=00000" => (),
            "cvid=00000&page=2" => (),
            _ => {
                panic!("Params did not convert properly");
            }
        }
    }
}