rsolr 0.3.2

A Solr client for Rust.
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
//! A Solr client for Rust.
//!
//! `Rsolr` provides capabilities to manipulate and form
//! requests to the Solr server, and contains some shorthands
//! for them. It uses the blocking version of the reqwest http client.
//!
//! ## Select
//!
//! You can retrieve documents as types with implemented `Clone` and `Deserialize`.
//!
//! ```rust
//! use serde_json::Value;
//! use rsolr::Client;
//! use rsolr::error::RSolrError;
//! use rsolr::solr_response::Response;
//!
//! fn query_all() -> Result<Response<Value>, RSolrError> {
//!     let mut client = Client::new("http://solr:8983", "collection");
//!     let result = client
//!         .select("*:*")
//!         .run();
//!
//!    match result {
//!         Ok(solr_result) => {
//!             let solr_result = client.get_response::<Value>();
//!             Ok(solr_result.expect("Serialization failed").response.expect("Response is OK, but no solr content"))
//!         }
//!         Err(e) => Err(e) // something happened on http
//!     }
//! }
//! ```
//!
//! ## Upload JSON doc(s)
//!
//! You should use types with implemented `Clone` and `Serialize`.
//!
//! ```rust
//!
//! use serde::Serialize;
//! use serde_json::Value;
//! use rsolr::Client;
//!
//! #[derive(Serialize, Clone)]
//! struct SimpleDocument {
//!     field: Vec<String>
//! }
//!
//! fn upload() {
//!     let document = SimpleDocument { field: vec!("nice".to_string(), "document".to_string()) };
//!     Client::new("http://solr:8983", "collection")
//!         .upload_json(document)
//!         .run().expect("request failed.");
//! }
//! ```
//! ## Delete
//!
//! ```rust
//! use serde_json::Value;
//! use rsolr::Client;
//! fn delete() {
//!     Client::new("http://solr:8983", "collection")
//!         .delete("delete:query")
//!         .run().expect("request failed.");
//! }
//! ```
//!
//! ## Custom handler with params
//!
//! You can define any handlers as well.
//!
//! ```rust
//!
//! use serde_json::Value;
//! use rsolr::Client;
//! use rsolr::error::RSolrError;
//! use rsolr::solr_response::Response;
//! fn more_like_this()  -> Result<Response<Value>, RSolrError> {
//!     let mut client = Client::new("http://solr:8983", "collection");
//!     let result = client
//!         .request_handler("mlt")
//!         .add_query_param("mlt.fl", "similarity_field")
//!         .add_query_param("mlt.mintf", "4")
//!         .add_query_param("mlt.minwl", "3")
//!         .run();
//!     match result {
//!         Ok(solr_result) => Ok(client.get_response::<Value>().expect("Serialization failed").response.expect("No response")),
//!         Err(e) => Err(e)
//!     }
//! }
//! ```
//!
//! ## Cursor-based pagination
//!
//! Paginated results can be fetched iteratively with the use of [solr cursor](https://solr.apache.org/guide/solr/latest/query-guide/pagination-of-results.html#fetching-a-large-number-of-sorted-results-cursors)
//!
//! ```rust
//! use serde_json::Value;
//! use rsolr::Client;
//! use rsolr::solr_response::SolrResponse;
//! fn cursor_fetch_all_pages() -> Vec<SolrResponse<Value>> {
//!     let mut responses = Vec::new();
//!     let mut client = Client::new("http://solr:8983", "collection");
//!     let result = client
//!         .select("*:*")
//!         .sort("id asc")
//!         .cursor()
//!         .run();
//!     let mut cursor = result.expect("request failed").expect("no cursor");
//!     while cursor.next::<Value>().expect("request failed").is_some() {
//!         responses.push(cursor.get_response::<Value>().expect("parsing failed"));
//!     }
//!     responses
//! }
//! ```

use std::fs::File;
use std::ops::Deref;
use cloneable_file::CloneableFile;

use http::StatusCode;
use mockall_double::double;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use url;
use url::Url;

#[double]
use http_client::HttpClient;

use crate::cursor::Cursor;
use crate::error::RSolrError;
use crate::solr_response::SolrResponse;

pub mod error;
pub mod solr_response;
pub mod query;
pub mod cursor;
mod facet_fields;
mod http_client;

/// The Payload defines the request method. Body and Empty sets method to POST, None uses GET.
#[derive(Clone, Debug)]
pub enum Payload {
    JsonBody(Value),
    CsvBody(CloneableFile),
    Empty,
    None
}

#[non_exhaustive]
pub struct RequestHandlers;

impl RequestHandlers {
    pub const QUERY: &'static str = "select";
    pub const UPLOAD_JSON: &'static str = "update/json/docs";
    pub const UPLOAD_CSV: &'static str = "update/csv";
    pub const DELETE: &'static str = "update";
}

#[derive(Clone, Debug)]
pub struct Client<'a> {
    request_handler: &'a str,
    url: Url,
    payload: Payload,
    collection: &'a str,
    response: Option<Value>
}

impl<'a> Client<'a> {

    pub fn new(base_url: &str, collection: &'a str) -> Self {
        let url = Url::parse(base_url).unwrap();
        Client { request_handler: "", url, payload: Payload::None, collection, response: None }
    }

    /// Adds custom GET query parameter to the Solr query.
    pub fn add_query_param(&mut self, key: &str, value: &str) -> &mut Self {
        self.url.query_pairs_mut().append_pair(key, value);
        self
    }

    /// Shorthand for facet_field.
    pub fn facet_field(&mut self, field: &str) -> &mut Self {
        self.switch_on_facet();
        self.url
            .query_pairs_mut()
            .append_pair("facet_field", field);

        self
    }

    /// Shorthand for facet_query.
    pub fn facet_query(&mut self, query: &str) -> &mut Self {
        self.switch_on_facet();
        self.url
            .query_pairs_mut()
            .append_pair("facet_query", query);
        self
    }

    /// Sets the Solr request handler in the URL. You can use RequestHandlers const, but it might be any string.
    pub fn request_handler(&mut self, handler: &'a str) -> &mut Self {
        self.request_handler = handler;
        self.payload = Payload::None;
        self.url.path_segments_mut().unwrap()
            .clear()
            .push("solr")
            .push(self.collection)
            .push(self.request_handler);
        self
    }
    /// Shorthand for commit=true, so if set write operations will be immediate.
    pub fn auto_commit(&mut self) -> &mut Self {
        self.add_query_param("commit", "true")
    }

    /// Shorthand for 'start' parameter of Solr basic pagination.
    pub fn start(&mut self, start: u32) -> &mut Self {
        self.add_query_param("start", &start.to_string())
    }

    pub fn update_cursor_mark(&mut self, cursor_mark: &str) -> &mut Self {
        let url = self.url.clone();
        let query = url.query().expect("Query part is required.");
        let regex = Regex::new(r"(cursorMark=)(\w|\*)").unwrap();
        let replace = format!("${{1}}{}", cursor_mark);
        let updated = regex.replace(query, replace.as_str());
        self.url.set_query(Some(updated.deref()));
        self
    }

    pub fn url(&mut self, url: &str) -> &mut Self {
        self.url = Url::parse(url).expect("Url parse failed.");
        self
    }

    /// Shorthand for 'sort' parameter.
    pub fn sort(&mut self, sort: &str) -> &mut Self {
        self.add_query_param("sort", sort)
    }

    /// Request cursor from Solr instance.
    pub fn cursor(&mut self) -> &mut Self {
        self.add_query_param("cursorMark", "*")
    }

    /// Shorthand for 'rows' parameter of Solr basic pagination.
    pub fn rows(&mut self, rows: u32) -> &mut Self {
        self.add_query_param("rows", &rows.to_string())
    }

    /// Shorthand for 'q' parameter for setting query in the request.
    pub fn query(&mut self, query: &str) -> &mut Self {
        self.add_query_param("q", query)
    }

    /// Shorthand for 'df' parameter.
    pub fn default_field(&mut self, default_field: &str) -> &mut Self {
        self.add_query_param("df", default_field)
    }

    /// Generates the request url as string without sending.
    pub fn url_str(&self) -> &str {
        self.url.as_str()
    }

    /// Sets the payload of the request, only JSON is supported.
    pub fn set_json_document<P : Clone + Serialize>(&mut self, document: P) -> &mut Self {
        self.payload(Payload::JsonBody(serde_json::to_value::<P>(document).unwrap()))
    }

    /// Empties the payload, it requires for POST requests (i.e. Solr delete or commit).
    pub fn set_empty_payload(&mut self) -> &mut Self {
        self.payload(Payload::Empty)
    }

    /// Clears the payload, now request method will be GET.
    pub fn clear_payload(&mut self) -> &mut Self {
        self.payload(Payload::None)
    }

    /// Runs the prepared request and fetches response to the type specified. Responds a Result which contains SolrResult, the response part of Solr response.
    pub fn run(&mut self) -> Result<Option<Cursor>, RSolrError> {
        let http_result = match &self.payload {
            Payload::JsonBody(body) => HttpClient::new().post_json(self.url_str(), Some(body)),
            Payload::Empty => HttpClient::new().post_json(self.url_str(), None),
            Payload::None => HttpClient::new().get(self.url_str()),
            Payload::CsvBody(file) => HttpClient::new().post_file_reader(self.url_str(), file.to_owned())
        };

        let http_response = match http_result {
            Ok(response) => response,
            Err(e) => return Err(RSolrError::Network { source: e }),
        };

        match http_response.status() {
            StatusCode::OK => {
                self.response = http_response.json::<Value>().ok();
                match self.url.query().unwrap_or("no url").contains("cursorMark") {
                    true => {
                        let cursor_mark = self.get_response::<Value>().unwrap().nextCursorMark.unwrap();
                        let cursor = Cursor::new(self.clone(), cursor_mark);
                        self.url.query_pairs_mut().clear();
                        Ok(Some(cursor))
                    },
                    false => {
                        self.url.query_pairs_mut().clear();
                        Ok(None)
                    }
                }
            },
            StatusCode::NOT_FOUND => Err(RSolrError::NotFound),
            other_status => {
                let body_text = http_response.text().unwrap();
                match serde_json::from_str::<Value>(&body_text) {
                    Ok(r) => Err(RSolrError::Syntax(r["error"]["msg"].as_str().unwrap().to_owned())),
                    Err(e) => {
                        Err( RSolrError::Other { source: Box::new(e), status: other_status, body_text })
                    }
                }
            }
        }
    }

    /// Get Solr response.
    pub fn get_response<T: for<'de> Deserialize<'de> + Clone + Default>(&self) -> Result<SolrResponse<T>, RSolrError>{
        match &self.response {
            Some(v) => match serde_json::from_value(v.to_owned()) {
                Ok(response) => Ok(response),
                Err(e) => Err(RSolrError::Serialization(e.to_string()) )
            },
            _ => Ok(SolrResponse::default())
        }
    }

    /// Shorthand for query.
    pub fn select(&mut self, query: &str) -> &mut Self {
        self
            .request_handler(RequestHandlers::QUERY)
            .query(query)
    }

    /// Alias for upload_json. It's deprecated.
    #[deprecated(since = "0.3.2", note = "Use upload_json instead.")]
    pub fn create<P: Serialize + Clone>(&mut self, document: P) -> &mut Self {
        self.upload_json(document)
    }

    /// Shorthand for uploading JSON doc(s).
    pub fn upload_json<P: Serialize + Clone>(&mut self, document: P) -> &mut Self {
        self
            .request_handler(RequestHandlers::UPLOAD_JSON)
            .set_json_document::<P>(document)
    }

    /// Shorthand for uploading a CSV file.
    pub fn upload_csv(&mut self, file: File) -> &mut Self {
        self
            .request_handler(RequestHandlers::UPLOAD_CSV)
            .set_csv_file(file)
    }

    /// Set a CSV file as payload.
    pub fn set_csv_file(&mut self, file: File) -> &mut Self {
        let cloneable_file = CloneableFile::from(file);
        self.payload(Payload::CsvBody(cloneable_file))
    }


    /// Shorthand for delete.
    pub fn delete(&mut self, query: &str) -> &mut Self {
        let delete_payload = json!({
            "delete": { "query": query }
        });

        self
            .request_handler(RequestHandlers::DELETE)
            .set_json_document(delete_payload)
    }

    /// Shorthand for direct commit.
    pub fn commit(&mut self) -> &mut Self {
        self
            .request_handler("update")
            .auto_commit()
            .set_empty_payload()
    }

    /// Shorthand for setting dismax query parser.
    pub fn dismax(&mut self) -> &mut Self {
        self.add_query_param("defType", "dismax")
    }

    /// Shorthand for setting edismax query parser.
    pub fn edismax(&mut self) -> &mut Self {
        self.add_query_param("defType", "edismax")
    }

    fn switch_on_facet(&mut self) {
        for query_pair in self.url.query_pairs() {
            if query_pair.0 == "facet" && query_pair.1 == "on" {
                return
            }
        }
        self.url.query_pairs_mut().append_pair("facet", "on");
    }

    fn payload(&mut self, payload: Payload) -> &mut Self {
        self.payload = payload;
        self
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Mutex, MutexGuard};

    use mockall::lazy_static;
    use mockall::predicate::eq;
    use serde_json::json;

    use super::*;

    lazy_static! {
        static ref MTX: Mutex<()> = Mutex::new(());
    }

    fn get_lock(m: &'static Mutex<()>) -> MutexGuard<'static, ()> {
        match m.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    fn setup_get_mock(url: &'static str, status_code: u16, body: &'static str) -> HttpClient {
        let mut mock = HttpClient::default();
        mock.expect_get()
            .with(eq(url))
            .returning(move |_| Ok(
                reqwest::blocking::Response::from(http::response::Builder::new()
                    .status(status_code)
                    .body(body)
                    .unwrap()))
            );
        mock
    }


    #[test]
    fn build_a_url_from_parameters() {
        let mut params = Client::new("http://host:8983", "collection");
        params
            .request_handler("request_handler")
            .query("*:*");

        let url_string = params.url_str();
        assert_eq!(url_string, "http://host:8983/solr/collection/request_handler?q=*%3A*");
    }

    #[test]
    fn build_a_url_from_parameters_set_autocommit() {
        let mut params = Client::new("http://host:8983", "collection");
        params
            .request_handler("request_handler")
            .auto_commit();

        let url_string = params.url_str();
        assert_eq!(url_string, "http://host:8983/solr/collection/request_handler?commit=true");
    }

    #[test]
    fn build_a_url_with_start_and_rows() {
        let mut params = Client::new("http://host:8983", "collection");
        params
            .request_handler("request_handler")
            .start(135545)
            .rows(12);

        let url_string = params.url_str();
        assert_eq!(url_string, "http://host:8983/solr/collection/request_handler?start=135545&rows=12");
    }

    #[test]
    fn build_a_url_with_default_field() {
        let mut params = Client::new("http://host:8983", "collection");
        params
            .request_handler("request_handler")
            .default_field("defaultfield");

        let url_string = params.url_str();
        assert_eq!(url_string, "http://host:8983/solr/collection/request_handler?df=defaultfield");
    }

    #[test]
    fn url_built_with_facet_if_facet_fields_set() {
        let mut params = Client::new("http://host:8983", "collection");
        params
            .request_handler("request_handler")
            .facet_field("facetfield");

        let url_string = params.url_str();
        assert_eq!(url_string, "http://host:8983/solr/collection/request_handler?facet=on&facet_field=facetfield");
    }

    #[test]
    fn url_built_with_facet_if_facet_query_set() {
        let mut params = Client::new("http://host:8983", "collection");
        params
            .request_handler("request_handler")
            .facet_query("facet");

        let url_string = params.url_str();
        assert_eq!(url_string, "http://host:8983/solr/collection/request_handler?facet=on&facet_query=facet");
    }

    #[test]
    fn url_built_with_facet_correctly_if_both_set() {
        let mut params = Client::new("http://host:8983", "collection");
        params
            .request_handler("request_handler")
            .facet_field("facetfield")
            .facet_query("facet");

        let url_string = params.url_str();
        assert_eq!(url_string, "http://host:8983/solr/collection/request_handler?facet=on&facet_field=facetfield&facet_query=facet");
    }

    #[test]
    fn run_formats_url_and_result() {
        let _m = get_lock(&MTX);

        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_get()
                .with(eq("http://localhost:8983/solr/default/select?q=*%3A*"))
                .returning(|_| Ok(reqwest::blocking::Response::from(http::response::Builder::new()
                    .status(200)
                    .body(r#"{"response": {"numFound": 1,"numFoundExact": true,"start": 0,"docs": [{"success": true }]}}"#)
                    .unwrap())));
            mock
        });

        let collection = "default";
        let host = "http://localhost:8983";
        let mut command = Client::new(host, collection);
        let result = command
            .request_handler("select")
            .query("*:*")
            .run();
        assert!(result.is_ok());
        assert_eq!(command.get_response::<Value>().unwrap().response.unwrap().docs[0]["success"], true);
    }

    #[test]
    fn run_handles_facet_fields() {
        let _m = get_lock(&MTX);
        let body = r#"{
                            "response": {"numFound": 1,"numFoundExact": true,"start": 0,"docs": [{"success": true }]},
                            "facet_counts": {
                                "facet_queries": {},
                                "facet_fields": {
                                    "exists": [
                                        "term1", 23423, "term2", 993939
                                    ]
                                },
                                "facet_ranges":{},
                                "facet_intervals":{},
                                "facet_heatmaps":{}
                            }
                        }"#;
        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            setup_get_mock("http://localhost:8983/solr/default/select?q=*%3A*&facet=on&facet_field=exists", 200, body)
        });

        let collection = "default";
        let host = "http://localhost:8983";
        let mut client = Client::new(host, collection);
        let result = client
            .request_handler("select")
            .query("*:*")
            .facet_field("exists")
            .run();
        assert!(result.is_ok());
        let facets = client.get_response::<Value>().unwrap().facet_counts.unwrap();
        assert_eq!(facets.facet_fields.fields, serde_json::from_str::<Value>(r#"{"exists":["term1", 23423,"term2",993939]}"#).unwrap());
    }

    #[test]
    fn run_handles_facet_query_and_returns_unimplemented_facets_in_raw() {
        let _m = get_lock(&MTX);
        let body = r#"{
                            "response": {"numFound": 1,"numFoundExact": true,"start": 0,"docs": [{"success": true }]},
                            "facet_counts": {
                                "facet_queries": {
                                    "anything: *": 324534
                                },
                                "facet_fields": {},
                                "facet_ranges":"interesting ranges",
                                "facet_intervals":"interesting intervals",
                                "facet_heatmaps":"interesting heatmaps"
                            }
                        }"#;

        let ctx = HttpClient::new_context();
        ctx.expect().returning(||
           setup_get_mock("http://localhost:8983/solr/default/select?q=*%3A*&facet=on&facet_query=anything%3A+*", 200, body)
        );

        let collection = "default";
        let host = "http://localhost:8983";
        let mut command = Client::new(host, collection);
        let result = command
            .request_handler("select")
            .query("*:*")
            .facet_query("anything: *")
            .run();
        assert!(result.is_ok());
        let facets = command.get_response::<Value>().unwrap().facet_counts.unwrap();
        assert_eq!(facets.facet_queries, serde_json::from_str::<Value>(r#"{"anything: *": 324534 }"#).unwrap());

        assert_eq!(facets.raw.get("facet_ranges").unwrap(), "interesting ranges");
        assert_eq!(facets.raw.get("facet_intervals").unwrap(), "interesting intervals");
        assert_eq!(facets.raw.get("facet_heatmaps").unwrap(), "interesting heatmaps");
    }

    #[test]
    fn run_deserializes_remaining_fields_into_raw() {
        let _m = get_lock(&MTX);
        let ctx = HttpClient::new_context();
        let body = r#"{"response": {"numFound": 1,"numFoundExact": true,"start": 0,"docs": [{"success": true }]},"anything":"other fields"}"#;

        ctx.expect().returning(||
            setup_get_mock("http://localhost:8983/solr/default/select?q=*%3A*", 200, body)
        );
        let mut client = Client::new("http://localhost:8983", "default");
        let result = client
            .select("*:*")
            .run();
        assert!(result.is_ok());
        assert_eq!(client.get_response::<Value>().unwrap().raw.get("anything").unwrap(),"other fields");
    }

    #[test]
    fn run_calls_post_with_url_and_body() {
        let _m = get_lock(&MTX);

        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_post_json()
                .withf(| url, body | url == "http://localhost:8983/solr/default/update%2Fjson%2Fdocs?commit=true" && *body == Some(&json!({ "this is": "a document"})) )
                .returning(|_, _| Ok(reqwest::blocking::Response::from(http::response::Builder::new()
                    .status(200)
                    .body(r#"{"response": {"numFound": 1,"numFoundExact": true,"start": 0,"docs": [{"success": true }]}}"#)
                    .unwrap())));
            mock
        });

        let collection = "default";
        let host = "http://localhost:8983";
        let mut command = Client::new(host, collection);
        let result = command
            .request_handler("update/json/docs")
            .auto_commit()
            .set_json_document(json!({ "this is": "a document"}))
            .run();
        assert!(result.is_ok());
        assert_eq!(command.get_response::<Value>().unwrap().response.unwrap().docs[0]["success"], true);
    }

    #[test]
    fn select_responds_rsolr_error_with_other_problem_if_dunno() {
        let _m = get_lock(&MTX);
        let ctx = HttpClient::new_context();

        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_get()
                .returning(|_| Ok(reqwest::blocking::Response::from(
                    http::response::Builder::new().status(500).body(r#"{"error": {"code": 500, "msg": "okapi"}}"#).unwrap())));
            mock
        });

        let collection = "default";
        let base_url = "http://localhost:8983";
        let mut client = Client::new(base_url, collection);
        let result = client
            .select("bad: query")
            .run();
        assert!(result.is_err());
        let error = result.err().expect("No Error");
        assert!(matches!(error, RSolrError::Syntax(..) ));
        assert_eq!(format!("{:?}", error), "Syntax(\"okapi\")");
    }

    #[test]
    fn select_responds_rsolr_error_with_raw_text_body_and_status_code_if_no_standard_message() {
        let _m = get_lock(&MTX);
        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_get().returning(|_| Ok(reqwest::blocking::Response::from(http::response::Builder::new().status(500).body(r#"some unparseable thing"#).unwrap())));
            mock
        });

        let collection = "default";
        let host = "http://localhost:8983";
        let mut client  = Client::new(host, collection);
            let result = client
            .select("bad: query")
            .run();
        let error = result.err().expect("No Error");
        assert!(matches!(error, RSolrError::Other {status: StatusCode::INTERNAL_SERVER_ERROR, ..} ));
        assert!(format!("{:?}", error).contains("some unparseable thing"));
    }

    #[test]
    fn create_responds_rsolr_error_with_other_problem_if_dunno() {
        let _m = get_lock(&MTX);
        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_post_json().returning(|_, _| Ok(reqwest::blocking::Response::from(http::response::Builder::new().status(500).body(r#"{"error": {"code": 500, "msg": "okapi"}}"#).unwrap())));
            mock
        });

        let collection = "default";
        let host = "http://localhost:8983";
        let mut client = Client::new(host, collection);
        let result = client
            .auto_commit()
            .upload_json(json!({"anything": "anything"}))
            .run();
        assert!(result.is_err());
        let error = result.err().expect("No Error");
        assert!(matches!(error, RSolrError::Syntax(..) ));
        assert_eq!(format!("{:?}", error), "Syntax(\"okapi\")");
    }

    #[test]
    fn create_responds_rsolr_error_with_raw_text_body_and_status_code_if_no_standard_message() {
        let _m = get_lock(&MTX);
        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_post_json().returning(|_, _| Ok(reqwest::blocking::Response::from(http::response::Builder::new().status(500).body(r#"some unparseable thing"#).unwrap())));
            mock
        });

        let collection = "default";
        let host = "http://localhost:8983";
        let mut client  = Client::new(host, collection);
        let result = client
            .auto_commit()
            .upload_json(json!({"anything": "anything"}))
            .run();
        assert!(result.is_err());
        let error = result.err().expect("No Error");
        assert!(matches!(error, RSolrError::Other {status: StatusCode::INTERNAL_SERVER_ERROR, ..} ));
        assert!(format!("{:?}", error).contains("some unparseable thing"));
    }

    #[test]
    fn delete_responds_rsolr_error_with_other_problem_if_dunno() {
        let _m = get_lock(&MTX);
        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_post_json().returning(|_, _| Ok(reqwest::blocking::Response::from(http::response::Builder::new().status(500).body(r#"{"error": {"code": 500, "msg": "okapi"}}"#).unwrap())));
            mock
        });

        let collection = "default";
        let host = "http://localhost:8983";
        let mut client = Client::new(host, collection);
        let result = client
            .auto_commit()
            .delete("*:*")
            .run();
        assert!(result.is_err());
        let error = result.err().expect("No Error");
        assert!(matches!(error, RSolrError::Syntax(..) ));
        assert_eq!(format!("{:?}", error), "Syntax(\"okapi\")");
    }

    #[test]
    fn delete_responds_rsolr_error_with_raw_text_body_and_status_code_if_no_standard_message() {
        let _m = get_lock(&MTX);
        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_post_json().returning(|_, _| Ok(reqwest::blocking::Response::from(http::response::Builder::new().status(500).body(r#"some unparseable thing"#).unwrap())));
            mock
        });

        let collection = "default";
        let host = "http://localhost:8983";
        let mut client = Client::new(host, collection);
        let result = client
            .delete("*:*")
            .run();
        assert!(result.is_err());
        let error = result.err().expect("No Error");
        assert!(matches!(error, RSolrError::Other {status: StatusCode::INTERNAL_SERVER_ERROR, ..} ));
        assert!(format!("{:?}", error).contains("some unparseable thing"));
    }

    #[test]
    fn run_responds_cursor_if_cursor_set() {
        let _m = get_lock(&MTX);
        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_get()
                .returning(|_| Ok(reqwest::blocking::Response::from(http::response::Builder::new()
                    .status(200)
                    .body(r#"{"response": {"numFound": 1,"numFoundExact": true,"start": 0,"docs": [{"success": true }]}, "nextCursorMark": "cursormark"}"#)
                    .unwrap())));
            mock
        });

        let mut client = Client::new("http://localhost:8983", "default");
        let result = client
            .select("*:*")
            .sort("field asc")
            .cursor()
            .run();
        assert!(result.expect("Ok expected").is_some());
    }

    #[test]
    fn next_returns_the_next_response() {
        let _m = get_lock(&MTX);
        let ctx = HttpClient::new_context();
        ctx.expect().returning(|| {
            let mut mock = HttpClient::default();
            mock.expect_get()
                .with(eq("http://solr.url/solr/dummy/select?q=*%3A*&rows=1&cursorMark=first_cursor_mark&sort=unique+asc"))
                .returning(|_| Ok(reqwest::blocking::Response::from(http::response::Builder::new()
                    .status(200)
                    .body(r#"{"response": {"numFound": 2,"numFoundExact": true,"start": 0,"docs": [{"success": true }]}, "nextCursorMark": "second_cursor_mark"}"#)
                    .unwrap())));

            mock.expect_get()
                .with(eq("http://solr.url/solr/dummy/select?q=*%3A*&rows=1&cursorMark=second_cursor_mark&sort=unique+asc"))
                .returning(|_| Ok(reqwest::blocking::Response::from(http::response::Builder::new()
                    .status(200)
                    .body(r#"{"response": {"numFound": 2,"numFoundExact": true,"start": 0,"docs": [{"success2": true }]}, "nextCursorMark": "third_cursor_mark"}"#)
                    .unwrap())));

            mock.expect_get()
                .with(eq("http://solr.url/solr/dummy/select?q=*%3A*&rows=1&cursorMark=third_cursor_mark&sort=unique+asc"))
                .returning(|_| Ok(reqwest::blocking::Response::from(http::response::Builder::new()
                    .status(200)
                    .body(r#"{"response": {"numFound": 2,"numFoundExact": true,"start": 0,"docs": []}, "nextCursorMark": "third_cursor_mark"}"#)
                    .unwrap())));

            mock
        });

        let mut client = Client::new("http://solr.url", "dummy");
        client
            .select("*:*")
            .rows(1)
            .cursor()
            .sort("unique asc");


        let mut cursor = Cursor::new(client, "first_cursor_mark".to_owned());
        let result = cursor.next::<Value>();
        assert_eq!(result.expect("Ok expected").expect("Response expected").response.expect("solr response expected").docs[0].get("success").unwrap(), true);

        let result2 = cursor.next::<Value>();
        assert_eq!(result2.expect("Ok expected").expect("Response expected").response.expect("solr response expected").docs[0].get("success2").unwrap(), true);

        let result3 = cursor.next::<Value>();
        assert!(result3.expect("Ok expected").is_none());
    }
}