File size: 71,285 Bytes
7b715bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
/*
Copyright 2011 Google Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using Google.Apis.Discovery;
using Google.Apis.Http;
using Google.Apis.Requests;
using Google.Apis.Services;
using Google.Apis.Tests.Mocks;
using Google.Apis.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace Google.Apis.Tests.Apis.Requests
{
    /// <summary>Tests for the <seealso cref="Google.Apis.Requests.ClientServiceRequest"/>.</summary>
    public class ClientServiceRequestTest
    {
        /// <summary>Helper method to get a string from the stream.</summary>
        private static string ExtractStringFromStream(Stream stream)
        {
            var buffer = new byte[1000];
            var len = stream.Read(buffer, 0, 1000);
            return Encoding.UTF8.GetString(buffer, 0, len);
        }

        /// <summary>A mock response class.</summary>
        class MockResponse : IDirectResponseSchema
        {
            [Newtonsoft.Json.JsonPropertyAttribute("etag")]
            public string ETag { get; set; }

            [Newtonsoft.Json.JsonPropertyAttribute("name")]
            public string Name { get; set; }

            [Newtonsoft.Json.JsonPropertyAttribute("id")]
            public int Id { get; set; }

            public override bool Equals(object obj)
            {
                var other = obj as MockResponse;
                return (other != null && other.ETag == ETag && other.Name == Name && other.Id == Id);
            }

            public override int GetHashCode()
            {
                return (ETag ?? string.Empty).GetHashCode() ^ (Name ?? string.Empty).GetHashCode() + Id;
            }
        }

        /// <summary>A mock request class.</summary>
        class MockRequest : IDirectResponseSchema
        {
            [Newtonsoft.Json.JsonPropertyAttribute("etag")]
            public string ETag { get; set; }

            [Newtonsoft.Json.JsonPropertyAttribute("long_name")]
            public string Name { get; set; }

            public override bool Equals(object obj)
            {
                var other = obj as MockRequest;
                return (other != null && other.ETag == ETag && other.Name == Name);
            }

            public override int GetHashCode()
            {
                return (ETag ?? string.Empty).GetHashCode() ^ (Name ?? string.Empty).GetHashCode();
            }
        }

        /// <summary>A mock service request which returns <see cref="MockResponse"/>.</summary>
        class TestClientServiceRequest : ClientServiceRequest<MockResponse>
        {
            public string OverrideRestPath { get; set; }
            /// <summary>Gets or sets a request number. It's used on concurrent tests.</summary>
            public int CallNum { get; set; }
            private string httpMethod;
            private object body;

            public TestClientServiceRequest(IClientService service, string httpMethod, object body)
                : base(service)
            {
                this.httpMethod = httpMethod;
                this.body = body;
                InitParameters();
                RequestParameters.Add("id", new Parameter
                {
                    Name = "id",
                    ParameterType = "path"
                });
            }

            // Normally requests override the ApiVersion with a constant (if at all) but it's
            // convenient for us to be able to do it on mutable basis for tests.
            public override string ApiVersion => ApiVersionImpl;
            public string ApiVersionImpl { get; set; }

            public override string MethodName => httpMethod;

            public override string RestPath => OverrideRestPath ?? "restPath" + CallNum;

            public override string HttpMethod => httpMethod;

            protected override object GetBody() => body;

            [RequestParameter("id", RequestParameterType.Path)]
            public string Id { get; set; }

            public string GenerateRequestUriPublic() => GenerateRequestUri();
        }

        /// <summary>A mock message handler which returns an error.</summary>
        class ErrorMessageHandler : CountableMessageHandler
        {
            public const string ExpectedError = 
                @"Message[Login Required] Location[Authorization - header] Reason[required] Domain[global]";
            public const string ErrorContent =
                @"{
                    ""error"": {
                        ""errors"": [
                            {
                                ""domain"": ""global"",
                                ""reason"": ""required"",
                                ""message"": ""Login Required"",
                                ""locationType"": ""header"",
                                ""location"": ""Authorization""
                            }
                        ],
                        ""code"": 401,
                        ""message"": ""Login Required""
                    }
                }";

            public const string ExpectedExceptionMessage = "The service TestService has thrown an exception. HttpStatusCode is Unauthorized. Login Required";

            protected override Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
                CancellationToken cancellationToken)
            {

                var response = new HttpResponseMessage
                    {
                        Content = new StringContent(ErrorContent),
                        StatusCode = HttpStatusCode.Unauthorized
                    };

                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                tcs.SetResult(response);
                return tcs.Task;
            }
        }

        /// <summary>Tests message handler which tests the content on the request and the response.</summary>
        class TestBodyMessageHandler : CountableMessageHandler
        {
            /// <summary>Gets or sets indication is GZip is eanbled.</summary>
            public bool GZipEnabled { get; set; }

            /// <summary>Gets or sets the expected request object.</summary>
            public MockRequest ExpectedRequestObject { get; set; }

            /// <summary>Gets or sets the returned response object </summary>
            public MockResponse ResponseObject { get; set; }

            /// <summary>Gets or sets the Serializer which is used to serialize and deserialize messages.</summary>
            public ISerializer Serializer { get; set; }

            public string ResponseETag = "\"some-etag-here\"";

            protected override async Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
                CancellationToken cancellationToken)
            {
                var mediaType = "application/json";
                string strObject = null;

                // If gzip enabled the request content is a gzip stream, otherwise it's a string content.
                if (GZipEnabled)
                {
                    Assert.IsAssignableFrom<StreamContent>(request.Content);
                    var encoding = request.Content.Headers.ContentEncoding;
                    Assert.True(encoding.Count == 1 && encoding.First().Equals("gzip"),
                        "Content-Encoding should be 'gzip'");
                    var stream = await request.Content.ReadAsStreamAsync().ConfigureAwait(false);
                    using (GZipStream gzipStream = new GZipStream(stream, CompressionMode.Decompress))
                    {
                        strObject = ExtractStringFromStream(gzipStream);
                    }
                }
                else
                {
                    Assert.IsAssignableFrom<StringContent>(request.Content);
                    strObject = await request.Content.ReadAsStringAsync().ConfigureAwait(false);
                }

                Assert.Equal(new MediaTypeHeaderValue(mediaType)
                {
                    CharSet = Encoding.UTF8.WebName
                }, request.Content.Headers.ContentType);

                // Deserialize the requested object and check it's equal to the expected object.
                var obj = Serializer.Deserialize<MockRequest>(strObject);
                Assert.Equal(ExpectedRequestObject, obj);

                // Return the response (with ETag).
                var response = new HttpResponseMessage();
                var serializedObject = Serializer.Serialize(ResponseObject);
                response.Content = new StringContent(serializedObject, Encoding.UTF8, mediaType);
                response.Headers.ETag = new EntityTagHeaderValue(ResponseETag);
                return response;
            }
        }

        /// <summary>
        /// A mock exception which is thrown from a mock message handler in case it is configured to throw exceptions. 
        /// </summary>
        class InvalidOperationMockException : Exception
        {
            public InvalidOperationMockException(string str)
                : base(str)
            {
            }
        }

        /// <summary>A message handler which returns a HTTP response message or throw an exception.</summary>
        class MockMessageHandler : CountableMessageHandler
        {
            private bool ThrowException { get; set; }
            public MockMessageHandler(bool throwException = false)
            {
                ThrowException = throwException;
            }

            protected override Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
                CancellationToken cancellationToken)
            {
                if (ThrowException)
                {
                    throw new InvalidOperationMockException("INVALID");
                }

                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                tcs.SetResult(new HttpResponseMessage());
                return tcs.Task;
            }
        }

        /// <summary>A message handler which is used to cancel a HTTP request in the middle.</summary>
        class CancelRedirectMessageHandler : CountableMessageHandler
        {
            /// <summary>The cancellation token we are going to use to cancel a request.</summary>
            public CancellationTokenSource CancellationTokenSource { get; set; }

            /// <summary>The request index we are going to cancel.</summary>
            public int CancelRequestNum { get; set; }

            protected override Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
                CancellationToken cancellationToken)
            {
                if (Calls == CancelRequestNum)
                {
                    CancellationTokenSource.Cancel();
                }
                var response = new HttpResponseMessage()
                    {
                        StatusCode = HttpStatusCode.Redirect,
                        RequestMessage = request
                    };
                response.Headers.Location = new Uri("http://www.test.com");

                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                tcs.SetResult(response);
                return tcs.Task;
            }
        }

        /// <summary>
        /// A message handler which checks concurrent calls (each odd request will succeeded, and even request will 
        /// fail on the first try and will succeeded in the second try.
        /// </summary>
        class ConcurrentCallsHandler : CountableMessageHandler
        {
            /// <summary>Gets or sets the Serializer which is used to serialize and deserialize messages.</summary>
            public ISerializer Serializer { get; set; }

            protected override Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
                CancellationToken cancellationToken)
            {
                var response = new HttpResponseMessage();
                var uri = request.RequestUri.AbsoluteUri;
                int lastDigit = 0;
                if (int.TryParse(uri[uri.Length - 1].ToString(), out lastDigit) && lastDigit % 2 == 0)
                {
                    response.StatusCode = System.Net.HttpStatusCode.ServiceUnavailable;
                    request.RequestUri = new Uri(uri + (lastDigit + 1));
                }
                else
                {
                    var mockObject = new MockResponse { Name = "Name-" + lastDigit };
                    var serializedObject = Serializer.Serialize(mockObject);
                    response.Content = new StringContent(serializedObject, Encoding.UTF8, "application/json");
                }

                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                tcs.SetResult(response);
                return tcs.Task;
            }

            /// <summary>Unsuccessful response handler which "handles" service unavailable responses.</summary>
            internal class ServiceUnavailableUnsuccessfulResponseHandler : IHttpUnsuccessfulResponseHandler
            {
                public Task<bool> HandleResponseAsync(HandleUnsuccessfulResponseArgs args)
                {
                    TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
                    tcs.SetResult(args.Response.StatusCode.Equals(HttpStatusCode.ServiceUnavailable));
                    return tcs.Task;
                }
            }

            /// <summary>
            /// Adds service unavailable unsuccessful response handler to the configurable message handler.
            /// </summary>
            internal class Initializer : IConfigurableHttpClientInitializer
            {
                public void Initialize(ConfigurableHttpClient httpClient)
                {
                    httpClient.MessageHandler.AddUnsuccessfulResponseHandler(
                        new ServiceUnavailableUnsuccessfulResponseHandler());
                }
            }
        }

        #region Execute (and ExecuteAsync)

        /// <summary>Tests that canceling a outgoing request to the server works as expected.</summary>
        [Fact]
        public async Task ExecuteAsync_Cancel()
        {
            await SubtestExecuteAsync_Cancel(1);
            await SubtestExecuteAsync_Cancel(5);
            await SubtestExecuteAsync_Cancel(10);
            await SubtestExecuteAsync_Cancel(11);
        }

        /// <summary>
        /// Test helper to test canceling token in a middle of a request to the server
        /// </summary>
        /// <param name="cancelRequestNum">
        /// The index of the "server"'s request which a cancel token will be mimic.
        /// </param>
        private async Task SubtestExecuteAsync_Cancel(int cancelRequestNum)
        {
            var handler = new CancelRedirectMessageHandler();
            handler.CancellationTokenSource = new CancellationTokenSource();
            handler.CancelRequestNum = cancelRequestNum;

            var initializer = new BaseClientService.Initializer()
                {
                    HttpClientFactory = new MockHttpClientFactory(handler)
                };

            TestClientServiceRequest request;
            using (var service = new MockClientService(initializer))
            {
                request = new TestClientServiceRequest(service, "POST", new MockRequest());
                var exception = await Assert.ThrowsAnyAsync<Exception>(() => request.ExecuteAsync(handler.CancellationTokenSource.Token));
                if (exception is OperationCanceledException)
                {
                    // We expect a task canceled exception in case the canceled request is less or equal total
                    // number of retries.
                    Assert.False(cancelRequestNum > service.HttpClient.MessageHandler.NumRedirects + 1);
                }
                else
                {
                    // Canceled exception wasn't thrown, in that case the cancel request number is bigger than
                    // the actual number of tries.
                    Assert.True(cancelRequestNum > service.HttpClient.MessageHandler.NumTries + 1);
                }

                var expectedCalls = Math.Min(service.HttpClient.MessageHandler.NumRedirects + 1, cancelRequestNum);
                Assert.Equal(expectedCalls, handler.Calls);
            }
        }

        /// <summary>Tests the execute method in case the service was disposed.</summary>
        [Fact]
        public void Execute_DisposeService()
        {
            var handler = new MockMessageHandler();
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            TestClientServiceRequest request;
            using (var service = new MockClientService(initializer))
            {
                request = new TestClientServiceRequest(service, "POST", new MockRequest());
            }

            // the service was disposed before the request was made (and the message handler as well). As a result an 
            // exception should be thrown before we try to send the request
            Assert.Throws<ObjectDisposedException>(() => request.Execute());
        }

        /// <summary>A subtest for testing GZip and sync-async calls.</summary>
        /// <param name="gzip">Defines if GZip is enabled</param>
        /// <param name="async">Defines which method is going to be called (Execute or ExecuteAsync)</param>
        private void SubtestExecute_GZip(bool gzip, bool async)
        {
            var handler = new TestBodyMessageHandler()
            {
                GZipEnabled = gzip,
                ResponseObject = new MockResponse { Id = 100, Name = "sample name" },
                ExpectedRequestObject = new MockRequest { Name = "long long name" }
            };

            var initializer = new BaseClientService.Initializer()
            {
                GZipEnabled = gzip,
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer))
            {
                handler.Serializer = service.Serializer;

                var request = new TestClientServiceRequest(service, "POST", handler.ExpectedRequestObject);
                MockResponse response = null;
                if (async)
                {
                    var task = request.ExecuteAsync();
                    response = task.Result;
                }
                else
                {
                    response = request.Execute();
                }

                // Note: Even if GZipEnabled is true, we don't need to extract the real string from the GZip stream,
                // because in a real request we use HttpClientHandler which its AutomaticDecompression is set to 
                // System.Net.DecompressionMethods.GZip.

                Assert.Equal(1, handler.Calls);
                // The returned response should contain ETag, check that the service adds the right ETag property on 
                // the response.
                handler.ResponseObject.ETag = handler.ResponseETag;
                Assert.Equal(handler.ResponseObject, response);
            }
        }

        /// <summary>Tests execute when GZip is enabled.</summary>
        [Fact]
        public void Execute_GZipEnabled()
        {
            SubtestExecute_GZip(true, false);
        }

        /// <summary>Tests execute when GZip is disabled.</summary>
        [Fact]
        public void Execute_GZipDisabled()
        {
            SubtestExecute_GZip(false, false);
        }

        /// <summary>Tests async execute when GZip is enabled.</summary>
        [Fact]
        public void ExecuteAsync_GZipEnabled()
        {
            SubtestExecute_GZip(true, true);
        }

        /// <summary>Tests async execute when GZip is disabled.</summary>
        [Fact]
        public void ExecuteAsync_GZipDisabled()
        {
            SubtestExecute_GZip(false, true);
        }

        /// <summary>Tests execute with unicode characters.</summary>
        [Fact]
        public void Execute_UnicodeCharacters()
        {
            var handler = new TestBodyMessageHandler()
            {
                GZipEnabled = false,
                ResponseObject = new MockResponse { Id = 100, Name = @"مرحبا العالم" },
                ExpectedRequestObject = new MockRequest { Name = @"مرحبا العالم! 您好,世界!" }
            };

            var initializer = new BaseClientService.Initializer()
            {
                GZipEnabled = false,
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer))
            {
                handler.Serializer = service.Serializer;

                var request = new TestClientServiceRequest(service, "GET", handler.ExpectedRequestObject);
                var response = request.Execute();
                Assert.Equal(1, handler.Calls);
                // The returned response should contain ETag, check that the service add the right ETag property on 
                // the response.
                handler.ResponseObject.ETag = handler.ResponseETag;
                Assert.Equal(handler.ResponseObject, response);
            }
        }

        /// <summary>
        /// A subtest for testing Execute when an exception is thrown while sending the request. This is tested with
        /// and without back-off. If back-off handler is attached to the service's message handler, there should be 3
        /// tries (the default value of <seealso cref="ConfigurableMessageHandler.NumTries"/>) before the operation 
        /// fails.
        /// </summary>
        /// <param name="backOff">Indicates if back-off handler is attached to the service.</param>
        private void SubtestExecute_ThrowException(bool backOff)
        {
            var handler = new MockMessageHandler(true);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            // Set the default exponential back-off policy by the input.
            initializer.DefaultExponentialBackOffPolicy = backOff ?
                ExponentialBackOffPolicy.Exception : ExponentialBackOffPolicy.None;

            using (var service = new MockClientService(initializer))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                Assert.Throws<InvalidOperationMockException>(() => request.Execute());

                int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1;
                Assert.Equal(calls, handler.Calls);
            }
        }

        /// <summary>
        /// Tests execute when an exception is thrown during a request and exponential back-off is enabled.
        /// </summary>
        [Fact]
        public void Execute_ThrowException_WithBackOff()
        {
            SubtestExecute_ThrowException(true);
        }

        /// <summary>
        /// Tests execute when an exception is thrown during a request and exponential back-off is disabled.
        /// </summary>
        [Fact]
        public void Execute_ThrowException_WithoutBackOff()
        {
            SubtestExecute_ThrowException(false);
        }

        /// <summary>
        /// A subtest for testing ExecuteAsync  when an exception is thrown while sending the request. This is tested 
        /// with and without back-off. If back-off handler is attached to the service's message handler, there should 
        /// be 3 tries (the default value of <seealso cref="ConfigurableMessageHandler.NumTries"/>) before the 
        /// operation fails.
        /// </summary>
        /// <param name="backOff">Indicates if back-off handler is attached to the service.</param>
        [Theory, CombinatorialData]            
        public async Task SubtestExecuteAsync_ThrowException(bool backOff)
        {
            var handler = new MockMessageHandler(true);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            // Configure the back-off behavior by the input.
            initializer.DefaultExponentialBackOffPolicy = backOff ?
                ExponentialBackOffPolicy.Exception : ExponentialBackOffPolicy.None;

            using (var service = new MockClientService(initializer))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                await Assert.ThrowsAnyAsync<InvalidOperationMockException>(() => request.ExecuteAsync());
                int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1;
                Assert.Equal(calls, handler.Calls);
            }
        }

        /// <summary>Tests execute when server returned an error.</summary>
        [Fact]
        public void Execute_Error()
        {
            var handler = new ErrorMessageHandler();
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                var exception = Assert.Throws<GoogleApiException>(() => request.Execute());

                Assert.Equal(1, handler.Calls);
                Assert.Equal(ErrorMessageHandler.ExpectedExceptionMessage, exception.Message);
                Assert.Contains(ErrorMessageHandler.ExpectedError, exception.ToString());
            }
        }

        /// <summary>Tests execute when server returned an error.</summary>
        [Fact]
        public async Task ExecuteAsync_Error()
        {
            var handler = new ErrorMessageHandler();
            var initializer = new BaseClientService.Initializer
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                var exception = await Assert.ThrowsAsync<GoogleApiException>(() => request.ExecuteAsync());
                AutoResetEvent resetEvent = new AutoResetEvent(false);
                
                Assert.Equal(1, handler.Calls);
                Assert.Equal(ErrorMessageHandler.ExpectedExceptionMessage, exception.Message);
                Assert.Contains(ErrorMessageHandler.ExpectedError, exception.ToString());
            }
        }

        /// <summary>Tests async execution of multiple request simultaneously.</summary>
        [Fact]
        public async Task ExecuteAsync_Simultaneously()
        {
            var tasks = new List<Task<MockResponse>>();
            var handler = new ConcurrentCallsHandler();
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler),
                HttpClientInitializer = new ConcurrentCallsHandler.Initializer()
            };

            using (var service = new MockClientService(initializer))
            {
                int calls = 100;
                handler.Serializer = service.Serializer;

                CountdownEvent ce = new CountdownEvent(calls);
                foreach (var i in Enumerable.Range(1, calls))
                {
                    var request = new TestClientServiceRequest(service, "GET", null) { CallNum = i };
                    var task = request.ExecuteAsync();
                    _ = task.ContinueWith(c => ce.Signal());
                    tasks.Add(task);
                }
                ce.Wait();

                for (var i = 1; i <= tasks.Count; ++i)
                {
                    var response = await tasks[i - 1];

                    // check that we got the right response. Name should be equal to the index number modulo 10 (or 
                    // index number plus one module 10, if it's an even request - because even request should fail in 
                    // the first request, but should succeed in the next try). That's the logic of our 
                    // ConcurrentCallHandler, see it core SendAsyncCore method to understand better the logic
                    var nameIndex = ((i % 2 == 0) ? i + 1 : i) % 10;
                    Assert.Equal("Name-" + nameIndex, response.Name);
                }

                // half of the request should succeed in the second call, so total calls should be calls + calls/2
                Assert.Equal(calls + calls / 2, handler.Calls);
            }
        }

        #endregion

        #region ExecuteStream (and ExecuteAsStreamAsync)

        /// <summary>A subtest for testing execute as stream (async and sync).</summary>
        private void SubtestExecuteAsStream(bool async)
        {
            var handler = new TestBodyMessageHandler
            {
                GZipEnabled = false,
                ResponseObject = new MockResponse { Id = 100, Name = "sample name" },
                ExpectedRequestObject = new MockRequest { Name = "long long name" }
            };

            var initializer = new BaseClientService.Initializer
            {
                GZipEnabled = false,
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer))
            {
                handler.Serializer = service.Serializer;

                var request = new TestClientServiceRequest(service, "GET", handler.ExpectedRequestObject);

                MockResponse response = null;
                Stream stream = null;
                if (async)
                {
                    request.ExecuteAsStreamAsync().ContinueWith(t =>
                    {
                        stream = t.Result;
                    }, TaskContinuationOptions.OnlyOnRanToCompletion).Wait();
                }
                else
                {
                    stream = request.ExecuteAsStream();
                }

                // Read the object.
                var str = ExtractStringFromStream(stream);
                response = service.Serializer.Deserialize<MockResponse>(str);

                Assert.Equal(1, handler.Calls);
                Assert.Equal(handler.ResponseObject, response);
            }
        }

        /// <summary>Tests execute stream.</summary>
        [Fact]
        public void ExecuteAsStream()
        {
            SubtestExecuteAsStream(false);
        }

        /// <summary>Tests execute stream (async).</summary>
        [Fact]
        public void ExecuteAsStreamAsync()
        {
            SubtestExecuteAsStream(true);
        }

        #endregion

        #region Parameters

        #region Query Parameters

        /// <summary>Client request which contains query parameters.</summary>
        class ClientServiceRequestWithQueryParameters : TestClientServiceRequest
        {
            [RequestParameterAttribute("required", Google.Apis.Util.RequestParameterType.Query)]
            public string Required { get; set; }

            [RequestParameterAttribute("optionalWithValue", Google.Apis.Util.RequestParameterType.Query)]
            public string OptionalWithValue { get; set; }

            [RequestParameterAttribute("optionalWithValue2", Google.Apis.Util.RequestParameterType.Query)]
            public string OptionalWithValue2 { get; set; }

            [RequestParameterAttribute("optionalNull", Google.Apis.Util.RequestParameterType.Query)]
            public string OptionalNull { get; set; }

            [RequestParameterAttribute("optionalEmpty", Google.Apis.Util.RequestParameterType.Query)]
            public string OptionalEmpty { get; set; }

            [RequestParameterAttribute("optionalNotPressent", Google.Apis.Util.RequestParameterType.Query)]
            public string OptionalNotPressent { get; set; }

            public ClientServiceRequestWithQueryParameters(IClientService service, string method, object body)
                : base(service, method, body)
            {
                RequestParameters.Add("required", new Parameter
                {
                    Name = "required",
                    IsRequired = true,
                    ParameterType = "query"
                });
                RequestParameters.Add("optionalWithValue", new Parameter
                {
                    Name = "optionalWithValue",
                    IsRequired = false,
                    ParameterType = "query",
                    DefaultValue = "DoesNotDisplay"
                });
                RequestParameters.Add("optionalWithValue2", new Parameter
                {
                    Name = "optionalWithValue",
                    IsRequired = false,
                    ParameterType = "query",
                    DefaultValue = "DoesNotDisplay"
                });
                RequestParameters.Add("optionalWithNull", new Parameter
                {
                    Name = "optionalWithNull",
                    IsRequired = false,
                    ParameterType = "query",
                    DefaultValue = "c"
                });
                RequestParameters.Add("optionalEmpty", new Parameter
                {
                    Name = "optionalEmpty",
                    IsRequired = false,
                    ParameterType = "query",
                    DefaultValue = "d"
                });
                RequestParameters.Add("optionalNotPressent", new Parameter
                {
                    Name = "optionalNotPressent",
                    IsRequired = false,
                    ParameterType = "query",
                    DefaultValue = "DoesNotDisplay"
                });
            }
        }

        /// <summary>Tests build request with query parameters.</summary>
        [Fact]
        public void CreateRequest_QueryParameters()
        {
            using (var service = new MockClientService("https://build_request_params"))
            {
                var request = new ClientServiceRequestWithQueryParameters(service, "GET", null);
                request.Required = "a";
                request.OptionalWithValue = "b";
                request.OptionalWithValue2 = "DoesNotDisplay";
                request.OptionalNull = null;
                request.OptionalEmpty = string.Empty;
                var httpRequest = request.CreateRequest();
                Assert.Equal(new Uri("https://build_request_params/restPath0?required=a&optionalWithValue=b&optionalEmpty"), httpRequest.RequestUri);
            }
        }

        /// <summary>Tests build request with missing required query parameter.</summary>
        [Fact]
        public void CreateRequest_QueryParameterIsMissing()
        {
            using (var service = new MockClientService("https://build_request_params"))
            {
                var request = new ClientServiceRequestWithQueryParameters(service, "GET", null);
                var exception = Assert.Throws<GoogleApiException>(() => request.CreateRequest());
                Assert.Contains("Parameter \"required\" is missing", exception.Message);
            }
        }

        /// <summary>Client request which contains date query parameter.</summary>
        class ClientServiceRequestWithDateQueryParameter : TestClientServiceRequest
        {
            [RequestParameterAttribute("min_time", Google.Apis.Util.RequestParameterType.Query)]
            public DateTime? Min { get; set; }

            public ClientServiceRequestWithDateQueryParameter(IClientService service, string method, object body)
                : base(service, method, body)
            {
                RequestParameters.Add("min_time", new Parameter
                {
                    Name = "min_time",
                    ParameterType = "query"
                });
            }
        }

        /// <summary>Tests build request with date query parameter.</summary>
        [Fact]
        public void CreateRequest_QueryDateParameter()
        {
            using (var service = new MockClientService("https://build_request_params"))
            {
                // Request without the date parameter.
                var request = new ClientServiceRequestWithDateQueryParameter(service, "GET", null);
                var httpRequest = request.CreateRequest();
                Assert.Equal(new Uri("https://build_request_params/restPath0"), httpRequest.RequestUri);

                // Request with the date parameter.
                DateTime date = new DateTime(2002, 2, 25, 12, 57, 32, 777, DateTimeKind.Utc);
                request.Min = date;
                httpRequest = request.CreateRequest();

                // On Mono, the ":" character gets UrlEncoded.
                Assert.Contains(httpRequest.RequestUri.AbsoluteUri, new [] {
                    "https://build_request_params/restPath0?min_time=2002-02-25T12:57:32.777Z",
                    "https://build_request_params/restPath0?min_time=2002-02-25T12%3A57%3A32.777Z",
                });
            }
        }

        class ClientServiceRequestWithBoolParameter : TestClientServiceRequest
        {
            [RequestParameter("bool", RequestParameterType.Query)]
            public bool? Bool { get; set; }

            public ClientServiceRequestWithBoolParameter(IClientService service, string method, object body)
                : base(service, method, body)
            {
                RequestParameters.Add("bool", new Parameter
                {
                    Name = "bool",
                    ParameterType = "query"
                });
            }
        }

        [Fact]
        public void CreateRequest_QueryBoolParameter()
        {
            using (var service = new MockClientService("https://build_request_params"))
            {
                // Request without the bool parameter.
                var request = new ClientServiceRequestWithBoolParameter(service, "GET", null);
                var httpRequest = request.CreateRequest();
                Assert.Equal(new Uri("https://build_request_params/restPath0"), httpRequest.RequestUri);

                // Request with the bool parameter true
                request.Bool = true;
                Assert.Equal(new Uri("https://build_request_params/restPath0?bool=true"), request.CreateRequest().RequestUri);

                // Request with the bool parameter false
                request.Bool = false;
                Assert.Equal(new Uri("https://build_request_params/restPath0?bool=false"), request.CreateRequest().RequestUri);

            }
        }

        #endregion

        #region Path Parameters

        /// <summary>Client request which contains path parameters.</summary>
        class ClientServiceRequestWithPathParameters : TestClientServiceRequest
        {
            [RequestParameter("path1", RequestParameterType.Path)]
            public int TestParameterA { get; set; }

            [RequestParameter("path2", RequestParameterType.Path)]
            public int TestParameterB { get; set; }

            public int TestParameterC { get; set; }

            public ClientServiceRequestWithPathParameters(IClientService service, string method, object body)
                : base(service, method, body)
            {
                RequestParameters.Add("path1", new Parameter
                {
                    Name = "path1",
                    ParameterType = "path"
                });
                RequestParameters.Add("path2", new Parameter
                {
                    Name = "path2",
                    ParameterType = "path",
                });
            }

            public override string RestPath
            {
                get { return "restPath/{path1}/something/{path2}"; }
            }
        }

        /// <summary>Tests build request with path parameters.</summary>
        [Fact]
        public void CreateRequest_PathParameters()
        {
            using (var service = new MockClientService("https://build_request_params"))
            {
                var request = new ClientServiceRequestWithPathParameters(service, "GET", null);
                request.TestParameterA = 42;
                request.TestParameterB = 43;
                request.TestParameterC = 44; // ignore it, because it doesn't contain RequestParameter attribute
                var httpRequest = request.CreateRequest();
                Assert.Equal(new Uri("https://build_request_params/restPath/42/something/43"), httpRequest.RequestUri);
            }
        }

        #endregion

        #region Developer Key

        private const string SimpleDeveloperKey = "ABC123";
        private const string ComplexDeveloperKey = "?&^%  ABC123";

        /// <summary>Tests build request with simple developer key.</summary>
        [Fact]
        public void CreateRequest_DeveloperKey()
        {
            var initializer = new BaseClientService.Initializer
            {
                ApiKey = SimpleDeveloperKey
            };

            using (var service = new MockClientService(initializer, "https://build_request_params"))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                var httpRequest = request.CreateRequest();
                Assert.Equal(new Uri("https://build_request_params/restPath0?key=" + SimpleDeveloperKey), httpRequest.RequestUri);
            }
        }

        /// <summary>Tests build request with complex developer key.</summary>
        [Fact]
        public void CreateRequest_DeveloperKey_RequiresEscape()
        {
            var initializer = new BaseClientService.Initializer
            {
                ApiKey = ComplexDeveloperKey
            };

            using (var service = new MockClientService(initializer, "https://build_request_params"))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                var httpRequest = request.CreateRequest();
                Assert.Equal(new Uri("https://build_request_params/restPath0?key=%3F%26%5E%25%20%20ABC123"), httpRequest.RequestUri);
            }
        }

        #endregion

        #endregion

        #region Supported Methods

        /// <summary>Tests if invalid method throws an exception.</summary>
        [Fact]
        public void CreateRequest_UnsupportedMethods()
        {
            using (var service = new MockClientService("https://build_request_params"))
            {
                var request = new TestClientServiceRequest(service, "Unsupported", null);
                Assert.Throws<ArgumentOutOfRangeException>(() => request.CreateRequest());
            }
        }

        /// <summary>Tests that valid method doesn't throw an exception.</summary>
        [Fact]
        public void CreateRequest_SupportedMethods()
        {
            SubtestCreateRequest_SupportedMethod(HttpConsts.Get);
            SubtestCreateRequest_SupportedMethod(HttpConsts.Put);
            SubtestCreateRequest_SupportedMethod(HttpConsts.Post);
            SubtestCreateRequest_SupportedMethod(HttpConsts.Patch);
            SubtestCreateRequest_SupportedMethod(HttpConsts.Delete);
        }

        private void SubtestCreateRequest_SupportedMethod(string method)
        {
            using (var service = new MockClientService("https://build_request_params"))
            {
                var request = new TestClientServiceRequest(service, method, null);
                var httpRequest = request.CreateRequest();
            }
        }

        #endregion

        #region ETag

        /// <summary>Tests the create request method with different ETags.</summary>
        [Fact]
        public void CreateRequest_ETag()
        {
            var body = new MockRequest { Name = "long long name" };
            using (var service = new MockClientService())
            {
                // No ETag (ETag = null).
                var request = new TestClientServiceRequest(service, HttpConsts.Get, body);
                var httpRequest = request.CreateRequest();
                Assert.Empty(httpRequest.Headers.IfMatch);
                Assert.Empty(httpRequest.Headers.IfNoneMatch);

                // ETag has a value, but ETag action is ignored.
                body.ETag = "\"ETAG_HERE\"";
                request = new TestClientServiceRequest(service, HttpConsts.Get, body);
                request.ETagAction = ETagAction.Ignore;
                httpRequest = request.CreateRequest();
                Assert.Empty(httpRequest.Headers.IfMatch);
                Assert.Empty(httpRequest.Headers.IfNoneMatch);

                // ETag has a value, so use default action (Get -> If-None-Match).
                request = new TestClientServiceRequest(service, HttpConsts.Get, body);
                httpRequest = request.CreateRequest();
                Assert.Empty(httpRequest.Headers.IfMatch);
                Assert.Single(httpRequest.Headers.IfNoneMatch);
                Assert.Equal(new EntityTagHeaderValue(body.ETag), httpRequest.Headers.IfNoneMatch.First());

                // ETag has a value, so use default action (Post -> If-Match).
                request = new TestClientServiceRequest(service, HttpConsts.Post, body);
                httpRequest = request.CreateRequest();
                Assert.Empty(httpRequest.Headers.IfNoneMatch);
                Assert.Single(httpRequest.Headers.IfMatch);
                Assert.Equal(new EntityTagHeaderValue(body.ETag), httpRequest.Headers.IfMatch.First());

                // ETag has a value, default is override, use the specified ETag action.
                request = new TestClientServiceRequest(service, HttpConsts.Post, body);
                request.ETagAction = ETagAction.IfNoneMatch;
                httpRequest = request.CreateRequest();
                Assert.Empty(httpRequest.Headers.IfMatch);
                Assert.Single(httpRequest.Headers.IfNoneMatch);
                Assert.Equal(new EntityTagHeaderValue(body.ETag), httpRequest.Headers.IfNoneMatch.First());

                // ETag has a value, default is override, use the specified ETag action.
                request = new TestClientServiceRequest(service, HttpConsts.Get, body);
                request.ETagAction = ETagAction.IfMatch;
                httpRequest = request.CreateRequest();
                Assert.Empty(httpRequest.Headers.IfNoneMatch);
                Assert.Single(httpRequest.Headers.IfMatch);
                Assert.Equal(new EntityTagHeaderValue(body.ETag), httpRequest.Headers.IfMatch.First());

                // Fixing bug https://code.google.com/p/google-api-dotnet-client/issues/detail?id=464.
                // If etag doesn't contain quotas - catch the format exception and log.
                body.ETag = "ETAG";
                request = new TestClientServiceRequest(service, HttpConsts.Post, body);
                httpRequest = request.CreateRequest();
                Assert.Empty(httpRequest.Headers.IfNoneMatch);
                Assert.Empty(httpRequest.Headers.IfMatch);
            }
        }

        /// <summary>Tests that get default ETag action works as expected.</summary>
        [Fact]
        public void GetDefaultETagActionTest()
        {
            Assert.Equal(ETagAction.IfNoneMatch, ClientServiceRequest<object>.GetDefaultETagAction(HttpConsts.Get));
            Assert.Equal(ETagAction.IfMatch, ClientServiceRequest<object>.GetDefaultETagAction(HttpConsts.Post));
            Assert.Equal(ETagAction.IfMatch, ClientServiceRequest<object>.GetDefaultETagAction(HttpConsts.Patch));
            Assert.Equal(ETagAction.IfMatch, ClientServiceRequest<object>.GetDefaultETagAction(HttpConsts.Put));
            Assert.Equal(ETagAction.IfMatch, ClientServiceRequest<object>.GetDefaultETagAction(HttpConsts.Delete));
            Assert.Equal(ETagAction.Ignore, ClientServiceRequest<object>.GetDefaultETagAction("INVALID"));
        }

        #endregion

        private class TestHttpHandler : HttpMessageHandler
        {
            public TestHttpHandler(Func<HttpRequestMessage, HttpResponseMessage> fn) => _fn = fn;

            private Func<HttpRequestMessage, HttpResponseMessage> _fn;

            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
                Task.FromResult(_fn(request));
        }

        // This is a valid JSON, but not one we recognize
        const string ErrorJson_Unknown =
            "{ " +
                "\"error\":\"invalid_target\", " +
                "\"error_description\":\"The target service indicated by the \\\"audience\\\" parameters is invalid. This might either be because the pool or provider is disabled or deleted or because it doesn't exist.\" " +
            "}";

        // HttpContent and HttpStatusCode for the response.
        // Expected ex.Message and ex.ToString() content.
        public static TheoryData<HttpContent, HttpStatusCode, string, string> DeserializeErrorThrows =>
            new TheoryData<HttpContent, HttpStatusCode, string, string>
            {
                {
                    new StringContent(ErrorJson_Unknown),
                    HttpStatusCode.BadRequest,
                    "The service TestService has thrown an exception. HttpStatusCode is BadRequest. No error message was specified.",
                    $"The service TestService has thrown an exception.{Environment.NewLine}" +
                    $"HttpStatusCode is BadRequest.{Environment.NewLine}" +
                    $"No JSON error details were specified.{Environment.NewLine}" +
                    $"Raw error details are: {ErrorJson_Unknown}"
                },
                {
                    new StringContent(""),
                    HttpStatusCode.BadRequest,
                    "The service TestService has thrown an exception. HttpStatusCode is BadRequest. No error message was specified.",
                    $"The service TestService has thrown an exception.{Environment.NewLine}" +
                    $"HttpStatusCode is BadRequest.{Environment.NewLine}" +
                    $"No JSON error details were specified.{Environment.NewLine}" +
                    $"Raw error details are empty or white spaces only."
                },
                {
                    new StringContent("not json"),
                    HttpStatusCode.BadRequest,
                    $"The service TestService has thrown an exception. HttpStatusCode is BadRequest. No error message was specified.",
                    $"The service TestService has thrown an exception.{Environment.NewLine}" +
                    $"HttpStatusCode is BadRequest.{Environment.NewLine}" +
                    $"No JSON error details were specified.{Environment.NewLine}" +
                    $"Raw error details are: not json"
                },
                {
                    null,
                    0,
                    $"The service TestService has thrown an exception. No HttpStatusCode was specified. No error message was specified.",
#if NET6_0_OR_GREATER
                    // Even though we tell our handler to return a response with null content,
                    // in .NET 6 we get a StringContent with empty string content.
                    // This just documents that behaviour.
                    $"The service TestService has thrown an exception.{Environment.NewLine}" +
                    $"No HttpStatusCode was specified.{Environment.NewLine}" +
                    $"No JSON error details were specified.{Environment.NewLine}" +
                    $"Raw error details are empty or white spaces only."
#else
                    $"The service TestService has thrown an exception.{Environment.NewLine}" +
                    $"No HttpStatusCode was specified.{Environment.NewLine}" +
                    $"No error details were specified."
#endif
                },
                {
                    null,
                    HttpStatusCode.BadRequest,
                    $"The service TestService has thrown an exception. HttpStatusCode is BadRequest. No error message was specified.",
#if NET6_0_OR_GREATER
                    // Even though we tell our handler to return a response with null content,
                    // in .NET 6 we get a StringContent with empty string content.
                    // This just documents that behaviour.
                    $"The service TestService has thrown an exception.{Environment.NewLine}" +
                    $"HttpStatusCode is BadRequest.{Environment.NewLine}" +
                    $"No JSON error details were specified.{Environment.NewLine}" +
                    $"Raw error details are empty or white spaces only."
#else
                    $"The service TestService has thrown an exception.{Environment.NewLine}" +
                    $"HttpStatusCode is BadRequest.{Environment.NewLine}" +
                    $"No error details were specified."
#endif
                }
            };

        // Content and HttpStatusCode for the response.
        // Expected error.Message and error.ToString().
        public static TheoryData<string, HttpStatusCode, string, string> DeserializeErrorSucceeds =>
            new TheoryData<string, HttpStatusCode, string, string>
            {
                {
                    "{\"error\":{\"message\":\"json error\"}}",
                    HttpStatusCode.BadRequest,
                    $"json error",
                    $"Google.Apis.Requests.RequestError{Environment.NewLine}" +
                    $"json error [0]{Environment.NewLine}" +
                    $"No individual errors{Environment.NewLine}"
                },
                {
                    "{\"error\":{\"message\":\"json error\",\"errors\":[{\"message\":\"individual error\",\"domain\":\"global\",\"reason\":\"badRequest\"}]}}",
                    HttpStatusCode.BadRequest,
                    $"json error",
                    $"Google.Apis.Requests.RequestError{Environment.NewLine}" +
                    $"json error [0]{Environment.NewLine}" +
                    $"Errors [{Environment.NewLine}" +
                    $"\tMessage[individual error] Location[ - ] Reason[badRequest] Domain[global]{Environment.NewLine}" +
                    $"]{Environment.NewLine}"
                },
            };

        // HttpContent and HttpStatusCode for the response.
        // Expected ex.Message and ex.ToString() content.
        public static TheoryData<HttpContent, HttpStatusCode, string, string> ResponseErrorData
        {
            get
            {
                var data = new TheoryData<HttpContent, HttpStatusCode, string, string>();

                // Regardless of whether deserialization of the error succeeds or fails,
                // the request execution has failed, so service client should throw.

                foreach(var success in DeserializeErrorSucceeds)
                {
                    string content = (string)success[0];
                    HttpStatusCode statusCode = (HttpStatusCode)success[1];
                    string errorMessage = (string)success[2];
                    string errorToString = (string)success[3];

                    data.Add(
                        new StringContent(content),
                        statusCode,
                        $"The service TestService has thrown an exception. HttpStatusCode is {statusCode}. {errorMessage}",
                        $"The service TestService has thrown an exception.{Environment.NewLine}" +
                        $"HttpStatusCode is {statusCode}.{Environment.NewLine}" +
                        $"{errorToString}");
                }

                foreach(var failure in DeserializeErrorThrows)
                {
                    data.Add((HttpContent)failure[0], (HttpStatusCode)failure[1], (string)failure[2], (string)failure[3]);
                }

                return data;
            }
        }

        [Theory]
        [MemberData(nameof(DeserializeErrorThrows))]
        public async Task DeserializeError_Throws(
            HttpContent content, HttpStatusCode statusCode, string expectedExceptionMessage, string expectedToStringContent)
        {
            var response = new HttpResponseMessage(statusCode)
            {
                Content = content
            };
            using (var service = new MockClientService())
            {
                var ex = await Assert.ThrowsAsync<GoogleApiException>(() => service.DeserializeError(response));
                Assert.Equal(expectedExceptionMessage, ex.Message);
                Assert.Equal(statusCode, ex.HttpStatusCode);
                Assert.Contains(expectedToStringContent, ex.ToString());
            }
        }

        [Theory]
        [MemberData(nameof(DeserializeErrorSucceeds))]
        public async Task DeserializeError_Succeeds(string content, HttpStatusCode statusCode, string expectedErrorMessage, string expectedToString)
        {
            var response = new HttpResponseMessage(statusCode)
            {
                Content = new StringContent(content)
            };
            using (var service = new MockClientService())
            {
                RequestError error = await service.DeserializeError(response);
                Assert.False(error.IsOnlyRawContent);
                Assert.Equal(expectedErrorMessage, error.Message);
                Assert.Equal(expectedToString, error.ToString());
                Assert.Equal(content, error.ErrorResponseContent);
            }
        }

        [Theory]
        [MemberData(nameof(ResponseErrorData))]
        public void ResponseError(HttpContent content, HttpStatusCode statusCode, string expectedExceptionMessage, string expectedToStringContent)
        {
            var response = new HttpResponseMessage(statusCode)
            {
                Content = content
            };
            using (var service = new MockClientService(new BaseClientService.Initializer
            {
                HttpClientFactory = new MockHttpClientFactory(new TestHttpHandler(_ => response))
            }))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                var ex = Assert.Throws<GoogleApiException>(() => request.Execute());
                Assert.Equal(expectedExceptionMessage, ex.Message);
                Assert.Contains(expectedToStringContent, ex.ToString());
                Assert.Equal(statusCode, ex.HttpStatusCode);
            }
        }

        private class TestUnsuccessfulResponseHandler : IHttpUnsuccessfulResponseHandler
        {
            public int Count { get; private set; } = 0;
            public Task<bool> HandleResponseAsync(HandleUnsuccessfulResponseArgs args) => Task.FromResult(++Count == 0);
        }

        [Fact]
        public void PerCallUnsuccessfulResponseHandler()
        {
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            using (var service = new MockClientService(new BaseClientService.Initializer
            {
                HttpClientFactory = new MockHttpClientFactory(new TestHttpHandler(_ => response))
            }))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                Assert.Throws<ArgumentNullException>(() => request.AddUnsuccessfulResponseHandler(null));
                var handler = new TestUnsuccessfulResponseHandler();
                request.AddUnsuccessfulResponseHandler(handler);
                var httpRequest = request.CreateRequest();
                var properties = TestHelpers.GetRequestProperties(httpRequest);
                Assert.Equal(handler, ((List<IHttpUnsuccessfulResponseHandler>) properties[ConfigurableMessageHandler.UnsuccessfulResponseHandlerKey]).Single());
                Assert.Throws<GoogleApiException>(() => request.Execute());
                Assert.True(handler.Count > 0);
            }
        }

        private class TestExceptionHandler : IHttpExceptionHandler
        {
            public int Count { get; private set; } = 0;
            public Task<bool> HandleExceptionAsync(HandleExceptionArgs args) => Task.FromResult(++Count == 0);
        }

        [Fact]
        public void PerCallExceptionHandler()
        {
            using (var service = new MockClientService(new BaseClientService.Initializer
            {
                HttpClientFactory = new MockHttpClientFactory(new TestHttpHandler(_ => throw new Exception("mymsg")))
            }))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                Assert.Throws<ArgumentNullException>(() => request.AddExceptionHandler(null));
                var handler = new TestExceptionHandler();
                request.AddExceptionHandler(handler);
                var httpRequest = request.CreateRequest();
                var properties = TestHelpers.GetRequestProperties(httpRequest);
                Assert.Equal(handler, ((List<IHttpExceptionHandler>) properties[ConfigurableMessageHandler.ExceptionHandlerKey]).Single());
                var ex = Assert.Throws<Exception>(() => request.Execute());
                Assert.Equal("mymsg", ex.Message);
                Assert.True(handler.Count > 0);
            }
        }

        private class TestExecuteInterceptor : IHttpExecuteInterceptor
        {
            public int Count { get; private set; } = 0;
            public Task InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken) => Task.FromResult(++Count == 0);
        }

        [Fact]
        public void PerCallExecutionInterceptor()
        {
            using (var service = new MockClientService(new BaseClientService.Initializer
            {
                HttpClientFactory = new MockHttpClientFactory(new TestHttpHandler(_ => throw new Exception("mymsg")))
            }))
            {
                var request = new TestClientServiceRequest(service, "GET", null);
                Assert.Throws<ArgumentNullException>(() => request.AddExecuteInterceptor(null));
                var interceptor = new TestExecuteInterceptor();
                request.AddExecuteInterceptor(interceptor);
                var httpRequest = request.CreateRequest();
                var properties = TestHelpers.GetRequestProperties(httpRequest);
                Assert.Equal(interceptor, ((List<IHttpExecuteInterceptor>) properties[ConfigurableMessageHandler.ExecuteInterceptorKey]).Single());
                Assert.Throws<Exception>(() => request.Execute());
                Assert.True(interceptor.Count > 0);
            }
        }

        [Theory]
        [InlineData("abc", "http://www.example.com/test/abc")]
        [InlineData(" %va/ue", "http://www.example.com/test/%20%25va%2Fue")]
        [InlineData("foo/bar/[baz] test.txt", "http://www.example.com/test/foo%2Fbar%2F%5Bbaz%5D%20test.txt")]
        public void GenerateRequestUri(string idValue, string expectedRequestUri)
        {
            var request = new TestClientServiceRequest(new MockClientService("http://www.example.com"), "POST", null)
            {
                OverrideRestPath = "test/{id}",
                Id = idValue
            };
            string requestUri = request.GenerateRequestUriPublic();
            Assert.Equal(expectedRequestUri, requestUri);
        }

        /// <summary>
        /// Client request which contains validated parameters. Both "optional" and "required"
        /// have patterns of "valid" (so only a value of "valid" should pass validation).
        /// </summary>
        class ClientServiceRequestWithValidatedParameters : TestClientServiceRequest
        {
            [RequestParameter("required", RequestParameterType.Query)]
            public string Required { get; set; }

            [RequestParameter("optional", RequestParameterType.Query)]
            public string Optional { get; set; }

            public ClientServiceRequestWithValidatedParameters(IClientService service)
                : base(service, "GET", body: null)
            {
                RequestParameters.Add("required", new Parameter
                {
                    Name = "required",
                    IsRequired = true,
                    ParameterType = "query",
                    Pattern = "^valid$"
                });
                RequestParameters.Add("optional", new Parameter
                {
                    Name = "optional",
                    IsRequired = false,
                    ParameterType = "query",
                    Pattern = "^valid$"
                });
            }
        }

        [Theory, CombinatorialData]
        public void Validation_ValidValues(bool serviceValidation, bool requestValidation,
            [CombinatorialValues("valid")] string requiredValue, [CombinatorialValues("valid", null)] string optionalValue)
        {
            var request = CreateClientServiceRequestWithValidatedParameters(serviceValidation, requestValidation, requiredValue, optionalValue);
            // We're just checking that this doesn't throw.
            request.CreateRequest();
        }

        [Theory]
        [InlineData(true, null, null, "valid")]
        [InlineData(true, null, "valid", "invalid")]
        // Even if we don't validate patterns, a required parameter is still required.
        [InlineData(true, false, null, "valid")]
        [InlineData(false, null, null, "valid")]
        // Request validation overrides service validation
        [InlineData(false, true, "valid", "invalid")]
        public void Validation_InvalidValues_Throwing(bool serviceValidation, bool? requestValidation, string requiredValue, string optionalValue)
        {
            var request = CreateClientServiceRequestWithValidatedParameters(serviceValidation, requestValidation, requiredValue, optionalValue);
            Assert.Throws<GoogleApiException>(() => request.CreateRequest());
        }

        [Theory]
        [InlineData(false, null, "valid", "invalid")]
        [InlineData(false, false, "valid", "invalid")]
        // Request validation overrides service validation
        [InlineData(true, false, "valid", "invalid")]
        public void Validation_InvalidValues_Ignored(bool serviceValidation, bool? requestValidation, string requiredValue, string optionalValue)
        {
            var request = CreateClientServiceRequestWithValidatedParameters(serviceValidation, requestValidation, requiredValue, optionalValue);
            // We're just checking that this doesn't throw.
            request.CreateRequest();
        }

        private ClientServiceRequestWithValidatedParameters CreateClientServiceRequestWithValidatedParameters(
            bool serviceValidation, bool? requestValidation, string requiredValue, string optionalValue)
        {
            var service = new MockClientService(new BaseClientService.Initializer { ValidateParameters = serviceValidation });
            return new ClientServiceRequestWithValidatedParameters(service)
            {
                ValidateParameters = requestValidation,
                Required = requiredValue,
                Optional = optionalValue
            };
        }

        [Fact]
        public async Task ApiVersion_NotSet()
        {
            HttpRequestMessage lastRequest = null;
            var handler = new TestHttpHandler(req =>
            {
                lastRequest = req;
                return new HttpResponseMessage
                {
                    // In .NET Framework 4.6.2 Content is null and since the request here succeedds,
                    // we attempt to parse the response and get NullReferenceException.
                    // Note this is a test problem and not a production code problem because Content
                    // won't be null on a successful response.
                    // In .NET 6, Content will be EmptyContent.
                    Content = new StringContent("")
                };
            });
            var initializer = new BaseClientService.Initializer
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            var service = new MockClientService(initializer);
            var request = new TestClientServiceRequest(service, "GET", null);
            await request.ExecuteAsync();

            Assert.NotNull(lastRequest);
            Assert.False(lastRequest.Headers.Contains(ClientServiceRequest<MockRequest>.ApiVersionHeaderName));
        }

        [Fact]
        public async Task ApiVersion_Set()
        {
            HttpRequestMessage lastRequest = null;
            var handler = new TestHttpHandler(req =>
            {
                lastRequest = req;
                return new HttpResponseMessage
                {
                    // In .NET Framework 4.6.2 Content is null and since the request here succeedds,
                    // we attempt to parse the response and get NullReferenceException.
                    // Note this is a test problem and not a production code problem because Content
                    // won't be null on a successful response.
                    // In .NET 6, Content will be EmptyContent.
                    Content = new StringContent("")
                };
            });
            var initializer = new BaseClientService.Initializer
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            var service = new MockClientService(initializer);
            var request = new TestClientServiceRequest(service, "GET", null) { ApiVersionImpl = "test-version" };
            await request.ExecuteAsync();

            Assert.NotNull(lastRequest);
            var value = Assert.Single(lastRequest.Headers.GetValues(ClientServiceRequest<MockRequest>.ApiVersionHeaderName));
            Assert.Equal("test-version", value);
        }
    }
}