gr/github/
merge_request.rs

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
use super::Github;
use crate::{
    api_traits::{ApiOperation, CommentMergeRequest, MergeRequest, NumberDeltaErr, RemoteProject},
    cli::browse::BrowseOptions,
    cmds::{
        merge_request::{
            Comment, CommentMergeRequestBodyArgs, CommentMergeRequestListBodyArgs,
            MergeRequestBodyArgs, MergeRequestListBodyArgs, MergeRequestResponse,
            MergeRequestState,
        },
        project::MrMemberType,
    },
    http::{self, Body},
    io::{HttpRunner, Response},
    json_loads,
    remote::query,
};

use crate::{error, Result};

impl<R> Github<R> {
    fn url_list_merge_requests(&self, args: &MergeRequestListBodyArgs) -> String {
        let state = match args.state {
            MergeRequestState::Opened => "open".to_string(),
            // Github has no distinction between closed and merged. A merged
            // pull request is considered closed.
            MergeRequestState::Closed | MergeRequestState::Merged => "closed".to_string(),
        };
        if args.assignee.is_some() {
            return format!(
                "{}/issues?state={}&filter=assigned",
                self.rest_api_basepath, state
            );
        } else if args.author.is_some() {
            return format!(
                "{}/issues?state={}&filter=created",
                self.rest_api_basepath, state
            );
        }
        format!(
            "{}/repos/{}/pulls?state={}",
            self.rest_api_basepath, self.path, state
        )
    }

    fn resource_comments_metadata_url(&self, args: CommentMergeRequestListBodyArgs) -> String {
        let url = format!(
            "{}/repos/{}/issues/{}/comments?page=1",
            self.rest_api_basepath, self.path, args.id
        );
        url
    }
}

impl<R: HttpRunner<Response = Response>> MergeRequest for Github<R> {
    fn open(&self, args: MergeRequestBodyArgs) -> Result<MergeRequestResponse> {
        let mut body = Body::new();
        body.add("base", args.target_branch);
        body.add("title", args.title);
        body.add("body", args.description);
        // Add draft in payload only when requested. It seems that Github opens
        // PR in draft mode even when the draft value is false.
        if args.draft {
            body.add("draft", args.draft.to_string());
        }
        let target_repo = args.target_repo.clone();
        let mut mr_url = format!(
            "{}/repos/{}/pulls",
            self.rest_api_basepath,
            self.path.clone()
        );
        if !target_repo.is_empty() {
            mr_url = format!(
                "{}/repos/{}/pulls",
                self.rest_api_basepath, args.target_repo
            );
            let owner_path = self.path.split('/').collect::<Vec<&str>>();
            if owner_path.len() != 2 {
                return Err(error::GRError::ApplicationError(format!(
                    "Invalid path format in git config: [{}] while attempting \
                    to retrieve existing pull request. Expected owner/repo",
                    self.path
                ))
                .into());
            }
            let remote_pr_branch = format!("{}:{}", owner_path[0], args.source_branch.clone());
            body.add("head", remote_pr_branch);
        } else {
            body.add("head", args.source_branch.clone());
        }

        match query::send_raw(
            &self.runner,
            &mr_url,
            Some(&body),
            self.request_headers(),
            ApiOperation::MergeRequest,
            http::Method::POST,
        ) {
            Ok(response) => {
                match response.status {
                    201 => {
                        let body = response.body;
                        // If target repo is provided bypass user assignation
                        // Do the same when assignee is not provided

                        if !target_repo.is_empty()
                            || args.assignee.mr_member_type == MrMemberType::Empty
                        {
                            let json_value = json_loads(&body)?;
                            return Ok(MergeRequestResponse::from(GithubMergeRequestFields::from(
                                &json_value,
                            )));
                        }
                        // This is a new pull request
                        // Set the assignee to the pull request. Currently, the
                        // only way to set the assignee to a pull request is by
                        // using the issues API. All pull requests in Github API v3
                        // are considered to be issues, but not the other way
                        // around.
                        // See note in https://docs.github.com/en/rest/issues/issues#list-repository-issues
                        // Note: Github's REST API v3 considers every pull request
                        // an issue, but not every issue is a pull request.
                        // https://docs.github.com/en/rest/issues/issues#update-an-issue
                        let merge_request_json = json_loads(&body)?;
                        let id = merge_request_json["number"].to_string();
                        let issues_url = format!(
                            "{}/repos/{}/issues/{}",
                            self.rest_api_basepath, self.path, id
                        );
                        let mut body = Body::new();
                        let assignees = vec![args.assignee.username.as_str()];
                        body.add("assignees", &assignees);
                        query::send::<_, &Vec<&str>, _>(
                            &self.runner,
                            &issues_url,
                            Some(&body),
                            self.request_headers(),
                            ApiOperation::MergeRequest,
                            |value| GithubMergeRequestFields::from(value).into(),
                            http::Method::PATCH,
                        )
                    }
                    422 => {
                        // There is an existing pull request already.
                        // Gather its URL by querying Github pull requests filtering by
                        // head owner:branch
                        // Ref:
                        // https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#list-pull-requests--parameters

                        // The path has owner/repo format.
                        let owner_path = self.path.split('/').collect::<Vec<&str>>();
                        if owner_path.len() != 2 {
                            return Err(error::GRError::ApplicationError(format!(
                                "Invalid path format in git config: [{}] while attempting \
                                to retrieve existing pull request. Expected owner/repo",
                                self.path
                            ))
                            .into());
                        }
                        let remote_pr_branch = format!("{}:{}", owner_path[0], args.source_branch);
                        let existing_mr_url = format!("{}?head={}", mr_url, remote_pr_branch);
                        let response = query::get_raw::<_, ()>(
                            &self.runner,
                            &existing_mr_url,
                            None,
                            self.request_headers(),
                            ApiOperation::MergeRequest,
                        )?;
                        let merge_requests_json: Vec<serde_json::Value> =
                            serde_json::from_str(&response.body)?;
                        if merge_requests_json.len() == 1 {
                            let mr_id = merge_requests_json[0]["number"].as_i64().unwrap();
                            if args.amend {
                                // Amend the existing pull request
                                let url = format!(
                                    "{}/repos/{}/pulls/{}",
                                    self.rest_api_basepath, self.path, mr_id
                                );
                                query::send_json::<_, String>(
                                    &self.runner,
                                    &url,
                                    Some(&body),
                                    self.request_headers(),
                                    ApiOperation::MergeRequest,
                                    http::Method::PATCH,
                                )?;
                            }
                            Ok(MergeRequestResponse::builder()
                                .id(mr_id)
                                .web_url(
                                    merge_requests_json[0]["html_url"]
                                        .to_string()
                                        .trim_matches('"')
                                        .to_string(),
                                )
                                .build()
                                .unwrap())
                        } else {
                            Err(error::GRError::RemoteUnexpectedResponseContract(format!(
                                "There should have been an existing pull request at \
                                URL: {} but got an unexpected response: {}",
                                existing_mr_url, response.body
                            ))
                            .into())
                        }
                    }
                    _ => Err(error::gen(format!(
                        "Failed to create merge request. Status code: {}, Body: {}",
                        response.status, response.body
                    ))),
                }
            }
            Err(err) => Err(err),
        }
    }

    fn list(&self, args: MergeRequestListBodyArgs) -> Result<Vec<MergeRequestResponse>> {
        let url = self.url_list_merge_requests(&args);
        let response = query::paged::<_, MergeRequestResponse>(
            &self.runner,
            &url,
            args.list_args,
            self.request_headers(),
            None,
            ApiOperation::MergeRequest,
            |value| GithubMergeRequestFields::from(value).into(),
        );
        if args.assignee.is_some() || args.author.is_some() {
            // Pull requests for the current authenticated user.
            // Filter those reponses that have pull_request not empty See ref:
            // https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28#list-issues-assigned-to-the-authenticated-user
            // Quoting Github's docs: Note: GitHub's REST API considers every
            // pull request an issue, but not every issue is a pull request. For
            // this reason, "Issues" endpoints may return both issues and pull
            // requests in the response. You can identify pull requests by the
            // pull_request key. Be aware that the id of a pull request returned
            // from "Issues" endpoints will be an issue id. To find out the pull
            // request id, use the "List pull requests" endpoint.
            let mut merge_requests = vec![];
            for mr in response? {
                if !mr.pull_request.is_empty() {
                    merge_requests.push(mr);
                }
            }
            return Ok(merge_requests);
        }
        response
    }

    fn merge(&self, id: i64) -> Result<MergeRequestResponse> {
        // https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#merge-a-pull-request
        //  /repos/{owner}/{repo}/pulls/{pull_number}/merge
        let url = format!(
            "{}/repos/{}/pulls/{}/merge",
            self.rest_api_basepath, self.path, id
        );
        query::send_json::<_, ()>(
            &self.runner,
            &url,
            None,
            self.request_headers(),
            ApiOperation::MergeRequest,
            http::Method::PUT,
        )?;
        // Response:
        // {
        //     "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
        //     "merged": true,
        //     "message": "Pull Request successfully merged"
        // }

        // We do not have the id nor the url available in the response. Compute
        // it and return it to the client so we can open the url if needed.
        Ok(MergeRequestResponse::builder()
            .id(id)
            .web_url(self.get_url(BrowseOptions::MergeRequestId(id)))
            .build()
            .unwrap())
    }

    fn get(&self, id: i64) -> Result<MergeRequestResponse> {
        let url = format!(
            "{}/repos/{}/pulls/{}",
            self.rest_api_basepath, self.path, id
        );
        query::get::<_, (), _>(
            &self.runner,
            &url,
            None,
            self.request_headers(),
            ApiOperation::MergeRequest,
            |value| GithubMergeRequestFields::from(value).into(),
        )
    }

    fn close(&self, id: i64) -> Result<MergeRequestResponse> {
        let url = format!(
            "{}/repos/{}/pulls/{}",
            self.rest_api_basepath, self.path, id
        );
        let mut body = Body::new();
        body.add("state", "closed");
        query::send::<_, &str, _>(
            &self.runner,
            &url,
            Some(&body),
            self.request_headers(),
            ApiOperation::MergeRequest,
            |value| GithubMergeRequestFields::from(value).into(),
            http::Method::PATCH,
        )
    }

    fn num_pages(&self, args: MergeRequestListBodyArgs) -> Result<Option<u32>> {
        let url = self.url_list_merge_requests(&args) + "&page=1";
        let headers = self.request_headers();
        query::num_pages(&self.runner, &url, headers, ApiOperation::MergeRequest)
    }

    fn num_resources(&self, args: MergeRequestListBodyArgs) -> Result<Option<NumberDeltaErr>> {
        let url = self.url_list_merge_requests(&args) + "&page=1";
        let headers = self.request_headers();
        query::num_resources(&self.runner, &url, headers, ApiOperation::MergeRequest)
    }

    fn approve(&self, _id: i64) -> Result<MergeRequestResponse> {
        todo!()
    }
}

impl<R: HttpRunner<Response = Response>> CommentMergeRequest for Github<R> {
    fn create(&self, args: CommentMergeRequestBodyArgs) -> Result<()> {
        let url = format!(
            "{}/repos/{}/issues/{}/comments",
            self.rest_api_basepath, self.path, args.id
        );
        let mut body = Body::new();
        body.add("body", args.comment);
        query::send_raw(
            &self.runner,
            &url,
            Some(&body),
            self.request_headers(),
            ApiOperation::MergeRequest,
            http::Method::POST,
        )?;
        Ok(())
    }

    fn list(&self, args: CommentMergeRequestListBodyArgs) -> Result<Vec<Comment>> {
        let url = format!(
            "{}/repos/{}/issues/{}/comments",
            self.rest_api_basepath, self.path, args.id
        );
        query::paged(
            &self.runner,
            &url,
            args.list_args,
            self.request_headers(),
            None,
            ApiOperation::MergeRequest,
            |value| GithubMergeRequestCommentFields::from(value).into(),
        )
    }

    fn num_pages(&self, args: CommentMergeRequestListBodyArgs) -> Result<Option<u32>> {
        let url = self.resource_comments_metadata_url(args);
        query::num_pages(
            &self.runner,
            &url,
            self.request_headers(),
            ApiOperation::MergeRequest,
        )
    }

    fn num_resources(
        &self,
        args: CommentMergeRequestListBodyArgs,
    ) -> Result<Option<NumberDeltaErr>> {
        let url = self.resource_comments_metadata_url(args);
        query::num_resources(
            &self.runner,
            &url,
            self.request_headers(),
            ApiOperation::MergeRequest,
        )
    }
}

pub struct GithubMergeRequestFields {
    fields: MergeRequestResponse,
}

impl From<&serde_json::Value> for GithubMergeRequestFields {
    fn from(merge_request_data: &serde_json::Value) -> Self {
        GithubMergeRequestFields {
            fields: MergeRequestResponse::builder()
                .id(merge_request_data["number"].as_i64().unwrap())
                .web_url(merge_request_data["html_url"].as_str().unwrap().to_string())
                .source_branch(
                    merge_request_data["head"]["ref"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                )
                .sha(
                    merge_request_data["merge_commit_sha"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                )
                .author(
                    merge_request_data["user"]["login"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                )
                .updated_at(
                    merge_request_data["updated_at"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                )
                .created_at(
                    merge_request_data["created_at"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                )
                .title(
                    merge_request_data["title"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                )
                .pull_request(
                    merge_request_data["pull_request"]["html_url"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                )
                .description(
                    merge_request_data["body"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                )
                .merged_at(
                    merge_request_data["merged_at"]
                        .as_str()
                        .unwrap_or_default()
                        .to_string(),
                )
                // Not available in the response. Set it to the same ID as the pull request
                .pipeline_id(Some(merge_request_data["number"].as_i64().unwrap()))
                .pipeline_url(
                    merge_request_data["html_url"]
                        .as_str()
                        .map(|url| format!("{}/checks", url)),
                )
                .build()
                .unwrap(),
        }
    }
}

impl From<GithubMergeRequestFields> for MergeRequestResponse {
    fn from(fields: GithubMergeRequestFields) -> Self {
        fields.fields
    }
}

pub struct GithubMergeRequestCommentFields {
    comment: Comment,
}

impl From<&serde_json::Value> for GithubMergeRequestCommentFields {
    fn from(comment_data: &serde_json::Value) -> Self {
        GithubMergeRequestCommentFields {
            comment: Comment::builder()
                .id(comment_data["id"].as_i64().unwrap())
                .author(comment_data["user"]["login"].as_str().unwrap().to_string())
                .created_at(comment_data["created_at"].as_str().unwrap().to_string())
                .body(comment_data["body"].as_str().unwrap().to_string())
                .build()
                .unwrap(),
        }
    }
}

impl From<GithubMergeRequestCommentFields> for Comment {
    fn from(fields: GithubMergeRequestCommentFields) -> Self {
        fields.comment
    }
}

#[cfg(test)]
mod test {

    use crate::{
        cmds::project::{Member, MrMemberType},
        http::{self, Headers},
        remote::ListBodyArgs,
        setup_client,
        test::utils::{
            default_github, get_contract, BasePath, ClientType, ContractType, Domain,
            ResponseContracts,
        },
    };

    use super::*;

    #[test]
    fn test_open_merge_request() {
        let responses = ResponseContracts::new(ContractType::Github)
            .add_contract(200, "merge_request.json", None)
            .add_contract(201, "merge_request.json", None);
        let (client, github) = setup_client!(responses, default_github(), dyn MergeRequest);
        let assignee = Member::builder()
            .name("tom".to_string())
            .username("tsawyer".to_string())
            .mr_member_type(MrMemberType::Filled)
            .id(1234)
            .build()
            .unwrap();
        let mr_args = MergeRequestBodyArgs::builder()
            .assignee(assignee)
            .build()
            .unwrap();
        assert!(github.open(mr_args).is_ok());
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/issues/23",
            *client.url(),
        );
        let actual_method = client.http_method.borrow();
        assert_eq!(http::Method::POST, actual_method[0]);
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_open_merge_request_on_target_repository() {
        let mr_args = MergeRequestBodyArgs::builder()
            .target_repo("jordilin/gitar".to_string())
            .build()
            .unwrap();
        let responses = ResponseContracts::new(ContractType::Github)
            .add_contract(200, "merge_request.json", None)
            .add_contract(201, "merge_request.json", None);
        // current repo, targetting jordilin/gitar
        let client_type = ClientType::Github(
            Domain("github.com".to_string()),
            BasePath("jdoe/gitar".to_string()),
        );
        let (client, github) = setup_client!(responses, client_type, dyn MergeRequest);

        assert!(github.open(mr_args).is_ok());
        assert_eq!(
            "https://api.github.com/repos/jordilin/gitar/pulls",
            *client.url(),
        );
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_open_merge_request_with_no_assignee() {
        let responses = ResponseContracts::new(ContractType::Github)
            .add_contract(200, "merge_request.json", None)
            .add_contract(201, "merge_request.json", None);
        let (client, github) = setup_client!(responses, default_github(), dyn MergeRequest);
        let assignee = Member::default();
        let mr_args = MergeRequestBodyArgs::builder()
            .assignee(assignee)
            .build()
            .unwrap();
        assert!(github.open(mr_args).is_ok());
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/pulls",
            *client.url(),
        );
        let actual_method = client.http_method.borrow();
        assert_eq!(http::Method::POST, actual_method[0]);
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
        let actual_body = client.request_body.borrow();
        assert!(!actual_body.contains("assignees"));
    }

    #[test]
    fn test_open_merge_request_error_status_code() {
        let mr_args = MergeRequestBodyArgs::builder().build().unwrap();
        let responses = ResponseContracts::new(ContractType::Github).add_body(
            401,
            Some(r#"{"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"}"#),
            None,
        );
        let (_, github) = setup_client!(responses, default_github(), dyn MergeRequest);
        assert!(github.open(mr_args).is_err());
    }

    #[test]
    fn test_open_merge_request_existing_one() {
        let mr_args = MergeRequestBodyArgs::builder()
            .source_branch("feature".to_string())
            .build()
            .unwrap();
        let contracts = ResponseContracts::new(ContractType::Github)
            .add_body(
                200,
                Some(format!(
                    "[{}]",
                    get_contract(ContractType::Github, "merge_request.json")
                )),
                None,
            )
            // Github returns a 422 (already exists), so the code grabs existing URL
            // filtering by namespace and branch. The response is a list of merge
            // requests.
            .add_contract(422, "merge_request_conflict.json", None);
        let (client, github) = setup_client!(contracts, default_github(), dyn MergeRequest);

        github.open(mr_args).unwrap();
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/pulls?head=jordilin:feature",
            *client.url(),
        );
        let actual_method = client.http_method.borrow();
        assert_eq!(http::Method::GET, actual_method[1]);
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_amend_existing_pull_request() {
        let mr_args = MergeRequestBodyArgs::builder()
            .source_branch("feature".to_string())
            .amend(true)
            .build()
            .unwrap();
        let contracts = ResponseContracts::new(ContractType::Github)
            .add_contract(200, "merge_request.json", None)
            .add_body(
                200,
                Some(format!(
                    "[{}]",
                    get_contract(ContractType::Github, "merge_request.json")
                )),
                None,
            )
            .add_contract(422, "merge_request_conflict.json", None);

        let (client, github) = setup_client!(contracts, default_github(), dyn MergeRequest);

        github.open(mr_args).unwrap();
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/pulls/23",
            *client.url(),
        );
        let actual_method = client.http_method.borrow();
        assert_eq!(http::Method::PATCH, actual_method[2]);
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_open_merge_request_cannot_retrieve_url_existing_one_is_error() {
        let mr_args = MergeRequestBodyArgs::builder()
            .source_branch("feature".to_string())
            .build()
            .unwrap();
        let contracts = ResponseContracts::new(ContractType::Github)
            .add_body(200, Some("[]"), None)
            .add_contract(422, "merge_request_conflict.json", None);
        let (_, github) = setup_client!(contracts, default_github(), dyn MergeRequest);
        let result = github.open(mr_args);
        match result {
            Ok(_) => panic!("Expected error"),
            Err(err) => match err.downcast_ref::<error::GRError>() {
                Some(error::GRError::RemoteUnexpectedResponseContract(_)) => (),
                _ => panic!("Expected error::GRError::RemoteUnexpectedResponseContract"),
            },
        }
    }

    #[test]
    fn test_open_merge_request_cannot_get_owner_org_namespace_in_existing_pull_request() {
        let mr_args = MergeRequestBodyArgs::builder()
            .source_branch("feature".to_string())
            .build()
            .unwrap();
        let contracts = ResponseContracts::new(ContractType::Github)
            .add_body(200, Some("[]"), None)
            .add_contract(422, "merge_request_conflict.json", None);
        // missing the repo name on path
        let client_type = ClientType::Github(
            Domain("github.com".to_string()),
            BasePath("jordilin".to_string()),
        );
        let (_, github) = setup_client!(contracts, client_type, dyn MergeRequest);

        let result = github.open(mr_args);
        match result {
            Ok(_) => panic!("Expected error"),
            Err(err) => match err.downcast_ref::<error::GRError>() {
                Some(error::GRError::ApplicationError(_)) => (),
                _ => panic!("Expected error::GRError::ApplicationError"),
            },
        }
    }

    #[test]
    fn test_merge_request_num_pages() {
        let link_header = r#"<https://api.github.com/repos/jordilin/githapi/pulls?state=open&page=2>; rel="next", <https://api.github.com/repos/jordilin/githapi/pulls?state=open&page=2>; rel="last""#;
        let mut headers = Headers::new();
        headers.set("link".to_string(), link_header.to_string());
        let contracts = ResponseContracts::new(ContractType::Github).add_body::<String>(
            200,
            None,
            Some(headers),
        );
        let (client, github) = setup_client!(contracts, default_github(), dyn MergeRequest);
        let args = MergeRequestListBodyArgs::builder()
            .state(MergeRequestState::Opened)
            .list_args(None)
            .assignee(None)
            .build()
            .unwrap();
        assert_eq!(Some(2), github.num_pages(args).unwrap());
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/pulls?state=open&page=1",
            *client.url(),
        );
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_list_merge_requests_from_to_page_set_in_url() {
        let contracts =
            ResponseContracts::new(ContractType::Github).add_body(200, Some("[]"), None);

        let (client, github) = setup_client!(contracts, default_github(), dyn MergeRequest);
        let args = MergeRequestListBodyArgs::builder()
            .state(MergeRequestState::Opened)
            .list_args(Some(
                ListBodyArgs::builder()
                    .page(2)
                    .max_pages(3)
                    .build()
                    .unwrap(),
            ))
            .assignee(None)
            .build()
            .unwrap();
        github.list(args).unwrap();
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/pulls?state=open&page=2",
            *client.url(),
        );
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_get_pull_requests_for_auth_user_is_assignee() {
        let contracts = ResponseContracts::new(ContractType::Github).add_contract(
            200,
            "list_issues_user.json",
            None,
        );
        let (client, github) = setup_client!(contracts, default_github(), dyn MergeRequest);
        let args = MergeRequestListBodyArgs::builder()
            .state(MergeRequestState::Opened)
            .list_args(None)
            .assignee(Some(
                Member::builder()
                    .name("tom".to_string())
                    .username("tsawyer".to_string())
                    .id(123456)
                    .build()
                    .unwrap(),
            ))
            .build()
            .unwrap();
        let merge_requests = github.list(args).unwrap();
        assert_eq!(
            "https://api.github.com/issues?state=open&filter=assigned",
            *client.url()
        );
        assert!(merge_requests.len() == 1);
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_get_pull_requests_for_auth_user_is_author() {
        let contracts = ResponseContracts::new(ContractType::Github).add_contract(
            200,
            "list_issues_user.json",
            None,
        );
        let (client, github) = setup_client!(contracts, default_github(), dyn MergeRequest);
        let args = MergeRequestListBodyArgs::builder()
            .state(MergeRequestState::Opened)
            .list_args(None)
            .author(Some(
                Member::builder()
                    .name("tom".to_string())
                    .username("tsawyer".to_string())
                    .id(12345)
                    .build()
                    .unwrap(),
            ))
            .build()
            .unwrap();
        let merge_requests = github.list(args).unwrap();
        assert_eq!(
            "https://api.github.com/issues?state=open&filter=created",
            *client.url()
        );
        assert!(merge_requests.len() == 1);
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_create_merge_request_comment() {
        let contracts =
            ResponseContracts::new(ContractType::Github).add_body::<String>(201, None, None);
        let (client, github) = setup_client!(contracts, default_github(), dyn CommentMergeRequest);
        let args = CommentMergeRequestBodyArgs::builder()
            .id(23)
            .comment("Looks good to me".to_string())
            .build()
            .unwrap();
        github.create(args).unwrap();
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/issues/23/comments",
            *client.url(),
        );
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_create_merge_request_comment_error_status_code() {
        let contracts =
            ResponseContracts::new(ContractType::Github).add_body::<String>(500, None, None);
        let (_, github) = setup_client!(contracts, default_github(), dyn CommentMergeRequest);
        let args = CommentMergeRequestBodyArgs::builder()
            .id(23)
            .comment("Looks good to me".to_string())
            .build()
            .unwrap();
        assert!(github.create(args).is_err());
    }

    #[test]
    fn test_close_pull_request_ok() {
        let contracts = ResponseContracts::new(ContractType::Github).add_contract(
            200,
            "merge_request.json",
            None,
        );
        let (client, github) = setup_client!(contracts, default_github(), dyn MergeRequest);
        github.close(23).unwrap();
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/pulls/23",
            *client.url(),
        );
        let actual_method = client.http_method.borrow();
        assert_eq!(http::Method::PATCH, actual_method[0]);
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_get_pull_request_details() {
        let contracts = ResponseContracts::new(ContractType::Github).add_contract(
            200,
            "merge_request.json",
            None,
        );
        let (client, github) = setup_client!(contracts, default_github(), dyn MergeRequest);
        github.get(23).unwrap();
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/pulls/23",
            *client.url(),
        );
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_github_merge_pull_request() {
        let contracts = ResponseContracts::new(ContractType::Github).add_contract(
            200,
            "merge_request.json",
            None,
        );
        let (client, github) = setup_client!(contracts, default_github(), dyn MergeRequest);
        github.merge(23).unwrap();
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/pulls/23/merge",
            *client.url(),
        );
        let actual_method = client.http_method.borrow();
        assert_eq!(http::Method::PUT, actual_method[0]);
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_list_pull_request_comments() {
        let contracts = ResponseContracts::new(ContractType::Github).add_body(
            200,
            Some(format!(
                "[{}]",
                get_contract(ContractType::Github, "comment.json")
            )),
            None,
        );
        let (client, github) = setup_client!(contracts, default_github(), dyn CommentMergeRequest);
        let args = CommentMergeRequestListBodyArgs::builder()
            .id(23)
            .list_args(None)
            .build()
            .unwrap();
        github.list(args).unwrap();
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/issues/23/comments",
            *client.url(),
        );
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }

    #[test]
    fn test_pull_request_comment_num_pages() {
        let link_header = r#"<https://api.github.com/repos/jordilin/githapi/issues/23/comments?page=2>; rel="next", <https://api.github.com/repos/jordilin/githapi/issues/23/comments?page=2>; rel="last""#;
        let mut headers = Headers::new();
        headers.set("link".to_string(), link_header.to_string());
        let contracts = ResponseContracts::new(ContractType::Github).add_body::<String>(
            200,
            None,
            Some(headers),
        );
        let (client, github) = setup_client!(contracts, default_github(), dyn CommentMergeRequest);
        let args = CommentMergeRequestListBodyArgs::builder()
            .id(23)
            .list_args(None)
            .build()
            .unwrap();
        assert_eq!(Some(2), github.num_pages(args).unwrap());
        assert_eq!(
            "https://api.github.com/repos/jordilin/githapi/issues/23/comments?page=1",
            *client.url(),
        );
        assert_eq!(
            Some(ApiOperation::MergeRequest),
            *client.api_operation.borrow()
        );
    }
}