File size: 26,512 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
/*
Copyright 2013 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.Requests;
using Google.Apis.Services;
using Google.Apis.Tests.Mocks;
using Google.Apis.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace Google.Apis.Tests.Apis.Requests
{
    /// <summary>Tests for <seealso cref="Google.Apis.Requests.BatchRequest"/>.</summary>
    public class BatchRequestTest
    {
        private static string ExpectedContentMessage = NormalizeLineEndings(@"--BOUNDARY
Content-Type: application/http

POST http://sample.com/5?q=20
If-Match: ""100""
Content-Type: application/json; charset=utf-8
Content-Length:  41

{""etag_key"":""\""100\"""",""name_key"":""Name1""}

--BOUNDARY
Content-Type: application/http

POST http://sample.com/5?q=20
If-Match: ""200""
Content-Type: application/json; charset=utf-8
Content-Length:  43

{""etag_key"":""\""200\"""",""name_key"":""Name1-1""}

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

            [Newtonsoft.Json.JsonPropertyAttribute("id_key")]
            public Nullable<int> Id { get; set; }

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

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

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

            [Newtonsoft.Json.JsonPropertyAttribute("name_key")]
            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>
        {
            private MockRequest body;

            [RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)]
            public int Id { get { return 5; } }

            [RequestParameterAttribute("q", Google.Apis.Util.RequestParameterType.Query)]
            public int Q { get { return 20; } }

            public TestClientServiceRequest(IClientService service, MockRequest body)
                : base(service)
            {
                this.body = body;
                InitParameters();
            }

            public override string MethodName
            {
                get { return "POST"; }
            }

            public override string RestPath
            {
                get { return "{id}"; }
            }

            public override string HttpMethod
            {
                get { return "POST"; }
            }

            protected override object GetBody()
            {
                return body;
            }

            protected override void InitParameters()
            {
                base.InitParameters();
                RequestParameters.Add("id", new Parameter { Name = "id", ParameterType = "path" });
                RequestParameters.Add("q", new Parameter { Name = "q", ParameterType = "query" });
            }
        }

        /// <summary>
        /// Message handler which verifies that the input request is correct and returns a response. The response may 
        /// contain an unsuccessful response for the 2nd individual request based on the boolean flag to its 
        /// constructor.
        /// </summary>
        class BatchMessageHandler : CountableMessageHandler
        {
            private static string ResponseContent = NormalizeLineEndings(@"--BOUNDARY
Content-Type: application/http

HTTP/1.1 200 OK
ETag: ""\""10011\""""
Content-Type: application/json; charset=UTF-8
Content-Length: 505
Vary: Accept-Encoding
Vary: Referer

{
 ""etag_key"": ""\""10011\"""",
 ""id_key"": 1
}

--BOUNDARY
Content-Type: application/http

SECOND_RESPONSE

--BOUNDARY--");

            private static string SuccessfulResponse = NormalizeLineEndings(
@"HTTP/1.1 200 OK
ETag: ""234""
Content-Type: application/json; charset=UTF-8
Content-Length: 202

{
 ""id_key"": 2
}");

            private static string UnsuccessfulResponse = NormalizeLineEndings(
@"HTTP/1.1 404 Not Found
Content-Type: application/json; charset=UTF-8
Date: Thu, 14 Nov 2013 22:03:08 GMT
Expires: Thu, 14 Nov 2013 22:03:08 GMT
Cache-Control: private, max-age=0
Content-Length: 202

{
 ""error"": {
  ""errors"": [
   {
    ""domain"": ""global"",
    ""reason"": ""notFound"",
    ""message"": ""Not Found"",
    ""customIndividual"": ""Custom individual error info""
   }
  ],
  ""code"": 404,
  ""message"": ""Not Found"",
  ""custom"": ""Custom error info""
 }
}");
            bool successful2ndResponse;
            public BatchMessageHandler(bool successful2ndReponse = true)
            {
                this.successful2ndResponse = successful2ndReponse;
            }

            protected override async Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request,
                CancellationToken cancellationToken)
            {
                // Verify Request Message
                var contentType = request.Content.Headers.ContentType;
                Assert.Equal("multipart/mixed", contentType.MediaType.ToString());
                var parameter = Assert.Single(contentType.Parameters);
                Assert.True(parameter.ToString().StartsWith("boundary=", StringComparison.Ordinal),
                    "Parameter should start with boundary=");
                var boundary = parameter.ToString().Substring("boundary=".Length).
                    Replace("\"", "");
                var expectedContent = ExpectedContentMessage.Replace("BOUNDARY", boundary);
                var actualContent = await request.Content.ReadAsStringAsync();
                Assert.Equal(expectedContent, NormalizeLineEndings(actualContent));

                HttpResponseMessage response = new HttpResponseMessage();
                // Response contains 2 responses. The second one is successful based on the constructor's parameter.
                var content = ResponseContent.Replace("BOUNDARY", boundary).Replace("SECOND_RESPONSE",
                    successful2ndResponse ? SuccessfulResponse : UnsuccessfulResponse);
                response.Content = new StringContent(content,
                    Encoding.UTF8, "multipart/mixed");
                response.Content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("boundary", boundary));

                return response;
            }
        }

        [Fact]
        public void ExecuteAsync_Test()
        {
            SubtestExecuteAsync_Test(true);
        }

        [Fact]
        public void ExecuteAsync_Error_Test()
        {
            SubtestExecuteAsync_Test(false);
        }

        /// <summary>Subtest for the execute method.</summary>
        /// <param name="successful2ndReponse">Indicates if the 2nd individual response is unsuccessful.</param>
        void SubtestExecuteAsync_Test(bool successful2ndReponse)
        {
            var handler = new BatchMessageHandler(successful2ndReponse);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer, "http://sample.com"))
            {
                var responses = new List<Tuple<MockResponse, RequestError, HttpResponseMessage>>();
                var batch = new BatchRequest(service);
                var request1 = new TestClientServiceRequest(service, new MockRequest
                    {
                        ETag = "\"100\"",
                        Name = "Name1"
                    });
                var request2 = new TestClientServiceRequest(service, new MockRequest
                    {
                        ETag = "\"200\"",
                        Name = "Name1-1"
                    });
                // Adding the content, error and message into the responses list to verify the results later on
                batch.Queue<MockResponse>(request1, (content, error, index, message) =>
                    {
                        responses.Add(new Tuple<MockResponse, RequestError, HttpResponseMessage>(
                            content, error, message));
                    });
                batch.Queue<MockResponse>(request2, (content, error, index, message) =>
                    {
                        responses.Add(new Tuple<MockResponse, RequestError, HttpResponseMessage>(
                                                    content, error, message));
                    });
                batch.ExecuteAsync().Wait();

                Assert.Equal(2, responses.Count);
                var tuple = responses[0];
                Assert.Null(tuple.Item2); // no error
                var response = tuple.Item1; // response
                Assert.Equal(@"""10011""", response.ETag);
                Assert.Equal(1, response.Id);
                var httpMessage = tuple.Item3; // HTTP message
                Assert.Equal("application/json", httpMessage.Content.Headers.ContentType.MediaType);
                Assert.Equal(505, httpMessage.Content.Headers.ContentLength);
                Assert.Contains("Accept-Encoding", httpMessage.Headers.Vary);
                Assert.Contains("Referer", httpMessage.Headers.Vary);

                tuple = responses[1];
                if (successful2ndReponse)
                {
                    Assert.Null(tuple.Item2); // no error
                    response = tuple.Item1; // response
                    Assert.Equal(@"""234""", response.ETag);
                    Assert.Equal(2, response.Id);
                }
                else
                {
                    Assert.Null(tuple.Item1); // no response
                    RequestError reqError = tuple.Item2; // error
                    Assert.Single(reqError.Errors);
                    Assert.Equal(404, reqError.Code);
                    Assert.Equal("Not Found", reqError.Message);
                    Assert.NotNull(reqError.ErrorResponseContent);
                    Assert.Contains("Custom individual error info", reqError.ErrorResponseContent);
                    Assert.Contains("Custom error info", reqError.ErrorResponseContent);
                }
                httpMessage = tuple.Item3; // HTTP message
                Assert.Equal("application/json", httpMessage.Content.Headers.ContentType.MediaType);
                Assert.Equal(202, httpMessage.Content.Headers.ContentLength);
            }
        }

        [Fact]
        public async Task ExecuteAsync_NoCallback_Test()
        {
            var handler = new BatchMessageHandler(true);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer, "http://sample.com"))
            {
                var responses = new List<Tuple<MockResponse, RequestError, HttpResponseMessage>>();
                var batch = new BatchRequest(service);
                var request1 = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"100\"",
                    Name = "Name1"
                });
                var request2 = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"200\"",
                    Name = "Name1-1"
                });
                batch.Queue<MockResponse>(request1, null);
                batch.Queue<MockResponse>(request2, null);
                await batch.ExecuteAsync();
            }
        }

        [Fact]
        public async Task CreateOuterRequestContent_Test()
        {
            using (var service = new MockClientService("http://sample.com"))
            {
                var request1 = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"100\"",
                    Name = "Name1"
                });
                var request2 = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"200\"",
                    Name = "Name1-1"
                });

                var content = await BatchRequest.CreateOuterRequestContent(new[] { request1, request2 });
                var requestStr = await content.ReadAsStringAsync();

                // Read the boundary.
                string boundary = null;
                using (var reader = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(requestStr))))
                {
                    var line = reader.ReadLine();
                    boundary = line.Substring(2);
                }

                Assert.Equal(ExpectedContentMessage.Replace("BOUNDARY", boundary), NormalizeLineEndings(requestStr));
            }
        }

        [Fact]
        public async Task CreateIndividualRequest_Test()
        {
            var expectedMessage = NormalizeLineEndings(@"POST http://sample.com/5?q=20
If-Match: ""123""
Content-Type: application/json; charset=utf-8
Content-Length:  40

{""etag_key"":""\""123\"""",""name_key"":""Name""}
");
            using (var service = new MockClientService("http://sample.com"))
            {
                var request = new TestClientServiceRequest(service, new MockRequest
                    {
                        ETag = "\"123\"",
                        Name = "Name"
                    });
                var content = await BatchRequest.CreateIndividualRequest(request);
                var requestStr = await content.ReadAsStringAsync();
                Assert.Equal(expectedMessage, NormalizeLineEndings(requestStr));
            }
        }

        [Fact]
        public async Task CreateRequestContentString_Test()
        {
            var expectedMessage = NormalizeLineEndings(@"GET http://test.com:2020/
Accept-Encoding: gzip
Content-Type: application/json
Content-Length:  11

hello world
");
            var request = new HttpRequestMessage(HttpMethod.Get, "http://test.com:2020");
            request.Content = new StringContent("hello world");
            request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var requestStr = await BatchRequest.CreateRequestContentString(request);
            Assert.Equal(expectedMessage, NormalizeLineEndings(requestStr));
        }

        [Fact]
        public void BatchUrl()
        {
            using (var service = new MockClientService("http://sample.com", "http://batch.sample.com"))
            {
                var batch = new BatchRequest(service);
                Assert.Equal("http://batch.sample.com", batch.BatchUrl);
            }
            using (var service = new MockClientService("http://sample.com", null))
            {
                var batch = new BatchRequest(service);
                Assert.Equal("https://www.googleapis.com/batch", batch.BatchUrl);
            }
        }

        class BatchEndpointErrorMessageHandler : CountableMessageHandler
        {
            private readonly string _responseContent;

            public BatchEndpointErrorMessageHandler(string responseContent) => _responseContent = responseContent;

            protected override Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) => 
                Task.FromResult(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    ReasonPhrase = "Bad Request",
                    Content = _responseContent == null ? null : new StringContent(_responseContent, Encoding.UTF8, "application/json")
                });
        }

        [Fact]
        public async Task BatchEndpointErrorJsonContent()
        {
            string jsonErrorContent = NormalizeLineEndings(@"
{
  ""error"": {
    ""code"": 400,
    ""message"": ""Failed to parse batch request, error: Failed in parsing HTTP headers: invalid content\n. Received batch body: "",
    ""errors"": [
      {
        ""message"": ""Failed to parse batch request, error: Failed in parsing HTTP headers: invalid content\n. Received batch body: "",
        ""domain"": ""global"",
        ""reason"": ""badRequest""
      }
    ],
    ""status"": ""INVALID_ARGUMENT""
  }
}");

            using (var service = new MockClientService( new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(new BatchEndpointErrorMessageHandler(jsonErrorContent))
            }, "http://sample.com"))
            {
                var batchRequest = new BatchRequest(service);
                var request = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"100\"",
                    Name = "Name1"
                });
                
                batchRequest.Queue<MockResponse>( request, (c, e, i, m) =>
                    Assert.Fail("The batch endpoint call should have failed. Callbacks for individual requests shouldn't be called."));

                HttpRequestException outerException = await Assert.ThrowsAsync<HttpRequestException>(() => batchRequest.ExecuteAsync());

                Assert.Contains("400", outerException.Message);
                Assert.Contains("Bad Request", outerException.Message);

                GoogleApiException innerException = Assert.IsType<GoogleApiException>(outerException.InnerException);

                Assert.Equal(HttpStatusCode.BadRequest, innerException.HttpStatusCode);
                Assert.NotNull(innerException.Error);

                RequestError requestError = innerException.Error;
                Assert.Equal(jsonErrorContent, requestError.ErrorResponseContent);
                Assert.Equal(400, requestError.Code);

                SingleError singleError = Assert.Single(requestError.Errors);
                Assert.Equal("global", singleError.Domain);
                Assert.Equal("badRequest", singleError.Reason);
            }
        }

        [Fact]
        public async Task BatchEndpointErrorNonJsonContent()
        {
            string nonJsonContent = "Invalid JSON";
            string expectedExceptionMessage = "The service TestService has thrown an exception. HttpStatusCode is BadRequest. No error message was specified.";
            string expectedExceptionToStringContent =
                $"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: {nonJsonContent}";

            using (var service = new MockClientService( new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(new BatchEndpointErrorMessageHandler(nonJsonContent))
            }, "http://sample.com"))
            {
                var batchRequest = new BatchRequest(service);
                var request = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"100\"",
                    Name = "Name1"
                });

                batchRequest.Queue<MockResponse>(request, (c, e, i, m) =>
                   Assert.Fail("The batch endpoint call should have failed. Callbacks for individual requests shouldn't be called."));

                HttpRequestException outerException = await Assert.ThrowsAsync<HttpRequestException>(() => batchRequest.ExecuteAsync());

                Assert.Contains("400", outerException.Message);
                Assert.Contains("Bad Request", outerException.Message);

                GoogleApiException innerException = Assert.IsType<GoogleApiException>(outerException.InnerException);

                Assert.Equal(HttpStatusCode.BadRequest, innerException.HttpStatusCode);
                Assert.True(innerException.Error.IsOnlyRawContent);
                Assert.Equal(expectedExceptionMessage, innerException.Message);
                Assert.Contains(expectedExceptionToStringContent, innerException.ToString());

                Assert.IsAssignableFrom<JsonException>(innerException.InnerException);
            }
        }

        [Fact]
        public async Task BatchEndpointErrorNullContent()
        {
            string expectedExceptionMessage = "The service TestService has thrown an exception. HttpStatusCode is BadRequest. No error message was specified.";

            using (var service = new MockClientService( new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(new BatchEndpointErrorMessageHandler(null))
            }, "http://sample.com"))
            {
                var batchRequest = new BatchRequest(service);
                var request = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"100\"",
                    Name = "Name1"
                });

                batchRequest.Queue<MockResponse>(request, (c, e, i, m) =>
                   Assert.Fail("The batch endpoint call should have failed. Callbacks for individual requests shouldn't be called."));

                HttpRequestException outerException = await Assert.ThrowsAsync<HttpRequestException>(() => batchRequest.ExecuteAsync());

                Assert.Contains("400", outerException.Message);
                Assert.Contains("Bad Request", outerException.Message);

                GoogleApiException innerException = Assert.IsType<GoogleApiException>(outerException.InnerException);
                Assert.Equal(HttpStatusCode.BadRequest, innerException.HttpStatusCode);
#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.
                Assert.Equal("", innerException.Error.ErrorResponseContent);
                string expectedExceptionToStringContent =
                    $"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
                Assert.Null(innerException.Error);
                string expectedExceptionToStringContent =
                    $"The service TestService has thrown an exception.{Environment.NewLine}" +
                    $"HttpStatusCode is BadRequest.{Environment.NewLine}" +
                    $"No error details were specified.";
#endif
                Assert.Equal(expectedExceptionMessage, innerException.Message);
                Assert.Contains(expectedExceptionToStringContent, innerException.ToString());
            }
        }

        [Fact]
        public async Task ParseAsHttpResponse_NormalContent()
        {
            string content = @"Content-Type: application/http

HTTP/1.1 200 OK
Vary: Origin
Vary: X-Origin
Vary: Referer
Content-Type: application/json

{}
";
            var response = BatchRequest.ParseAsHttpResponse(content);
            Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
            Assert.Equal("{}", (await response.Content.ReadAsStringAsync()).Trim());
        }

        [Fact]
        public async Task ParseAsHttpResponse_NoContent()
        {
            string content = @"Content-Type: application/http

HTTP/1.1 204 No content
Vary: Origin
Vary: X-Origin
Vary: Referer

";
            var response = BatchRequest.ParseAsHttpResponse(content);
            var httpContent = response.Content;
            Assert.NotNull(content);

#if NET6_0_OR_GREATER
            Assert.Null(httpContent.Headers.ContentType);
#else
            Assert.Equal("text/plain", httpContent.Headers.ContentType.MediaType);
#endif
            Assert.Equal("", (await response.Content.ReadAsStringAsync()).Trim());
        }

        [Fact]
        public async Task ParseAsHttpResponse_ContentButNoContentType()
        {
            string content = @"Content-Type: application/http

HTTP/1.1 200 OK
Vary: Origin
Vary: X-Origin
Vary: Referer

{}
";
            var response = BatchRequest.ParseAsHttpResponse(content);
            Assert.Equal("text/plain", response.Content.Headers.ContentType.MediaType);
            Assert.Equal("{}", (await response.Content.ReadAsStringAsync()).Trim());
        }

        // Line endings in HttpContent are different between mono & .NET.
        private static string NormalizeLineEndings(string s) =>
            Regex.Replace(s, @"\r\n|\n", "\r\n");
    }
}