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
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
//! Access wikipedia articles from Rust.
//!
//! # Examples
//! ```
//! extern crate wikipedia;
//!
//! let wiki = wikipedia::Wikipedia::<wikipedia::http::default::Client>::default();
//! let page = wiki.page_from_title("Club Atletico River Plate".to_owned());
//! let content = page.get_content().unwrap();
//! assert!(content.contains("B Nacional"));
//! ```
#[cfg(feature="http-client")] extern crate reqwest;
#[cfg(feature="http-client")] extern crate url;
extern crate serde_json;
#[macro_use] extern crate failure;

use std::cmp::PartialEq;
use std::io;
use std::result;

pub mod iter;
pub mod http;
pub use iter::Iter;

const LANGUAGE_URL_MARKER:&'static str = "{language}";

macro_rules! results {
    ($data: expr, $query_field: expr) => {
        // There has to be a better way to write the following code
        try!(
            $data.as_object()
            .and_then(|x| x.get("query"))
            .and_then(|x| x.as_object())
            .and_then(|x| x.get($query_field))
            .and_then(|x| x.as_array())
            .ok_or(Error::JSONPathError)
            ).into_iter().filter_map(|i|
                i.as_object()
                .and_then(|i| i.get("title"))
                .and_then(|s| s.as_str().map(|s| s.to_owned()))
                ).collect()
    }
}

macro_rules! cont {
    ($this: expr, $cont: expr, $($params: expr),*) => {{
        let qp = $this.identifier.query_param();
        let mut params = vec![
            $($params),*,
            ("format", "json"),
            ("action", "query"),
            (&*qp.0, &*qp.1),
        ];
        match *$cont {
            Some(ref v) => {
                for x in v.iter() { params.push((&*x.0, &*x.1)); }
            },
            None => params.push(("continue", "")),
        }
        let q = try!($this.wikipedia.query(params.into_iter()));

        let pages = try!(q
            .as_object()
            .and_then(|x| x.get("query"))
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("pages"))
            .and_then(|x| x.as_object())
            .ok_or(Error::JSONPathError));

        Ok((pages.values().cloned().collect(), try!($this.parse_cont(&q))))
    }}
}

/// Wikipedia failed to fetch some information
#[derive(Fail, Debug)]
pub enum Error {
    /// Some error communicating with the server
    #[fail(display = "HTTP Error")]
    HTTPError,
    /// Error reading response
    #[fail(display = "IO Error: {}", _0)]
    IOError(#[cause] io::Error),
    /// Failed to parse JSON response
    #[fail(display = "JSON Error: {}", _0)]
    JSONError(#[cause] serde_json::error::Error),
    /// Missing required keys in the JSON response
    #[fail(display = "JSON Path Error")]
    JSONPathError,
    /// One of the parameters provided (identified by `String`) is invalid
    #[fail(display = "Invalid Parameter: {}", _0)]
    InvalidParameter(String),
}

pub type Result<T> = result::Result<T, Error>;

#[derive(Debug)]
pub struct Wikipedia<A: http::HttpClient> {
    /// HttpClient struct.
    pub client: A,
    /// Url is created by concatenating `pre_language_url` + `language` + `post_language_url`.
    pub pre_language_url: String,
    pub post_language_url: String,
    pub language: String,
    /// Number of results to fetch when searching.
    pub search_results: u32,
    /// Number of images to fetch in each request when calling `get_images`.
    /// The iterator will go through all of them, fetching pages of this size.
    /// It can be the string "max" to fetch as many as possible on every request.
    pub images_results: String,
    /// Like `images_results`, for links and references.
    pub links_results: String,
    /// Like `images_results`, for categories.
    pub categories_results: String,
}

impl<A: http::HttpClient + Default> Default for Wikipedia<A> {
    fn default() -> Self {
        Wikipedia::new(A::default())
    }
}

impl<A: http::HttpClient + Clone> Clone for Wikipedia<A> {
    fn clone(&self) -> Self {
        Wikipedia {
            client: self.client.clone(),
            pre_language_url: self.pre_language_url.clone(),
            post_language_url: self.post_language_url.clone(),
            language: self.language.clone(),
            search_results: self.search_results.clone(),
            images_results: self.images_results.clone(),
            links_results: self.links_results.clone(),
            categories_results: self.categories_results.clone(),
        }
    }
}

impl<A: http::HttpClient> Wikipedia<A> {
    /// Creates a new object using the provided client and default values.
    pub fn new(mut client: A) -> Self {
        client.user_agent("wikipedia (https://github.com/seppo0010/wikipedia-rs)".to_owned());
        Wikipedia {
            client: client,
            pre_language_url: "https://".to_owned(),
            post_language_url: ".wikipedia.org/w/api.php".to_owned(),
            language: "en".to_owned(),
            search_results: 10,
            images_results: "max".to_owned(),
            links_results: "max".to_owned(),
            categories_results: "max".to_owned(),
        }
    }

    /// Returns a list of languages in the form of (`identifier`, `language`),
    /// for example [("en", "English"), ("es", "Español")]
    pub fn get_languages(&self) -> Result<Vec<(String, String)>> {
        let q = try!(self.query(vec![
                ("meta", "siteinfo"),
                ("siprop", "languages"),
                ("format", "json"),
                ("action", "query"),
            ].into_iter()));

        Ok(try!(q
            .as_object()
            .and_then(|x| x.get("query"))
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("languages"))
            .and_then(|x| x.as_array())
            .ok_or(Error::JSONPathError))
            .into_iter()
            .filter_map(|x| {
                        let o = x.as_object();
                        Some((
                            match o
                                .and_then(|x| x.get("code"))
                                .and_then(|x| x.as_str())
                                .map(|x| x.to_owned()) {
                                    Some(v) => v,
                                    None => return None,
                                },
                            match o
                                .and_then(|x| x.get("*"))
                                .and_then(|x| x.as_str())
                                .map(|x| x.to_owned()) {
                                    Some(v) => v,
                                    None => return None,
                                },
                        ))
                    })
            .collect())
    }

    /// Returns the api url
    pub fn base_url(&self) -> String {
        format!("{}{}{}", self.pre_language_url, self.language, self.post_language_url)
    }

    /// Updates the url format. The substring `{language}` will be replaced
    /// with the selected language.
    pub fn set_base_url(&mut self, base_url: &str) {
        let index = match base_url.find(LANGUAGE_URL_MARKER) {
            Some(i) => i,
            None => {
                self.pre_language_url = base_url.to_owned();
                self.language = "".to_owned();
                self.post_language_url = "".to_owned();
                return;
            }
        };
        self.pre_language_url = base_url[0..index].to_owned();
        self.post_language_url = base_url[index+LANGUAGE_URL_MARKER.len()..].to_owned();
    }

    fn query<'a, I>(&self, args: I) -> Result<serde_json::Value>
            where I: Iterator<Item=(&'a str, &'a str)> {
        let response_str = self.client.get(&*self.base_url(), args).map_err(|_| Error::HTTPError)?;
        let json = serde_json::from_str(&*response_str).map_err(Error::JSONError)?;
        Ok(json)
    }

    /// Searches for a string and returns a list of relevant page titles.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate wikipedia;
    ///
    /// let wiki = wikipedia::Wikipedia::<wikipedia::http::default::Client>::default();
    /// let results = wiki.search("keyboard").unwrap();
    /// assert!(results.contains(&"Computer keyboard".to_owned()));
    /// ```
    pub fn search(&self, query: &str) -> Result<Vec<String>> {
        let results = &*format!("{}", self.search_results);
        let data = try!(self.query(vec![
                ("list", "search"),
                ("srprop", ""),
                ("srlimit", results),
                ("srsearch", query),
                ("format", "json"),
                ("action", "query"),
            ].into_iter()));

        Ok(results!(data, "search"))
    }

    /// Search articles within `radius` meters of `latitude` and `longitude`.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate wikipedia;
    ///
    /// let wiki = wikipedia::Wikipedia::<wikipedia::http::default::Client>::default();
    /// let results = wiki.geosearch(40.750556,-73.993611, 20).unwrap();
    /// assert!(results.contains(&"Madison Square Garden".to_owned()));
    /// ```
    pub fn geosearch(&self, latitude: f64, longitude: f64, radius: u16) -> Result<Vec<String>> {
        if latitude < -90.0 || latitude > 90.0 {
            return Err(Error::InvalidParameter("latitude".to_string()))
        }
        if longitude < -180.0 || longitude > 180.0 {
            return Err(Error::InvalidParameter("longitude".to_string()))
        }
        if radius < 10 || radius > 10000 {
            return Err(Error::InvalidParameter("radius".to_string()))
        }
        let results = &*format!("{}", self.search_results);
        let data = try!(self.query(vec![
                ("list", "geosearch"),
                ("gsradius", &*format!("{}", radius)),
                ("gscoord", &*format!("{}|{}", latitude, longitude)),
                ("gslimit", results),
                ("format", "json"),
                ("action", "query"),
                ].into_iter()));
        Ok(results!(data, "geosearch"))
    }

    /// Fetches `count` random articles' title.
    pub fn random_count(&self, count: u8) -> Result<Vec<String>> {
        let data = try!(self.query(vec![
                ("list", "random"),
                ("rnnamespace", "0"),
                ("rnlimit", &*format!("{}", count)),
                ("format", "json"),
                ("action", "query"),
                ].into_iter()));
        let r:Vec<String> = results!(data, "random");
        Ok(r)
    }

    /// Fetches a random article's title.
    pub fn random(&self) -> Result<Option<String>> {
        Ok(try!(self.random_count(1)).into_iter().next())
    }

    /// Creates a new `Page` given a `title`.
    pub fn page_from_title<'a>(&'a self, title: String) -> Page<'a, A> {
        Page::from_title(self, title)
    }

    /// Creates a new `Page` given a `pageid`.
    pub fn page_from_pageid<'a>(&'a self, pageid: String) -> Page<'a, A> {
        Page::from_pageid(self, pageid)
    }
}

#[derive(Debug)]
enum TitlePageId {
    Title(String),
    PageId(String),
}

impl TitlePageId {
    fn query_param(&self) -> (String, String) {
        match *self {
            TitlePageId::Title(ref s) => ("titles".to_owned(), s.clone()),
            TitlePageId::PageId(ref s) => ("pageids".to_owned(), s.clone()),
        }
    }
}

#[derive(Debug)]
pub struct Page<'a, A: 'a + http::HttpClient> {
    wikipedia: &'a Wikipedia<A>,
    identifier: TitlePageId,
}

/// A wikipedia article.
impl<'a, A: http::HttpClient> Page<'a, A> {
    /// Creates a new `Page` given a `title`.
    pub fn from_title(wikipedia: &'a Wikipedia<A>, title: String) -> Page<A> {
        Page { wikipedia: wikipedia, identifier: TitlePageId::Title(title) }
    }

    /// Creates a new `Page` given a `pageid`.
    pub fn from_pageid(wikipedia: &'a Wikipedia<A>, pageid: String) -> Page<A> {
        Page { wikipedia: wikipedia, identifier: TitlePageId::PageId(pageid) }
    }

    /// Gets the `Page`'s `pageid`.
    pub fn get_pageid(&self) -> Result<String> {
        match self.identifier {
            TitlePageId::PageId(ref s) => Ok(s.clone()),
            TitlePageId::Title(_) => {
                let qp = self.identifier.query_param();
                let q = try!(self.wikipedia.query(vec![
                    ("prop", "info|pageprops"),
                    ("inprop", "url"),
                    ("ppprop", "disambiguation"),
                    ("redirects", ""),
                    ("format", "json"),
                    ("action", "query"),
                    (&*qp.0, &*qp.1),
                ].into_iter()));

                match self.redirect(&q) {
                    Some(r) => return Page::from_title(&self.wikipedia, r).get_pageid(),
                    None => (),
                }
                let pages = try!(q
                    .as_object()
                    .and_then(|x| x.get("query"))
                    .and_then(|x| x.as_object())
                    .and_then(|x| x.get("pages"))
                    .and_then(|x| x.as_object())
                    .ok_or(Error::JSONPathError));
                pages.keys().cloned().next().ok_or(Error::JSONPathError)
            }
        }
    }

    /// Gets the `Page`'s `title`.
    pub fn get_title(&self) -> Result<String> {
        match self.identifier {
            TitlePageId::Title(ref s) => Ok(s.clone()),
            TitlePageId::PageId(_) => {
                let qp = self.identifier.query_param();
                let q = try!(self.wikipedia.query(vec![
                    ("prop", "info|pageprops"),
                    ("inprop", "url"),
                    ("ppprop", "disambiguation"),
                    ("redirects", ""),
                    ("format", "json"),
                    ("action", "query"),
                    (&*qp.0, &*qp.1),
                ].into_iter()));

                match self.redirect(&q) {
                    Some(r) => return Ok(r),
                    None => (),
                }
                let pages = try!(q
                    .as_object()
                    .and_then(|x| x.get("query"))
                    .and_then(|x| x.as_object())
                    .and_then(|x| x.get("pages"))
                    .and_then(|x| x.as_object())
                    .ok_or(Error::JSONPathError));
                let page = match pages.values().next() {
                    Some(p) => p,
                    None => return Err(Error::JSONPathError),
                };
                Ok(try!(page.as_object()
                    .and_then(|x| x.get("title"))
                    .and_then(|x| x.as_str())
                    .ok_or(Error::JSONPathError))
                    .to_owned())
            },
        }
    }

    /// If the `Page` redirects to another one it returns its title, otherwise
    /// returns None.
    fn redirect(&self, q: &serde_json::Value) -> Option<String> {
        q.as_object()
            .and_then(|x| x.get("query"))
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("redirects"))
            .and_then(|x| x.as_array())
            .and_then(|x| x.into_iter().next())
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("to"))
            .and_then(|x| x.as_str())
            .map(|x| x.to_owned())
    }

    /// Given a parsed response, usually we access the first page with the data
    fn get_first_page<'parsed>(&self, data: &'parsed serde_json::Value) -> Option<&'parsed serde_json::Value> {
        let pages = data
            .as_object()
            .and_then(|x| x.get("query"))
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("pages"))
            .and_then(|x| x.as_object());
        let pageid = match pages {
            Some(some_pages) => match some_pages.keys().next() {
                Some(pageid) => pageid,
                None => return None,
            },
            None => return None,
        };
        pages.unwrap().get(pageid)
    }

    /// Gets the markdown content of the article.
    pub fn get_content(&self) -> Result<String> {
        let qp = self.identifier.query_param();
        let q = try!(self.wikipedia.query(vec![
            ("prop", "extracts|revisions"),
            ("explaintext", ""),
            ("rvprop", "ids"),
            ("redirects", ""),
            ("format", "json"),
            ("action", "query"),
            (&*qp.0, &*qp.1),
        ].into_iter()));

        match self.redirect(&q) {
            Some(r) => return Page::from_title(&self.wikipedia, r).get_content(),
            None => (),
        };

        Ok(try!(self.get_first_page(&q)
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("extract"))
            .and_then(|x| x.as_str())
            .ok_or(Error::JSONPathError))
            .to_owned())
    }

    /// Gets the html content of the article.
    pub fn get_html_content(&self) -> Result<String> {
        let qp = self.identifier.query_param();
        let q = try!(self.wikipedia.query(vec![
            ("prop", "revisions"),
            ("rvprop", "content"),
            ("rvlimit", "1"),
            ("rvparse", ""),
            ("redirects", ""),
            ("format", "json"),
            ("action", "query"),
            (&*qp.0, &*qp.1),
        ].into_iter()));

        match self.redirect(&q) {
            Some(r) => return Page::from_title(&self.wikipedia, r).get_html_content(),
            None => (),
        }

        Ok(try!(self.get_first_page(&q)
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("revisions"))
            .and_then(|x| x.as_array())
            .and_then(|x| x.into_iter().next())
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("*"))
            .and_then(|x| x.as_str())
            .ok_or(Error::JSONPathError))
            .to_owned())
    }

    /// Gets a summary of the article.
    pub fn get_summary(&self) -> Result<String> {
        let qp = self.identifier.query_param();
        let q = try!(self.wikipedia.query(vec![
            ("prop", "extracts"),
            ("explaintext", ""),
            ("exintro", ""),
            ("redirects", ""),
            ("format", "json"),
            ("action", "query"),
            (&*qp.0, &*qp.1),
        ].into_iter()));

        match self.redirect(&q) {
            Some(r) => return Page::from_title(&self.wikipedia, r).get_summary(),
            None => (),
        }

        Ok(try!(self.get_first_page(&q)
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("extract"))
            .and_then(|x| x.as_str())
            .ok_or(Error::JSONPathError))
            .to_owned())
    }

    /// Receive a json object and extracts any `continue` parameters to be
    /// used when browsing following pages.
    fn parse_cont(&self, q: &serde_json::Value) -> Result<Option<Vec<(String, String)>>> {
        let cont = match q
            .as_object()
            .and_then(|x| x.get("continue"))
            .and_then(|x| x.as_object()) {
            Some(v) => v,
            None => return Ok(None),
        };
        let mut cont_v = vec![];
        for (k, v) in cont.into_iter() {
            let value = match *v {
                serde_json::Value::Null => "".to_owned(),
                serde_json::Value::Bool(b) => if b { "1" } else { "0" }.to_owned(),
                serde_json::Value::Number(ref f) => format!("{}", f),
                serde_json::Value::String(ref s) => s.clone(),
                _ => return Err(Error::JSONPathError),
            };
            cont_v.push((k.clone(), value));
        }
        Ok(Some(cont_v))
    }

    fn request_images(&self, cont: &Option<Vec<(String, String)>>) ->
            Result<(Vec<serde_json::Value>, Option<Vec<(String, String)>>)> {
        cont!(self, cont,
            ("generator", "images"),
            ("gimlimit", &*self.wikipedia.images_results),
            ("prop", "imageinfo"),
            ("iiprop", "url")
        )
    }

    /// Creates an iterator to view all images in the `Page`.
    pub fn get_images(&self) -> Result<Iter<A, iter::Image>> {
        Iter::new(&self)
    }

    fn request_extlinks(&self, cont: &Option<Vec<(String, String)>>) ->
            Result<(Vec<serde_json::Value>, Option<Vec<(String, String)>>)> {
        let a:Result<(Vec<serde_json::Value>, _)> = cont!(self, cont,
            ("prop", "extlinks"),
            ("ellimit", &*self.wikipedia.links_results)
        );
        a.map(|(pages, cont)| {
            let page = match pages.into_iter().next() {
                Some(p) => p,
                None => return (Vec::new(), None),
            };
            (page
                .as_object()
                .and_then(|x| x.get("extlinks"))
                .and_then(|x| x.as_array())
                .map(|x| x.into_iter().cloned().collect())
                .unwrap_or(Vec::new()), cont)
        })
    }

    /// Creates an iterator to view all references (external links) in the `Page`.
    pub fn get_references(&self) -> Result<Iter<A, iter::Reference>> {
        Iter::new(&self)
    }

    fn request_links(&self, cont: &Option<Vec<(String, String)>>) ->
            Result<(Vec<serde_json::Value>, Option<Vec<(String, String)>>)> {
        let a:Result<(Vec<serde_json::Value>, _)> = cont!(self, cont,
            ("prop", "links"),
            ("plnamespace", "0"),
            ("ellimit", &*self.wikipedia.links_results)
        );
        a.map(|(pages, cont)| {
            let page = match pages.into_iter().next() {
                Some(p) => p,
                None => return (Vec::new(), None),
            };
            (page
                .as_object()
                .and_then(|x| x.get("links"))
                .and_then(|x| x.as_array())
                .map(|x| x.into_iter().cloned().collect())
                .unwrap_or(Vec::new()), cont)
        })
    }

    /// Creates an iterator to view all internal links in the `Page`.
    pub fn get_links(&self) -> Result<Iter<A, iter::Link>> {
        Iter::new(&self)
    }

    fn request_categories(&self, cont: &Option<Vec<(String, String)>>) ->
            Result<(Vec<serde_json::Value>, Option<Vec<(String, String)>>)> {
        let a:Result<(Vec<serde_json::Value>, _)> = cont!(self, cont,
            ("prop", "categories"),
            ("cllimit", &*self.wikipedia.categories_results)
        );
        a.map(|(pages, cont)| {
            let page = match pages.into_iter().next() {
                Some(p) => p,
                None => return (Vec::new(), None),
            };
            (page
                .as_object()
                .and_then(|x| x.get("categories"))
                .and_then(|x| x.as_array())
                .map(|x| x.into_iter().cloned().collect())
                .unwrap_or(Vec::new()), cont)
        })
    }

    /// Creates an iterator to view all categories of the `Page`.
    pub fn get_categories(&self) -> Result<Iter<A, iter::Category>> {
        Iter::new(&self)
    }

    fn request_langlinks(&self, cont: &Option<Vec<(String, String)>>) ->
            Result<(Vec<serde_json::Value>, Option<Vec<(String, String)>>)> {
        let a:Result<(Vec<serde_json::Value>, _)> = cont!(self, cont,
            ("prop", "langlinks"),
            ("lllimit", &*self.wikipedia.links_results)
        );
        a.map(|(pages, cont)| {
            let page = match pages.into_iter().next() {
                Some(p) => p,
                None => return (Vec::new(), None),
            };
            (page
                .as_object()
                .and_then(|x| x.get("langlinks"))
                .and_then(|x| x.as_array())
                .map(|x| x.into_iter().cloned().collect())
                .unwrap_or(Vec::new()), cont)
        })
    }

    /// Creates an iterator to view all langlinks of the `Page`.
    /// This iterates over the page titles in all available languages.
    pub fn get_langlinks(&self) -> Result<Iter<A, iter::LangLink>> {
        Iter::new(&self)
    }

    /// Returns the latitude and longitude associated to the `Page` if any.
    pub fn get_coordinates(&self) -> Result<Option<(f64, f64)>> {
        let qp = self.identifier.query_param();
        let params = vec![
            ("prop", "coordinates"),
            ("colimit", "max"),
            ("redirects", ""),
            ("format", "json"),
            ("action", "query"),
            (&*qp.0, &*qp.1),
        ];
        let q = try!(self.wikipedia.query(params.into_iter()));

        match self.redirect(&q) {
            Some(r) => return Page::from_title(&self.wikipedia, r).get_coordinates(),
            None => (),
        }

        let coord = match self.get_first_page(&q)
                .and_then(|x| x.as_object())
                .and_then(|x| x.get("coordinates"))
                .and_then(|x| x.as_array())
                .and_then(|x| x.into_iter().next())
                .and_then(|x| x.as_object()) {
            Some(c) => c,
            None => return Ok(None),
        };
        Ok(Some((
            try!(coord.get("lat").and_then(|x| x.as_f64()).ok_or(Error::JSONPathError)),
            try!(coord.get("lon").and_then(|x| x.as_f64()).ok_or(Error::JSONPathError)),
        )))
    }

    /// Fetches all sections of the article.
    pub fn get_sections(&self) -> Result<Vec<String>> {
        let pageid = try!(self.get_pageid());
        let params = vec![
            ("prop", "sections"),
            ("format", "json"),
            ("action", "parse"),
            ("pageid", &*pageid),
        ];
        let q = try!(self.wikipedia.query(params.into_iter()));

        Ok(try!(q
            .as_object()
            .and_then(|x| x.get("parse"))
            .and_then(|x| x.as_object())
            .and_then(|x| x.get("sections"))
            .and_then(|x| x.as_array())
            .ok_or(Error::JSONPathError))
            .into_iter()
            .filter_map(|x| x.as_object()
                    .and_then(|x| x.get("line"))
                    .and_then(|x| x.as_str())
                    .map(|x| x.to_owned())
                    )
            .collect())
    }

    /// Fetches the content of a section.
    pub fn get_section_content(&self, title: &str) -> Result<Option<String>> {
        let headr = format!("== {} ==", title);
        let content = try!(self.get_content());
        let index = match content.find(&*headr) {
            Some(i) => headr.len() + i,
            None => return Ok(None),
        };
        let end = match content[index..].find("==") {
            Some(i) => index + i,
            None => content.len(),
        };
        Ok(Some(content[index..end].to_owned()))
    }
}

impl<'a, A: http::HttpClient> PartialEq<Page<'a, A>> for Page<'a, A> {
    fn eq(&self, other: &Page<A>) -> bool {
        match self.identifier {
            TitlePageId::Title(ref t1) => match other.identifier {
                TitlePageId::Title(ref t2) => t1 == t2,
                TitlePageId::PageId(_) => false,
            },
            TitlePageId::PageId(ref p1) => match other.identifier {
                TitlePageId::Title(_) => false,
                TitlePageId::PageId(ref p2) => p1 == p2,
            },
        }
    }
}

#[cfg(test)]
mod test {
    use super::Wikipedia;
    use super::http::HttpClient;
    use super::iter;
    use std::sync::Mutex;

    struct MockClient {
        pub url: Mutex<Vec<String>>,
        pub user_agent: Option<String>,
        pub arguments: Mutex<Vec<Vec<(String, String)>>>,
        pub response: Mutex<Vec<String>>,
    }

    impl Default for MockClient {
        fn default() -> Self {
            MockClient {
                url: Mutex::new(Vec::new()),
                user_agent: None,
                arguments: Mutex::new(Vec::new()),
                response: Mutex::new(Vec::new()),
            }
        }
    }

    impl super::http::HttpClient for MockClient {
        fn user_agent(&mut self, user_agent: String) {
            self.user_agent = Some(user_agent)
        }

        fn get<'a, I>(&self, base_url: &str, args: I) -> Result<String, super::http::Error>
                where I: Iterator<Item=(&'a str, &'a str)> {
            self.url.lock().unwrap().push(base_url.to_owned());
            self.arguments.lock().unwrap().push(args.map(|x| (x.0.to_owned(), x.1.to_owned())).collect());
            Ok(self.response.lock().unwrap().remove(0))
        }
    }

    #[test]
    fn base_url() {
        let mut wikipedia = Wikipedia::<MockClient>::default();
        assert_eq!(wikipedia.base_url(), "https://en.wikipedia.org/w/api.php");
        wikipedia.language = "es".to_owned();
        assert_eq!(wikipedia.base_url(), "https://es.wikipedia.org/w/api.php");

        wikipedia.set_base_url("https://hello.{language}.world/");
        assert_eq!(wikipedia.base_url(), "https://hello.es.world/");

        wikipedia.set_base_url("https://hello.world/");
        assert_eq!(wikipedia.base_url(), "https://hello.world/");
    }

    #[test]
    fn user_agent() {
        let mut wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{}".to_owned());
        wikipedia.search("hello world").unwrap_err();
        assert_eq!(&*wikipedia.client.user_agent.unwrap(), "wikipedia (https://github.com/seppo0010/wikipedia-rs)");

        let mut client = MockClient::default();
        client.user_agent("hello world".to_owned());
        client.response.lock().unwrap().push("{}".to_owned());
        wikipedia.client = client;
        wikipedia.search("hello world").unwrap_err();
        assert_eq!(&*wikipedia.client.user_agent.unwrap(), "hello world");
    }

    #[test]
    fn search() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"search\":[{\"title\":\"hello\"}, {\"title\":\"world\"}]}}".to_owned());
        assert_eq!(
                wikipedia.search("hello world").unwrap(),
                vec![
                "hello".to_owned(),
                "world".to_owned(),
                ]);
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("list".to_owned(), "search".to_owned()),
                    ("srprop".to_owned(), "".to_owned()),
                    ("srlimit".to_owned(), "10".to_owned()),
                    ("srsearch".to_owned(), "hello world".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned())
                    ]]);
    }

    #[test]
    fn geosearch() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"geosearch\":[{\"title\":\"hello\"}, {\"title\":\"world\"}]}}".to_owned());
        assert_eq!(
                wikipedia.geosearch(-34.603333, -58.381667, 10).unwrap(),
                vec![
                "hello".to_owned(),
                "world".to_owned(),
                ]);
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("list".to_owned(), "geosearch".to_owned()),
                    ("gsradius".to_owned(), "10".to_owned()),
                    ("gscoord".to_owned(), "-34.603333|-58.381667".to_owned()),
                    ("gslimit".to_owned(), "10".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned())
                    ]]);
    }

    #[test]
    fn random_count() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"random\":[{\"title\":\"hello\"}, {\"title\":\"world\"}]}}".to_owned());
        assert_eq!(
                wikipedia.random_count(10).unwrap(),
                vec![
                "hello".to_owned(),
                "world".to_owned(),
                ]);
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("list".to_owned(), "random".to_owned()),
                    ("rnnamespace".to_owned(), "0".to_owned()),
                    ("rnlimit".to_owned(), "10".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned())
                    ]]);
    }

    #[test]
    fn random() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"random\":[{\"title\":\"hello\"}, {\"title\":\"world\"}]}}".to_owned());
        assert_eq!(
                wikipedia.random().unwrap(),
                Some("hello".to_owned())
                );
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("list".to_owned(), "random".to_owned()),
                    ("rnnamespace".to_owned(), "0".to_owned()),
                    ("rnlimit".to_owned(), "1".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned())
                    ]]);
    }

    #[test]
    fn page_content() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{\"extract\":\"hello\"}}}}".to_owned());
        let page = wikipedia.page_from_pageid("4138548".to_owned());
        let html = page.get_content().unwrap();
        assert_eq!(
                html,
                "hello".to_owned()
                );
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("prop".to_owned(), "extracts|revisions".to_owned()),
                    ("explaintext".to_owned(), "".to_owned()),
                    ("rvprop".to_owned(), "ids".to_owned()),
                    ("redirects".to_owned(), "".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("pageids".to_owned(), "4138548".to_owned()),
                    ]]);
    }

    #[test]
    fn page_html_content() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{\"revisions\":[{\"*\":\"hello\"}]}}}}".to_owned());
        let page = wikipedia.page_from_pageid("4138548".to_owned());
        let html = page.get_html_content().unwrap();
        assert_eq!(
                html,
                "hello".to_owned()
                );
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("prop".to_owned(), "revisions".to_owned()),
                    ("rvprop".to_owned(), "content".to_owned()),
                    ("rvlimit".to_owned(), "1".to_owned()),
                    ("rvparse".to_owned(), "".to_owned()),
                    ("redirects".to_owned(), "".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("pageids".to_owned(), "4138548".to_owned()),
                    ]]);
    }

    #[test]
    fn page_summary() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{\"extract\":\"hello\"}}}}".to_owned());
        let page = wikipedia.page_from_title("Parkinson's law of triviality".to_owned());
        let summary = page.get_summary().unwrap();
        assert_eq!(
                summary,
                "hello".to_owned()
                );
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("prop".to_owned(), "extracts".to_owned()),
                    ("explaintext".to_owned(), "".to_owned()),
                    ("exintro".to_owned(), "".to_owned()),
                    ("redirects".to_owned(), "".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "Parkinson\'s law of triviality".to_owned())
                    ]]);
    }

    #[test]
    fn page_redirect_summary() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"redirects\":[{\"to\":\"hello world\"}]}}".to_owned());
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{\"extract\":\"hello\"}}}}".to_owned());
        let page = wikipedia.page_from_title("Parkinson's law of triviality".to_owned());
        let summary = page.get_summary().unwrap();
        assert_eq!(
                summary,
                "hello".to_owned()
                );
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec![
                "https://en.wikipedia.org/w/api.php".to_owned(),
                "https://en.wikipedia.org/w/api.php".to_owned(),
                ]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![
                vec![
                    ("prop".to_owned(), "extracts".to_owned()),
                    ("explaintext".to_owned(), "".to_owned()),
                    ("exintro".to_owned(), "".to_owned()),
                    ("redirects".to_owned(), "".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "Parkinson\'s law of triviality".to_owned())
                ],
                vec![
                    ("prop".to_owned(), "extracts".to_owned()),
                    ("explaintext".to_owned(), "".to_owned()),
                    ("exintro".to_owned(), "".to_owned()),
                    ("redirects".to_owned(), "".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "hello world".to_owned())
                    ]
                ]
                );
    }

    #[test]
    fn page_images() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"continue\": {\"lol\":\"1\"},\"query\":{\"pages\":{\"a\":{\"title\":\"Image 1\", \"imageinfo\":[{\"url\": \"http://example.com/image1.jpg\", \"descriptionurl\": \"http://example.com/image1.jpg.html\"}]}}}}".to_owned());
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{\"title\":\"Image 2\", \"imageinfo\":[{\"url\": \"http://example.com/image2.jpg\", \"descriptionurl\": \"http://example.com/image2.jpg.html\"}]}}}}".to_owned());
        let page = wikipedia.page_from_title("Parkinson's law of triviality".to_owned());
        let images = page.get_images().unwrap().collect::<Vec<_>>();
        assert_eq!(
                images,
                vec![
                iter::Image {
                    url: "http://example.com/image1.jpg".to_owned(),
                    title: "Image 1".to_owned(),
                    description_url: "http://example.com/image1.jpg.html".to_owned(),
                },
                iter::Image {
                    url: "http://example.com/image2.jpg".to_owned(),
                    title: "Image 2".to_owned(),
                    description_url: "http://example.com/image2.jpg.html".to_owned(),
                }
                ]);
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec![
                "https://en.wikipedia.org/w/api.php".to_owned(),
                "https://en.wikipedia.org/w/api.php".to_owned(),
                ]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![
                vec![
                    ("generator".to_owned(), "images".to_owned()),
                    ("gimlimit".to_owned(), "max".to_owned()),
                    ("prop".to_owned(), "imageinfo".to_owned()),
                    ("iiprop".to_owned(), "url".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "Parkinson\'s law of triviality".to_owned()),
                    ("continue".to_owned(), "".to_owned())
                ],
                vec![
                    ("generator".to_owned(), "images".to_owned()),
                    ("gimlimit".to_owned(), "max".to_owned()),
                    ("prop".to_owned(), "imageinfo".to_owned()),
                    ("iiprop".to_owned(), "url".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "Parkinson\'s law of triviality".to_owned()),
                    ("lol".to_owned(), "1".to_owned())
                ]
                ]
                );
    }

    #[test]
    fn page_coordinates() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{\"coordinates\":[{\"lat\": 2.1, \"lon\":-1.3}]}}}}".to_owned());
        let page = wikipedia.page_from_title("World".to_owned());
        let coordinates = page.get_coordinates().unwrap().unwrap();
        assert_eq!(
                coordinates,
                (2.1, -1.3)
                );
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("prop".to_owned(), "coordinates".to_owned()),
                    ("colimit".to_owned(), "max".to_owned()),
                    ("redirects".to_owned(), "".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "World".to_owned())
                    ]]);
    }

    #[test]
    fn page_no_coordinates() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{}}}}".to_owned());
        let page = wikipedia.page_from_title("World".to_owned());
        assert!(page.get_coordinates().unwrap().is_none());
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("prop".to_owned(), "coordinates".to_owned()),
                    ("colimit".to_owned(), "max".to_owned()),
                    ("redirects".to_owned(), "".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "World".to_owned())
                    ]]);
    }

    #[test]
    fn get_references() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"continue\": {\"lol\":\"1\"},\"query\":{\"pages\":{\"a\":{\"extlinks\":[{\"*\": \"//example.com/reference1.html\"}]}}}}".to_owned());
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{\"extlinks\":[{\"*\": \"//example.com/reference2.html\"}]}}}}".to_owned());
        let page = wikipedia.page_from_title("World".to_owned());
        assert_eq!(
                page.get_references().unwrap().collect::<Vec<_>>(),
                vec![
                iter::Reference {
                    url: "http://example.com/reference1.html".to_owned(),
                },
                iter::Reference {
                    url: "http://example.com/reference2.html".to_owned(),
                }
                ]);
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec![
                "https://en.wikipedia.org/w/api.php".to_owned(),
                "https://en.wikipedia.org/w/api.php".to_owned(),
                ]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("prop".to_owned(), "extlinks".to_owned()),
                    ("ellimit".to_owned(), "max".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "World".to_owned()),
                    ("continue".to_owned(), "".to_owned())
                ],
                vec![
                    ("prop".to_owned(), "extlinks".to_owned()),
                    ("ellimit".to_owned(), "max".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "World".to_owned()),
                    ("lol".to_owned(), "1".to_owned())
                ]
                ]);
    }

    #[test]
    fn get_links() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"continue\": {\"lol\":\"1\"},\"query\":{\"pages\":{\"a\":{\"links\":[{\"title\": \"Hello\"}]}}}}".to_owned());
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{\"links\":[{\"title\": \"World\"}]}}}}".to_owned());
        let page = wikipedia.page_from_title("World".to_owned());
        assert_eq!(
                page.get_links().unwrap().collect::<Vec<_>>(),
                vec![
                iter::Link {
                    title: "Hello".to_owned(),
                },
                iter::Link {
                    title: "World".to_owned(),
                }
                ]);
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec![
                "https://en.wikipedia.org/w/api.php".to_owned(),
                "https://en.wikipedia.org/w/api.php".to_owned(),
                ]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![
                vec![
                    ("prop".to_owned(), "links".to_owned()),
                    ("plnamespace".to_owned(), "0".to_owned()),
                    ("ellimit".to_owned(), "max".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "World".to_owned()),
                    ("continue".to_owned(), "".to_owned()),
                ],
                vec![
                    ("prop".to_owned(), "links".to_owned()),
                    ("plnamespace".to_owned(), "0".to_owned()),
                    ("ellimit".to_owned(), "max".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "World".to_owned()),
                    ("lol".to_owned(), "1".to_owned()),
                ]
                ]);
    }

    #[test]
    fn get_categories() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"continue\": {\"lol\":\"1\"},\"query\":{\"pages\":{\"a\":{\"categories\":[{\"title\": \"Hello\"}]}}}}".to_owned());
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"pages\":{\"a\":{\"categories\":[{\"title\": \"Category: World\"}]}}}}".to_owned());
        let page = wikipedia.page_from_title("World".to_owned());
        assert_eq!(
                page.get_categories().unwrap().collect::<Vec<_>>(),
                vec![
                iter::Category {
                    title: "Hello".to_owned(),
                },
                iter::Category {
                    title: "World".to_owned(),
                }
                ]);
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec![
                "https://en.wikipedia.org/w/api.php".to_owned(),
                "https://en.wikipedia.org/w/api.php".to_owned(),
                ]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![
                vec![
                    ("prop".to_owned(), "categories".to_owned()),
                    ("cllimit".to_owned(), "max".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "World".to_owned()),
                    ("continue".to_owned(), "".to_owned()),
                ],
                vec![
                    ("prop".to_owned(), "categories".to_owned()),
                    ("cllimit".to_owned(), "max".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned()),
                    ("titles".to_owned(), "World".to_owned()),
                    ("lol".to_owned(), "1".to_owned()),
                ]
                ]);
    }

    #[test]
    fn sections() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"parse\":{\"sections\":[{\"line\":\"hello\"}, {\"line\":\"world\"}]}}".to_owned());
        let page = wikipedia.page_from_pageid("123".to_owned());
        assert_eq!(
                page.get_sections().unwrap(),
                vec!["hello".to_owned(), "world".to_owned()]
                );
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("prop".to_owned(), "sections".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "parse".to_owned()),
                    ("pageid".to_owned(), "123".to_owned())
                    ]]);
    }

    #[test]
    fn languages() {
        let wikipedia = Wikipedia::<MockClient>::default();
        wikipedia.client.response.lock().unwrap().push("{\"query\":{\"languages\":[{\"*\":\"hello\", \"code\":\"world\"}, {\"*\":\"foo\", \"code\":\"bar\"}]}}".to_owned());
        assert_eq!(
                wikipedia.get_languages().unwrap(),
                vec![
                    ("world".to_owned(), "hello".to_owned()),
                    ("bar".to_owned(), "foo".to_owned()),
                ]
                );
        assert_eq!(*wikipedia.client.url.lock().unwrap(),
                vec!["https://en.wikipedia.org/w/api.php".to_owned()]);
        assert_eq!(*wikipedia.client.arguments.lock().unwrap(),
                vec![vec![
                    ("meta".to_owned(), "siteinfo".to_owned()),
                    ("siprop".to_owned(), "languages".to_owned()),
                    ("format".to_owned(), "json".to_owned()),
                    ("action".to_owned(), "query".to_owned())
                    ]]);
    }
}