-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHttpResponseMessageTaskAssertions.cs
More file actions
887 lines (775 loc) · 32.3 KB
/
Copy pathHttpResponseMessageTaskAssertions.cs
File metadata and controls
887 lines (775 loc) · 32.3 KB
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
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT.
// Copyright (C) Leszek Pomianowski and Fluent Framework Contributors.
// All Rights Reserved.
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using AwesomeAssertions;
using AwesomeAssertions.Execution;
using AwesomeAssertions.Primitives;
namespace Fluent.Client.AwesomeAssertions;
/// <summary>
/// Provides fluent assertion methods for a <see cref="Task{HttpResponseMessage}"/> returned by
/// Fluent.Client HTTP methods such as <c>Get</c>, <c>Post</c>, <c>Put</c>, and <c>Delete</c>.
/// </summary>
/// <remarks>
/// Obtain an instance by calling <c>.Should()</c> on any Fluent.Client method result. The task is
/// awaited internally, so you do not need to await it before asserting.
/// <para>
/// For assertions on an already-materialised <see cref="HttpResponseMessage"/>, use
/// <see cref="HttpResponseMessageAssertions"/> via the <c>HttpResponseMessageExtensions.Should()</c>
/// extension instead.
/// </para>
/// </remarks>
public class HttpResponseMessageTaskAssertions(
Task<HttpResponseMessage> instance,
AssertionChain assertionChain
)
: ReferenceTypeAssertions<Task<HttpResponseMessage>, HttpResponseMessageTaskAssertions>(
instance,
assertionChain
)
{
private readonly AssertionChain chain = assertionChain;
protected override string Identifier => "http-response-task";
// ReSharper disable once MemberCanBePrivate.Global
// ReSharper disable once FieldCanBeMadeReadOnly.Global
/// <summary>
/// Shared <see cref="JsonSerializerOptions"/> used when deserializing response bodies in
/// <c>Satisfy<TBody></c> and <c>SucceedWith<TBody></c>.
/// </summary>
/// <remarks>
/// Default settings: property names are matched case-insensitively, trailing commas are
/// allowed, and enums are serialized as strings. Replace this field globally to customise
/// deserialization for your entire test suite, for example to register custom converters.
/// </remarks>
public static JsonSerializerOptions DefaultJsonOptions = new()
{
PropertyNameCaseInsensitive = true,
AllowTrailingCommas = true,
WriteIndented = true,
IncludeFields = false,
Converters = { new JsonStringEnumConverter() },
};
/// <summary>
/// Asserts that the HTTP response indicates success (status code 2xx).
/// </summary>
[CustomAssertion]
public async Task Succeed(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
using HttpResponseMessage response = await Subject;
chain
.BecauseOf(because, becauseArgs)
.ForCondition(response.IsSuccessStatusCode)
.FailWith(
$"Expected HTTP response to be successful, but found {(int)response.StatusCode} ({response.ReasonPhrase})."
);
}
/// <summary>
/// Asserts that the HTTP response is both successful (status code 2xx) and has exactly
/// <paramref name="expectedStatusCode"/>.
/// </summary>
/// <param name="expectedStatusCode">The exact status code the response must have.</param>
/// <param name="because">A reason to include in the failure message.</param>
/// <param name="becauseArgs">Format arguments for <paramref name="because"/>.</param>
/// <remarks>
/// Unlike <c>HaveStatusCode</c>, this method enforces that the response is in the success
/// range first, making the intent explicit when you want to confirm e.g. a <c>201 Created</c>
/// and not just any arbitrary code.
/// </remarks>
[CustomAssertion]
public async Task SucceedWith(
System.Net.HttpStatusCode expectedStatusCode,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
using HttpResponseMessage response = await Subject;
chain
.BecauseOf(because, becauseArgs)
.ForCondition(response.StatusCode == expectedStatusCode)
.FailWith(
$"Expected HTTP response to have status code {(int)expectedStatusCode} ({expectedStatusCode}), "
+ $"but found {(int)response.StatusCode} ({response.ReasonPhrase})."
);
}
/// <summary>
/// Asserts that the HTTP response indicates a failure (non-success status code).
/// </summary>
[CustomAssertion]
public async Task Fail([StringSyntax("CompositeFormat")] string because = "", params object[] becauseArgs)
{
using HttpResponseMessage response = await Subject;
chain
.BecauseOf(because, becauseArgs)
.ForCondition(!response.IsSuccessStatusCode)
.FailWith(
$"Expected HTTP response to fail, but found {(int)response.StatusCode} ({response.ReasonPhrase})."
);
}
/// <summary>
/// Asserts that the HTTP response has exactly <paramref name="expectedStatusCode"/>, without
/// any constraint on whether the status is a success or failure code.
/// </summary>
/// <param name="expectedStatusCode">The exact status code the response must have.</param>
/// <param name="because">A reason to include in the failure message.</param>
/// <param name="becauseArgs">Format arguments for <paramref name="because"/>.</param>
/// <remarks>
/// Use this method when asserting error codes such as 400, 401, or 422 where
/// <c>SucceedWith</c> would fail the success check before comparing the code.
/// </remarks>
[CustomAssertion]
public async Task HaveStatusCode(
System.Net.HttpStatusCode expectedStatusCode,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
using HttpResponseMessage response = await Subject;
chain
.BecauseOf(because, becauseArgs)
.ForCondition(response.StatusCode == expectedStatusCode)
.FailWith(
$"Expected HTTP response to have status code {(int)expectedStatusCode} ({expectedStatusCode}), "
+ $"but found {(int)response.StatusCode} ({response.ReasonPhrase})."
);
}
/// <summary>
/// Asserts that the HTTP response contains the expected header.
/// </summary>
[CustomAssertion]
public async Task HaveHeader(
string headerName,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
ThrowIfNull(headerName, nameof(headerName));
using HttpResponseMessage response = await Subject;
bool headerExists = ContainsHeader(response, headerName);
chain
.BecauseOf(because, becauseArgs)
.ForCondition(headerExists)
.FailWith($"Expected HTTP response to contain header \"{headerName}\", but it was not found.");
}
/// <summary>
/// Asserts that the HTTP response contains the expected header with the expected value.
/// </summary>
[CustomAssertion]
public async Task HaveHeaderWithValue(
string headerName,
string expectedValue,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
ThrowIfNull(headerName, nameof(headerName));
ThrowIfNull(expectedValue, nameof(expectedValue));
using HttpResponseMessage response = await Subject;
bool headerExists = ContainsHeader(response, headerName);
chain
.BecauseOf(because, becauseArgs)
.ForCondition(headerExists)
.FailWith($"Expected HTTP response to contain header \"{headerName}\", but it was not found.");
if (!headerExists)
{
return;
}
string[] actualHeaderValues = GetHeaderValues(response, headerName);
string actualValues = string.Join(", ", actualHeaderValues);
bool containsExpectedValue = actualHeaderValues.Any(value =>
string.Equals(value, expectedValue, StringComparison.OrdinalIgnoreCase)
);
chain
.BecauseOf(because, becauseArgs)
.ForCondition(containsExpectedValue)
.FailWith(
$"Expected HTTP response header \"{headerName}\" to contain value \"{expectedValue}\", but found \"{actualValues}\"."
);
}
/// <summary>
/// Asserts that the HTTP response contains all expected headers.
/// </summary>
[CustomAssertion]
public async Task HaveHeaders(params string[] headerNames)
{
ThrowIfNull(headerNames, nameof(headerNames));
using HttpResponseMessage response = await Subject;
foreach (string headerName in headerNames)
{
ThrowIfNull(headerName, nameof(headerName));
}
string[] missingHeaders = [.. headerNames.Where(name => !ContainsHeader(response, name))];
string expectedList = string.Join(", ", headerNames.Select(name => $"\"{name}\""));
string missingList = string.Join(", ", missingHeaders.Select(name => $"\"{name}\""));
chain
.ForCondition(missingHeaders.Length == 0)
.FailWith(
$"Expected HTTP response to contain headers {expectedList}, but the following were not found: {missingList}."
);
}
/// <summary>
/// Asserts that the HTTP response indicates a failure with the specific status code.
/// </summary>
[CustomAssertion]
public async Task FailWith(
System.Net.HttpStatusCode expectedStatusCode,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
using HttpResponseMessage response = await Subject;
chain
.BecauseOf(because, becauseArgs)
.ForCondition(!response.IsSuccessStatusCode && response.StatusCode == expectedStatusCode)
.FailWith(
$"Expected HTTP response to fail with status code {(int)expectedStatusCode} ({expectedStatusCode}), "
+ $"but found {(int)response.StatusCode} ({response.ReasonPhrase})."
);
}
/// <summary>
/// Asserts that the HTTP response has a 404 Not Found status code.
/// </summary>
[CustomAssertion]
public async Task BeNotFound(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
) => await HaveStatusCode(System.Net.HttpStatusCode.NotFound, because, becauseArgs);
/// <summary>
/// Asserts that the HTTP response has a 401 Unauthorized status code.
/// </summary>
[CustomAssertion]
public async Task BeUnauthorized(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
) => await HaveStatusCode(System.Net.HttpStatusCode.Unauthorized, because, becauseArgs);
/// <summary>
/// Asserts that the HTTP response has a 400 Bad Request status code.
/// </summary>
[CustomAssertion]
public async Task BeBadRequest(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
) => await HaveStatusCode(System.Net.HttpStatusCode.BadRequest, because, becauseArgs);
/// <summary>
/// Asserts that the HTTP response has a 201 Created status code.
/// </summary>
[CustomAssertion]
public async Task BeCreated(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
) => await HaveStatusCode(System.Net.HttpStatusCode.Created, because, becauseArgs);
/// <summary>
/// Asserts that the HTTP response has a 204 No Content status code.
/// </summary>
[CustomAssertion]
public async Task BeNoContent(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
) => await HaveStatusCode(System.Net.HttpStatusCode.NoContent, because, becauseArgs);
/// <summary>
/// Asserts that the HTTP response has a 403 Forbidden status code.
/// </summary>
[CustomAssertion]
public async Task BeForbidden(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
) => await HaveStatusCode(System.Net.HttpStatusCode.Forbidden, because, becauseArgs);
/// <summary>
/// Asserts that the HTTP response has a 409 Conflict status code.
/// </summary>
[CustomAssertion]
public async Task BeConflict(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
) => await HaveStatusCode(System.Net.HttpStatusCode.Conflict, because, becauseArgs);
/// <summary>
/// Asserts that the HTTP response has the expected Content-Type header.
/// </summary>
[CustomAssertion]
public async Task HaveContentType(
string expectedMediaType,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
ThrowIfNull(expectedMediaType, nameof(expectedMediaType));
using HttpResponseMessage response = await Subject;
string? actualContentType = response.Content?.Headers?.ContentType?.MediaType;
chain
.BecauseOf(because, becauseArgs)
.ForCondition(
string.Equals(actualContentType, expectedMediaType, StringComparison.OrdinalIgnoreCase)
)
.FailWith(
$"Expected HTTP response to have Content-Type \"{expectedMediaType}\", but found \"{actualContentType ?? "(none)"}\"."
);
}
/// <summary>
/// Asserts that the HTTP response indicates a redirect (3xx status code).
/// </summary>
[CustomAssertion]
public async Task BeRedirect(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
using HttpResponseMessage response = await Subject;
int statusCode = (int)response.StatusCode;
chain
.BecauseOf(because, becauseArgs)
.ForCondition(statusCode >= 300 && statusCode <= 399)
.FailWith(
$"Expected HTTP response to be a redirect (3xx), but found {statusCode} ({response.ReasonPhrase})."
);
}
/// <summary>
/// Asserts that the HTTP response is a redirect (3xx) whose <c>Location</c> header equals
/// <paramref name="expectedUrl"/>.
/// </summary>
/// <param name="expectedUrl">The URL the <c>Location</c> header must match.</param>
/// <param name="because">A reason to include in the failure message.</param>
/// <param name="becauseArgs">Format arguments for <paramref name="because"/>.</param>
/// <remarks>
/// The <c>Location</c> header comparison is case-insensitive. Use this assertion to verify
/// login redirects, permanent moves (301), or any endpoint that returns a 3xx with an
/// explicit target URL.
/// </remarks>
[CustomAssertion]
public async Task BeRedirectedTo(
string expectedUrl,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
ThrowIfNull(expectedUrl, nameof(expectedUrl));
using HttpResponseMessage response = await Subject;
int statusCode = (int)response.StatusCode;
chain
.BecauseOf(because, becauseArgs)
.ForCondition(statusCode >= 300 && statusCode <= 399)
.FailWith(
$"Expected HTTP response to be a redirect (3xx), but found {statusCode} ({response.ReasonPhrase})."
);
if (statusCode < 300 || statusCode > 399)
{
return;
}
string? actualLocation = response.Headers.Location?.ToString();
chain
.BecauseOf(because, becauseArgs)
.ForCondition(string.Equals(actualLocation, expectedUrl, StringComparison.OrdinalIgnoreCase))
.FailWith(
$"Expected HTTP response to redirect to \"{expectedUrl}\", but found \"{actualLocation ?? "(none)"}\"."
);
}
/// <summary>
/// Asserts that the HTTP response has an empty body.
/// </summary>
[CustomAssertion]
public async Task HaveEmptyBody(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
using HttpResponseMessage response = await Subject;
string content = await response.Content.ReadAsStringAsync();
chain
.BecauseOf(because, becauseArgs)
.ForCondition(string.IsNullOrWhiteSpace(content))
.FailWith(
$"Expected HTTP response to have an empty body, but found content with length {content.Length}."
);
}
/// <summary>
/// Asserts that the HTTP response has a non-empty body.
/// </summary>
[CustomAssertion]
public async Task HaveNonEmptyBody(
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
using HttpResponseMessage response = await Subject;
string content = await response.Content.ReadAsStringAsync();
chain
.BecauseOf(because, becauseArgs)
.ForCondition(!string.IsNullOrWhiteSpace(content))
.FailWith("Expected HTTP response to have a non-empty body, but the body was empty.");
}
/// <summary>
/// Asserts that the HTTP response is successful (2xx) and that the response body, deserialized
/// to <typeparamref name="TBody"/>, satisfies the provided <paramref name="assertion"/>.
/// </summary>
/// <typeparam name="TBody">The type to deserialize the JSON response body into.</typeparam>
/// <param name="assertion">A callback that receives the deserialized body and performs further assertions.</param>
/// <param name="because">A reason to include in the failure message.</param>
/// <param name="becauseArgs">Format arguments for <paramref name="because"/>.</param>
/// <remarks>
/// Deserialization uses <see cref="DefaultJsonOptions"/>. The assertion fails immediately if
/// the status code is not 2xx — use <c>Satisfy<TBody></c> instead when you need to
/// assert on error responses that carry a JSON body (e.g. <c>ProblemDetails</c> on 400).
/// </remarks>
[CustomAssertion]
public async Task SucceedWith<TBody>(
Action<TBody> assertion,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
if (assertion is null)
{
throw new ArgumentNullException(nameof(assertion));
}
using HttpResponseMessage response = await Subject;
chain
.BecauseOf(because, becauseArgs)
.ForCondition(response.IsSuccessStatusCode)
.FailWith(
$"Expected HTTP response to be successful, but found {(int)response.StatusCode} ({response.ReasonPhrase})."
);
if (!CurrentAssertionChain.Succeeded)
{
return;
}
string content = await response.Content.ReadAsStringAsync();
chain
.BecauseOf(because, becauseArgs)
.ForCondition(!string.IsNullOrWhiteSpace(content))
.FailWith(
$"Expected HTTP response body to be deserializable to {typeof(TBody)}, but it was null."
);
if (!CurrentAssertionChain.Succeeded)
{
return;
}
string[] failuresFromInspector;
using (AssertionScope assertionScope = new())
{
TBody? body;
try
{
body = JsonSerializer.Deserialize<TBody>(content, DefaultJsonOptions);
}
catch (Exception e)
{
CurrentAssertionChain
.WithDefaultIdentifier(Identifier)
.WithExpectation(
$"Expected HTTP response content to be deserializable to \"{typeof(TBody).Name}\", but deserialization threw an exception:",
assertionChain => assertionChain.FailWith(e.ToString())
);
return;
}
assertion(body!);
failuresFromInspector = assertionScope.Discard();
}
if (failuresFromInspector.Length > 0)
{
string failureMessage =
Environment.NewLine + string.Join(Environment.NewLine, failuresFromInspector);
CurrentAssertionChain
.WithDefaultIdentifier(Identifier)
.WithExpectation(
"Expected {context:object} to match inspector, but the inspector was not satisfied:",
Subject,
assertionChain => assertionChain.FailWith(failureMessage)
);
}
}
/// <summary>
/// Deserializes the response body to <typeparamref name="TBody"/> regardless of the status
/// code, then runs <paramref name="assertion"/> on the result.
/// </summary>
/// <typeparam name="TBody">The type to deserialize the JSON response body into.</typeparam>
/// <param name="assertion">A callback that receives the deserialized body and performs further assertions.</param>
/// <param name="because">A reason to include in the failure message.</param>
/// <param name="becauseArgs">Format arguments for <paramref name="because"/>.</param>
/// <remarks>
/// Unlike <c>SucceedWith<TBody></c>, this overload does <b>not</b> require a 2xx status
/// code. Use it when testing endpoints that return a structured JSON body on error, such as
/// <c>ProblemDetails</c> on a 400 or 422 response.
/// </remarks>
/// <example>
/// <code>
/// await client.Post("/users", invalidData)
/// .Should()
/// .Satisfy<ProblemDetails>(problem => problem.Status.Should().Be(400));
/// </code>
/// </example>
[CustomAssertion]
public async Task Satisfy<TBody>(
Action<TBody> assertion,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
if (assertion is null)
{
throw new ArgumentNullException(nameof(assertion));
}
using HttpResponseMessage response = await Subject;
ReceivedHttpResponse receivedResponse = new()
{
StatusCode = response.StatusCode,
Content = await response.Content.ReadAsStringAsync(),
Headers =
[
.. response.Headers.Select(x => new KeyValuePair<string, string[]>(x.Key, [.. x.Value])),
],
};
// TODO: When 400 can deserialize problem response
chain
.BecauseOf(because, becauseArgs)
.ForCondition(!receivedResponse.IsEmpty())
.FailWith(
$"Expected HTTP response body to be deserializable to {typeof(TBody)}, but it was null."
);
if (CurrentAssertionChain.Succeeded)
{
string[] failuresFromInspector;
using (AssertionScope assertionScope = new())
{
TBody? body;
try
{
body = JsonSerializer.Deserialize<TBody>(receivedResponse.Content, DefaultJsonOptions);
}
catch (Exception e)
{
CurrentAssertionChain
.WithDefaultIdentifier(Identifier)
.WithExpectation(
$"Expected HTTP response content to be deserializable to \"{typeof(TBody).Name}\", but deserialization threw an exception:",
assertionChain => assertionChain.FailWith(e.ToString())
);
return;
}
assertion(body!);
failuresFromInspector = assertionScope.Discard();
}
if (failuresFromInspector.Length > 0)
{
string failureMessage =
Environment.NewLine + string.Join(Environment.NewLine, failuresFromInspector);
CurrentAssertionChain
.WithDefaultIdentifier(Identifier)
.WithExpectation(
"Expected {context:object} to match inspector, but the inspector was not satisfied:",
Subject,
assertionChain => assertionChain.FailWith(failureMessage)
);
}
}
}
/// <summary>
/// Asserts that the deserialized HTTP response body satisfies the provided asynchronous assertion.
/// </summary>
[CustomAssertion]
public async Task Satisfy<TBody>(
Func<TBody, Task> assertion,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
if (assertion is null)
{
throw new ArgumentNullException(nameof(assertion));
}
using HttpResponseMessage response = await Subject;
ReceivedHttpResponse receivedResponse = new()
{
StatusCode = response.StatusCode,
Content = await response.Content.ReadAsStringAsync(),
Headers =
[
.. response.Headers.Select(x => new KeyValuePair<string, string[]>(x.Key, [.. x.Value])),
],
};
chain
.BecauseOf(because, becauseArgs)
.ForCondition(!receivedResponse.IsEmpty())
.FailWith(
$"Expected HTTP response body to be deserializable to {typeof(TBody)}, but it was null."
);
if (CurrentAssertionChain.Succeeded)
{
string[] failuresFromInspector;
using (AssertionScope assertionScope = new())
{
TBody? body;
try
{
body = JsonSerializer.Deserialize<TBody>(receivedResponse.Content, DefaultJsonOptions);
}
catch (Exception e)
{
CurrentAssertionChain
.WithDefaultIdentifier(Identifier)
.WithExpectation(
$"Expected HTTP response content to be deserializable to \"{typeof(TBody).Name}\", but deserialization threw an exception:",
assertionChain => assertionChain.FailWith(e.ToString())
);
return;
}
await assertion(body!);
failuresFromInspector = assertionScope.Discard();
}
if (failuresFromInspector.Length > 0)
{
string failureMessage =
Environment.NewLine + string.Join(Environment.NewLine, failuresFromInspector);
CurrentAssertionChain
.WithDefaultIdentifier(Identifier)
.WithExpectation(
"Expected {context:object} to match inspector, but the inspector was not satisfied:",
Subject,
assertionChain => assertionChain.FailWith(failureMessage)
);
}
}
}
/// <summary>
/// Passes the raw <see cref="HttpResponseMessage"/> to <paramref name="assertion"/> for fully
/// custom, synchronous inspection of the response.
/// </summary>
/// <param name="assertion">
/// A callback that receives the awaited <see cref="HttpResponseMessage"/>. Use it to assert on
/// any combination of status code, headers, and body that the built-in methods do not cover.
/// </param>
/// <param name="because">A reason to include in the failure message.</param>
/// <param name="becauseArgs">Format arguments for <paramref name="because"/>.</param>
/// <example>
/// <code>
/// await client.Get("/data").Should().Satisfy(response =>
/// {
/// response.StatusCode.Should().Be(HttpStatusCode.OK);
/// response.Headers.ETag.Should().NotBeNull();
/// });
/// </code>
/// </example>
[CustomAssertion]
public async Task Satisfy(
Action<HttpResponseMessage> assertion,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
if (assertion is null)
{
throw new ArgumentNullException(nameof(assertion));
}
using HttpResponseMessage response = await Subject;
string[] failuresFromInspector;
using (AssertionScope assertionScope = new())
{
assertion(response);
failuresFromInspector = assertionScope.Discard();
}
if (failuresFromInspector.Length > 0)
{
string failureMessage =
Environment.NewLine + string.Join(Environment.NewLine, failuresFromInspector);
CurrentAssertionChain
.WithDefaultIdentifier(Identifier)
.WithExpectation(
"Expected {context:object} to match inspector, but the inspector was not satisfied:",
Subject,
assertionChain => assertionChain.FailWith(failureMessage)
);
}
}
/// <summary>
/// Passes the raw <see cref="HttpResponseMessage"/> to an asynchronous
/// <paramref name="assertion"/> for fully custom inspection of the response.
/// </summary>
/// <param name="assertion">
/// An async callback that receives the awaited <see cref="HttpResponseMessage"/>. Use this
/// overload when your assertion itself needs to <c>await</c>, for example to read the body
/// stream or call async helper methods.
/// </param>
/// <param name="because">A reason to include in the failure message.</param>
/// <param name="becauseArgs">Format arguments for <paramref name="because"/>.</param>
[CustomAssertion]
public async Task Satisfy(
Func<HttpResponseMessage, Task> assertion,
[StringSyntax("CompositeFormat")] string because = "",
params object[] becauseArgs
)
{
if (assertion is null)
{
throw new ArgumentNullException(nameof(assertion));
}
using HttpResponseMessage response = await Subject;
string[] failuresFromInspector;
using (AssertionScope assertionScope = new())
{
await assertion(response);
failuresFromInspector = assertionScope.Discard();
}
if (failuresFromInspector.Length > 0)
{
string failureMessage =
Environment.NewLine + string.Join(Environment.NewLine, failuresFromInspector);
CurrentAssertionChain
.WithDefaultIdentifier(Identifier)
.WithExpectation(
"Expected {context:object} to match inspector, but the inspector was not satisfied:",
Subject,
assertionChain => assertionChain.FailWith(failureMessage)
);
}
}
private static void ThrowIfNull(object? value, string parameterName)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(value, parameterName);
#else
if (value is null)
{
throw new ArgumentNullException(parameterName);
}
#endif
}
private static bool ContainsHeader(HttpResponseMessage response, string headerName)
{
return ContainsHeader(response.Headers, headerName)
|| (response.Content is not null && ContainsHeader(response.Content.Headers, headerName));
}
private static bool ContainsHeader(HttpHeaders headers, string headerName)
{
try
{
return headers.Contains(headerName);
}
catch (InvalidOperationException)
{
return false;
}
}
private static string[] GetHeaderValues(HttpResponseMessage response, string headerName)
{
string[] responseHeaderValues = GetHeaderValues(response.Headers, headerName);
string[] contentHeaderValues = response.Content is not null
? GetHeaderValues(response.Content.Headers, headerName)
: [];
return [.. responseHeaderValues, .. contentHeaderValues];
}
private static string[] GetHeaderValues(HttpHeaders headers, string headerName)
{
try
{
return headers.TryGetValues(headerName, out IEnumerable<string>? values) ? [.. values] : [];
}
catch (InvalidOperationException)
{
return [];
}
}
}