-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathRuntimeHelpersTests.fs
More file actions
529 lines (420 loc) · 20.1 KB
/
RuntimeHelpersTests.fs
File metadata and controls
529 lines (420 loc) · 20.1 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
namespace SwaggerProvider.Tests.RuntimeHelpersTests
open System
open System.IO
open System.Net
open System.Net.Http
open System.Text.Json
open System.Threading
open System.Threading.Tasks
open Xunit
open FsUnitTyped
open Swagger.Internal.RuntimeHelpers
/// Unit tests for RuntimeHelpers — the runtime parameter serialization and HTTP utilities.
/// These functions are used by every generated API client but previously had no dedicated tests.
module ToParamTests =
[<Fact>]
let ``toParam formats DateTime as ISO 8601 round-trip``() =
let dt = DateTime(2024, 6, 15, 10, 30, 0, DateTimeKind.Utc)
let result = toParam(box dt)
result |> shouldEqual(dt.ToString("O"))
[<Fact>]
let ``toParam formats DateTimeOffset as ISO 8601 round-trip``() =
let dto = DateTimeOffset(2024, 6, 15, 10, 30, 0, TimeSpan.FromHours(2.0))
let result = toParam(box dto)
result |> shouldEqual(dto.ToString("O"))
[<Fact>]
let ``toParam returns null for null input``() =
let result = toParam null
result |> shouldEqual null
[<Fact>]
let ``toParam uses ToString for integers``() =
let result = toParam(box 42)
result |> shouldEqual "42"
[<Fact>]
let ``toParam uses ToString for strings``() =
let result = toParam(box "hello world")
result |> shouldEqual "hello world"
[<Fact>]
let ``toParam uses ToString for Guid``() =
let g = Guid("d3b07384-d9a2-4e3f-9a4b-1234567890ab")
let result = toParam(box g)
result |> shouldEqual(g.ToString())
[<Fact>]
let ``toParam unwraps Some(Guid) — fixes issue #140``() =
let g = Guid("d3b07384-d9a2-4e3f-9a4b-1234567890ab")
let result = toParam(box(Some g))
result |> shouldEqual(g.ToString())
[<Fact>]
let ``toParam returns null for None(Guid) — fixes issue #140``() =
let result = toParam(box(None: Guid option))
result |> shouldEqual null
[<Fact>]
let ``toParam unwraps Some(string)``() =
let result = toParam(box(Some "token-value"))
result |> shouldEqual "token-value"
[<Fact>]
let ``toParam returns null for None(string)``() =
let result = toParam(box(None: string option))
result |> shouldEqual null
[<Fact>]
let ``toParam unwraps Some(DateTimeOffset) and formats as ISO 8601``() =
let dto = DateTimeOffset(2024, 1, 15, 12, 0, 0, TimeSpan.Zero)
let result = toParam(box(Some dto))
result |> shouldEqual(dto.ToString("O"))
module ToQueryParamsTests =
let private stubClient =
{ new Swagger.ProvidedApiClientBase(null, JsonSerializerOptions()) with
override _.Serialize(v) =
JsonSerializer.Serialize v
override _.Deserialize(s, t) =
JsonSerializer.Deserialize(s, t) }
[<Fact>]
let ``toQueryParams handles string array``() =
let result = toQueryParams "tag" (box [| "alpha"; "beta"; "gamma" |]) stubClient
result
|> shouldEqual [ ("tag", "alpha"); ("tag", "beta"); ("tag", "gamma") ]
[<Fact>]
let ``toQueryParams handles int32 array``() =
let result = toQueryParams "id" (box [| 1; 2; 3 |]) stubClient
result |> shouldEqual [ ("id", "1"); ("id", "2"); ("id", "3") ]
[<Fact>]
let ``toQueryParams handles int64 array``() =
let result = toQueryParams "id" (box [| 1L; 2L; 3L |]) stubClient
result |> shouldEqual [ ("id", "1"); ("id", "2"); ("id", "3") ]
[<Fact>]
let ``toQueryParams handles bool array``() =
let result = toQueryParams "flag" (box [| true; false |]) stubClient
result |> shouldEqual [ ("flag", "True"); ("flag", "False") ]
[<Fact>]
let ``toQueryParams formats DateTime array as ISO 8601``() =
let dt = DateTime(2024, 1, 15, 12, 0, 0, DateTimeKind.Utc)
let result = toQueryParams "d" (box [| dt |]) stubClient
result |> shouldHaveLength 1
fst result[0] |> shouldEqual "d"
snd result[0] |> shouldEqual(dt.ToString("O"))
[<Fact>]
let ``toQueryParams formats DateTimeOffset array as ISO 8601``() =
let dto = DateTimeOffset(2024, 1, 15, 12, 0, 0, TimeSpan.Zero)
let result = toQueryParams "d" (box [| dto |]) stubClient
result |> shouldHaveLength 1
snd result[0] |> shouldEqual(dto.ToString("O"))
[<Fact>]
let ``toQueryParams handles Option<string> Some``() =
let result = toQueryParams "q" (box(Some "hello")) stubClient
result |> shouldEqual [ ("q", "hello") ]
[<Fact>]
let ``toQueryParams handles Option<string> None``() =
let result = toQueryParams "q" (box(Option<string>.None)) stubClient
result |> shouldEqual []
[<Fact>]
let ``toQueryParams handles Option<int32> Some``() =
let result = toQueryParams "n" (box(Some 99)) stubClient
result |> shouldEqual [ ("n", "99") ]
[<Fact>]
let ``toQueryParams handles Option<int32> None``() =
let result = toQueryParams "n" (box(Option<int>.None)) stubClient
result |> shouldEqual []
[<Fact>]
let ``toQueryParams handles Option<DateTime> Some as ISO 8601``() =
let dt = DateTime(2024, 3, 1, 0, 0, 0, DateTimeKind.Utc)
let result = toQueryParams "d" (box(Some dt)) stubClient
result |> shouldHaveLength 1
snd result[0] |> shouldEqual(dt.ToString("O"))
[<Fact>]
let ``toQueryParams handles Option<DateTime> None``() =
let result = toQueryParams "d" (box(Option<DateTime>.None)) stubClient
result |> shouldEqual []
[<Fact>]
let ``toQueryParams handles Option<Guid> Some``() =
let g = Guid.NewGuid()
let result = toQueryParams "id" (box(Some g)) stubClient
result |> shouldEqual [ ("id", g.ToString()) ]
[<Fact>]
let ``toQueryParams handles plain DateTime as ISO 8601``() =
let dt = DateTime(2024, 6, 1, 8, 0, 0, DateTimeKind.Utc)
let result = toQueryParams "dt" (box dt) stubClient
result |> shouldHaveLength 1
snd result[0] |> shouldEqual(dt.ToString("O"))
[<Fact>]
let ``toQueryParams handles plain DateTimeOffset as ISO 8601``() =
let dto = DateTimeOffset(2024, 6, 1, 8, 0, 0, TimeSpan.FromHours(-5.0))
let result = toQueryParams "dto" (box dto) stubClient
result |> shouldHaveLength 1
snd result[0] |> shouldEqual(dto.ToString("O"))
[<Fact>]
let ``toQueryParams handles plain string``() =
let result = toQueryParams "q" (box "search term") stubClient
result |> shouldEqual [ ("q", "search term") ]
[<Fact>]
let ``toQueryParams returns empty list for null input (treated as Option None)``() =
// In F#, None for any option type is compiled as null at the .NET level,
// so a null obj is treated as Option None and returns an empty list.
let result = toQueryParams "q" null stubClient
result |> shouldEqual []
[<Fact>]
let ``toQueryParams skips None items in Option array``() =
let values: Option<int>[] = [| Some 1; None; Some 3 |]
let result = toQueryParams "n" (box values) stubClient
result |> shouldEqual [ ("n", "1"); ("n", "3") ]
[<Fact>]
let ``toQueryParams handles Guid array``() =
let g1 = Guid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
let g2 = Guid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")
let result = toQueryParams "id" (box [| g1; g2 |]) stubClient
result |> shouldEqual [ ("id", g1.ToString()); ("id", g2.ToString()) ]
[<Fact>]
let ``toQueryParams handles float32 array``() =
let result = toQueryParams "v" (box [| 1.5f; 2.5f |]) stubClient
result |> shouldEqual [ ("v", "1.5"); ("v", "2.5") ]
[<Fact>]
let ``toQueryParams handles double array``() =
let result = toQueryParams "v" (box [| 1.5; 2.5 |]) stubClient
result |> shouldEqual [ ("v", "1.5"); ("v", "2.5") ]
[<Fact>]
let ``toQueryParams handles byte array as base64``() =
// byte[] is serialized via client.Serialize (JSON base64) with surrounding quotes trimmed
let bytes = [| 72uy; 101uy; 108uy; 108uy; 111uy |] // "Hello" in ASCII
let expected = (JsonSerializer.Serialize bytes).Trim('"')
let result = toQueryParams "data" (box bytes) stubClient
result |> shouldEqual [ ("data", expected) ]
[<Fact>]
let ``toQueryParams skips None items in Option<string> array``() =
let values: Option<string>[] = [| Some "a"; None; Some "c" |]
let result = toQueryParams "q" (box values) stubClient
result |> shouldEqual [ ("q", "a"); ("q", "c") ]
[<Fact>]
let ``toQueryParams skips None items in Option<float32> array``() =
let values: Option<float32>[] = [| Some 1.5f; None; Some 3.5f |]
let result = toQueryParams "v" (box values) stubClient
result |> shouldEqual [ ("v", "1.5"); ("v", "3.5") ]
[<Fact>]
let ``toQueryParams skips None items in Option<double> array``() =
let values: Option<double>[] = [| Some 1.5; None; Some 3.5 |]
let result = toQueryParams "v" (box values) stubClient
result |> shouldEqual [ ("v", "1.5"); ("v", "3.5") ]
module CombineUrlTests =
[<Fact>]
let ``combineUrl joins paths without extra slashes``() =
combineUrl "http://example.com/api" "v1/users"
|> shouldEqual "http://example.com/api/v1/users"
[<Fact>]
let ``combineUrl trims trailing slash from left``() =
combineUrl "http://example.com/api/" "v1/users"
|> shouldEqual "http://example.com/api/v1/users"
[<Fact>]
let ``combineUrl trims leading slash from right``() =
combineUrl "http://example.com/api" "/v1/users"
|> shouldEqual "http://example.com/api/v1/users"
[<Fact>]
let ``combineUrl trims both slashes``() =
combineUrl "http://example.com/api/" "/v1/users"
|> shouldEqual "http://example.com/api/v1/users"
[<Fact>]
let ``combineUrl works with empty path segment``() =
combineUrl "http://example.com" ""
|> shouldEqual "http://example.com/"
module CreateHttpRequestTests =
[<Fact>]
let ``createHttpRequest creates GET request``() =
use req = createHttpRequest "GET" "v1/users" []
req.Method |> shouldEqual HttpMethod.Get
[<Fact>]
let ``createHttpRequest creates POST request``() =
use req = createHttpRequest "POST" "v1/users" []
req.Method |> shouldEqual HttpMethod.Post
[<Fact>]
let ``createHttpRequest creates DELETE request``() =
use req = createHttpRequest "DELETE" "v1/users/42" []
req.Method |> shouldEqual HttpMethod.Delete
[<Fact>]
let ``createHttpRequest is case-insensitive for method``() =
use req = createHttpRequest "get" "v1/users" []
req.Method |> shouldEqual HttpMethod.Get
[<Fact>]
let ``createHttpRequest appends query parameters``() =
use req = createHttpRequest "GET" "v1/users" [ ("page", "2"); ("size", "10") ]
let uri = req.RequestUri.ToString()
uri |> shouldContainText "page=2"
uri |> shouldContainText "size=10"
[<Fact>]
let ``createHttpRequest skips null query parameter values``() =
use req = createHttpRequest "GET" "v1/users" [ ("q", null) ]
let uri = req.RequestUri.ToString()
uri |> shouldNotContainText "q="
[<Fact>]
let ``createHttpRequest includes path in request URI``() =
use req = createHttpRequest "GET" "v1/pets/42" []
req.RequestUri.ToString() |> shouldContainText "v1/pets/42"
module FillHeadersTests =
[<Fact>]
let ``fillHeaders adds standard headers``() =
use req = new HttpRequestMessage(HttpMethod.Get, "http://example.com/")
fillHeaders req [ ("Accept", "application/json"); ("X-Api-Key", "secret") ]
req.Headers.Contains("Accept") |> shouldEqual true
req.Headers.Contains("X-Api-Key") |> shouldEqual true
[<Fact>]
let ``fillHeaders skips null-value headers``() =
use req = new HttpRequestMessage(HttpMethod.Get, "http://example.com/")
fillHeaders req [ ("X-Missing", null) ]
req.Headers.Contains("X-Missing") |> shouldEqual false
[<Fact>]
let ``fillHeaders silently ignores Content-Type header``() =
// Content-Type must be set on HttpContent, not on the request; this should not throw
use req = new HttpRequestMessage(HttpMethod.Get, "http://example.com/")
// Should not raise an exception even though Content-Type cannot be added to request headers
fillHeaders req [ ("Content-Type", "application/json") ]
module ToContentTests =
[<Fact>]
let ``toStringContent returns JSON content type``() =
use c = toStringContent "{\"key\":\"value\"}"
c.Headers.ContentType.MediaType |> shouldEqual "application/json"
[<Fact>]
let ``toStringContent preserves the body``() =
let body = "{\"name\":\"Alice\"}"
use c = toStringContent body
let text = c.ReadAsStringAsync() |> Async.AwaitTask |> Async.RunSynchronously
text |> shouldEqual body
[<Fact>]
let ``toTextContent returns text/plain content type``() =
use c = toTextContent "hello"
c.Headers.ContentType.MediaType |> shouldEqual "text/plain"
[<Fact>]
let ``toStreamContent sets provided content type``() =
use stream = new MemoryStream([| 1uy; 2uy; 3uy |])
use c = toStreamContent(box stream, "application/octet-stream")
c.Headers.ContentType.MediaType
|> shouldEqual "application/octet-stream"
[<Fact>]
let ``toStreamContent omits content type when empty``() =
use stream = new MemoryStream([| 1uy; 2uy |])
use c = toStreamContent(box stream, "")
c.Headers.ContentType |> shouldEqual null
[<Fact>]
let ``toStreamContent throws for non-stream input``() =
Assert.Throws<Exception>(fun () -> toStreamContent(box "not a stream", "application/json") |> ignore)
|> ignore
/// A stub HttpMessageHandler that always returns a fixed status code and body.
type private StubHttpMessageHandler(statusCode: HttpStatusCode, responseBody: string) =
inherit HttpMessageHandler()
override _.SendAsync(_request: HttpRequestMessage, cancellationToken: CancellationToken) =
cancellationToken.ThrowIfCancellationRequested()
let response = new HttpResponseMessage(statusCode)
response.Content <- new StringContent(responseBody)
Task.FromResult(response)
module OpenApiExceptionTests =
let private makeClient(handler: HttpMessageHandler) =
let httpClient = new HttpClient(handler)
httpClient.BaseAddress <- Uri("http://stub/")
{ new Swagger.ProvidedApiClientBase(httpClient, JsonSerializerOptions()) with
override _.Serialize(v) =
JsonSerializer.Serialize v
override _.Deserialize(s, t) =
JsonSerializer.Deserialize(s, t) }
[<Fact>]
let ``OpenApiException message includes description when no body``() =
use content = new StringContent("")
use response = new HttpResponseMessage(HttpStatusCode.NotFound)
let ex = Swagger.OpenApiException(404, "Not Found", response.Headers, content)
ex.Message |> shouldEqual "Not Found"
[<Fact>]
let ``OpenApiException message includes body when body is provided``() =
use content = new StringContent("{\"error\":\"missing\"}")
use response = new HttpResponseMessage(HttpStatusCode.NotFound)
let ex =
Swagger.OpenApiException(404, "Not Found", response.Headers, content, "{\"error\":\"missing\"}")
ex.Message |> shouldContainText "Not Found"
ex.Message |> shouldContainText "{\"error\":\"missing\"}"
[<Fact>]
let ``OpenApiException ResponseBody is empty string when not provided``() =
use content = new StringContent("")
use response = new HttpResponseMessage(HttpStatusCode.BadRequest)
let ex = Swagger.OpenApiException(400, "Bad Request", response.Headers, content)
ex.ResponseBody |> shouldEqual ""
[<Fact>]
let ``OpenApiException ResponseBody returns the provided body``() =
use content = new StringContent("error detail")
use response = new HttpResponseMessage(HttpStatusCode.UnprocessableEntity)
let ex =
Swagger.OpenApiException(422, "Unprocessable Entity", response.Headers, content, "error detail")
ex.ResponseBody |> shouldEqual "error detail"
[<Fact>]
let ``OpenApiException message is only description when body is empty string``() =
use content = new StringContent("")
use response = new HttpResponseMessage(HttpStatusCode.Forbidden)
let ex = Swagger.OpenApiException(403, "Forbidden", response.Headers, content, "")
ex.Message |> shouldEqual "Forbidden"
[<Fact>]
let ``CallAsync raises OpenApiException with response body for documented error code``() =
task {
let expectedBody = "{\"message\":\"pet not found\"}"
use handler = new StubHttpMessageHandler(HttpStatusCode.NotFound, expectedBody)
let client = makeClient handler
use request = new HttpRequestMessage(HttpMethod.Get, "http://stub/pets/1")
let! ex =
Assert.ThrowsAsync<Swagger.OpenApiException>(fun () ->
task {
let! _ = client.CallAsync(request, [| "404" |], [| "Pet not found" |])
()
})
ex.StatusCode |> shouldEqual 404
ex.ResponseBody |> shouldEqual expectedBody
ex.Message |> shouldContainText "Pet not found"
ex.Message |> shouldContainText expectedBody
}
[<Fact>]
let ``CallAsync raises OpenApiException without body text when body is empty``() =
task {
use handler = new StubHttpMessageHandler(HttpStatusCode.NotFound, "")
let client = makeClient handler
use request = new HttpRequestMessage(HttpMethod.Get, "http://stub/pets/1")
let! ex =
Assert.ThrowsAsync<Swagger.OpenApiException>(fun () ->
task {
let! _ = client.CallAsync(request, [| "404" |], [| "Pet not found" |])
()
})
ex.StatusCode |> shouldEqual 404
ex.Message |> shouldEqual "Pet not found"
}
[<Fact>]
let ``CallAsync raises HttpRequestException for undocumented error code``() =
task {
use handler =
new StubHttpMessageHandler(HttpStatusCode.InternalServerError, "server error")
let client = makeClient handler
use request = new HttpRequestMessage(HttpMethod.Get, "http://stub/pets/1")
// 500 is not in the documented error codes, so HttpRequestException should be raised
let! _ =
Assert.ThrowsAsync<HttpRequestException>(fun () ->
task {
let! _ = client.CallAsync(request, [| "404" |], [| "Pet not found" |])
()
})
()
}
[<Fact>]
let ``CallAsync with CancellationToken returns content on success``() =
task {
use handler = new StubHttpMessageHandler(HttpStatusCode.OK, "result")
let client = makeClient handler
use request = new HttpRequestMessage(HttpMethod.Get, "http://stub/pets/1")
let! content = client.CallAsync(request, [||], [||], CancellationToken.None)
let! body = content.ReadAsStringAsync()
body |> shouldEqual "result"
}
[<Fact>]
let ``CallAsync with already-cancelled token raises OperationCanceledException``() =
task {
use cts = new CancellationTokenSource()
cts.Cancel()
use handler = new StubHttpMessageHandler(HttpStatusCode.OK, "ok")
let client = makeClient handler
use request = new HttpRequestMessage(HttpMethod.Get, "http://stub/pets/1")
let! _ =
Assert.ThrowsAnyAsync<OperationCanceledException>(fun () ->
task {
let! _ = client.CallAsync(request, [||], [||], cts.Token)
()
})
()
}