-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWireMockFixture.cs
More file actions
524 lines (489 loc) · 19.8 KB
/
WireMockFixture.cs
File metadata and controls
524 lines (489 loc) · 19.8 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
using WireMock.Admin.Requests;
using WireMock.Logging;
using WireMock.Server;
using WireMock.Settings;
namespace MeAjudaAi.Integration.Tests.Infrastructure;
/// <summary>
/// Fixture for WireMock HTTP server used to mock external APIs in integration tests.
/// Provides stubs for ViaCep, BrasilApi, OpenCep, Nominatim, and IBGE APIs.
/// </summary>
public class WireMockFixture : IAsyncDisposable
{
private WireMockServer? _server;
/// <summary>
/// Gets the WireMock server instance.
/// </summary>
public WireMockServer Server => _server ?? throw new InvalidOperationException("WireMock server not started. Call StartAsync() first.");
/// <summary>
/// Gets the base URL for the mock server.
/// </summary>
public string BaseUrl => Server.Url!;
/// <summary>
/// Starts the WireMock server and configures all API stubs.
/// </summary>
public Task StartAsync()
{
_server = WireMockServer.Start(new WireMockServerSettings
{
Port = 0, // Use dynamic port to avoid conflicts in parallel test execution
StartAdminInterface = true,
ReadStaticMappings = false,
WatchStaticMappings = false,
Logger = new WireMockConsoleLogger()
});
// Configure all API stubs
ConfigureIbgeStubs();
ConfigureViaCepStubs();
ConfigureBrasilApiStubs();
ConfigureOpenCepStubs();
ConfigureNominatimStubs();
return Task.CompletedTask;
}
/// <summary>
/// Configures IBGE Localidades API stubs.
/// </summary>
private void ConfigureIbgeStubs()
{
// Search by city name: Muriaé/MG - IBGE code: 3143906
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios")
.WithParam("nome", "muriaé")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
[{
"id": 3143906,
"nome": "Muriaé",
"microrregiao": {
"id": 31054,
"nome": "Muriaé",
"mesorregiao": {
"id": 3107,
"nome": "Zona da Mata",
"UF": {
"id": 31,
"sigla": "MG",
"nome": "Minas Gerais",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
}
}
}
}]
"""));
// Search by city name: Itaperuna/RJ - IBGE code: 3302205
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios")
.WithParam("nome", "itaperuna")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
[{
"id": 3302205,
"nome": "Itaperuna",
"microrregiao": {
"id": 33005,
"nome": "Itaperuna",
"mesorregiao": {
"id": 3301,
"nome": "Noroeste Fluminense",
"UF": {
"id": 33,
"sigla": "RJ",
"nome": "Rio de Janeiro",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
}
}
}
}]
"""));
// Get city by ID: Muriaé/MG
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios/3143906")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
{
"id": 3143906,
"nome": "Muriaé",
"microrregiao": {
"id": 31054,
"nome": "Muriaé",
"mesorregiao": {
"id": 3107,
"nome": "Zona da Mata",
"UF": {
"id": 31,
"sigla": "MG",
"nome": "Minas Gerais",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
}
}
}
}
"""));
// Get all states (UFs)
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/estados")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
[
{
"id": 31,
"sigla": "MG",
"nome": "Minas Gerais",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
},
{
"id": 33,
"sigla": "RJ",
"nome": "Rio de Janeiro",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
},
{
"id": 35,
"sigla": "SP",
"nome": "São Paulo",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
}
]
"""));
// Get state by ID: MG
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/estados/31")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
{
"id": 31,
"sigla": "MG",
"nome": "Minas Gerais",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
}
"""));
// Get state by UF: MG
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/estados/MG")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
{
"id": 31,
"sigla": "MG",
"nome": "Minas Gerais",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
}
"""));
// Search by state: SP
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/estados/SP/municipios")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
[{
"id": 3550308,
"nome": "São Paulo",
"microrregiao": {
"id": 35061,
"nome": "São Paulo",
"mesorregiao": {
"id": 3515,
"nome": "Metropolitana de São Paulo",
"UF": {
"id": 35,
"sigla": "SP",
"nome": "São Paulo",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
}
}
}
}]
"""));
// Invalid city ID - 404
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios/9999999")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(404)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("[]"));
// Invalid state ID - 404
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/estados/999")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(404)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("[]"));
// Unknown city - empty array response
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios")
.WithParam("nome", "CidadeInexistente")
.WithParam("orderBy", "nome")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("[]"));
// Special characters handling: São Paulo
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios")
.WithParam("nome", "são paulo")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
[{
"id": 3550308,
"nome": "São Paulo",
"microrregiao": {
"id": 35061,
"nome": "São Paulo",
"mesorregiao": {
"id": 3515,
"nome": "Metropolitana de São Paulo",
"UF": {
"id": 35,
"sigla": "SP",
"nome": "São Paulo",
"regiao": { "id": 3, "sigla": "SE", "nome": "Sudeste" }
}
}
}
}]
"""));
// Catch-all for unknown cities - return empty array (200 status, not 404)
// This allows IbgeClient to return null instead of throwing exception
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios")
.WithParam("nome") // Match any nome parameter
.UsingGet())
.AtPriority(100) // Lower priority so specific stubs match first
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("[]"));
// Service unavailability simulation - 500 error
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios/unavailable")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(500)
.WithHeader("Content-Type", "text/plain")
.WithBody("Internal Server Error"));
// Timeout simulation - delay 30 seconds (exceeds typical HTTP client timeout)
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios/timeout")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("[]")
.WithDelay(TimeSpan.FromSeconds(30)));
// Malformed response simulation - invalid JSON
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/v1/localidades/municipios/malformed")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("{invalid json"));
}
/// <summary>
/// Configures ViaCep API stubs.
/// </summary>
private void ConfigureViaCepStubs()
{
// CEP 01310-100 - Avenida Paulista, São Paulo/SP
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/ws/01310100/json/")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
{
"cep": "01310-100",
"logradouro": "Avenida Paulista",
"complemento": "lado ímpar",
"bairro": "Bela Vista",
"localidade": "São Paulo",
"uf": "SP",
"erro": false
}
"""));
// CEP inválido - erro
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/ws/00000000/json/")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
{
"erro": true
}
"""));
}
/// <summary>
/// Configures BrasilApi CEP stubs.
/// </summary>
private void ConfigureBrasilApiStubs()
{
// CEP 01310-100 - Avenida Paulista, São Paulo/SP
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/api/cep/v2/01310100")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
{
"cep": "01310100",
"state": "SP",
"city": "São Paulo",
"neighborhood": "Bela Vista",
"street": "Avenida Paulista",
"service": "viacep"
}
"""));
}
/// <summary>
/// Configures OpenCep API stubs.
/// </summary>
private void ConfigureOpenCepStubs()
{
// CEP 01310-100 - Avenida Paulista, São Paulo/SP
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/v1/01310100")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
{
"cep": "01310-100",
"logradouro": "Avenida Paulista",
"complemento": "lado ímpar",
"bairro": "Bela Vista",
"localidade": "São Paulo",
"uf": "SP",
"ibge": "3550308"
}
"""));
}
/// <summary>
/// Configures Nominatim geocoding API stubs.
/// </summary>
private void ConfigureNominatimStubs()
{
// São Paulo search
Server
.Given(WireMock.RequestBuilders.Request.Create()
.WithPath("/search")
.WithParam("q", "São Paulo, Brasil")
.WithParam("format", "json")
.UsingGet())
.RespondWith(WireMock.ResponseBuilders.Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithBody("""
{
"address": {
"city": "São Paulo",
"state": "São Paulo",
"country": "Brasil",
"country_code": "br"
},
"display_name": "São Paulo, Brasil"
}
"""));
}
/// <summary>
/// Resets all configured stubs and request logs.
/// </summary>
public void Reset()
{
Server.Reset();
ConfigureIbgeStubs();
ConfigureViaCepStubs();
ConfigureBrasilApiStubs();
ConfigureOpenCepStubs();
ConfigureNominatimStubs();
}
/// <summary>
/// Disposes the WireMock server.
/// </summary>
public ValueTask DisposeAsync()
{
_server?.Stop();
_server?.Dispose();
_server = null;
GC.SuppressFinalize(this);
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Console logger for WireMock server.
/// </summary>
internal class WireMockConsoleLogger : IWireMockLogger
{
public void Debug(string formatString, params object[] args)
{
// Suppress debug logs to reduce noise
}
public void Info(string formatString, params object[] args)
{
Console.WriteLine($"[WireMock INFO] {string.Format(formatString, args)}");
}
public void Warn(string formatString, params object[] args)
{
Console.WriteLine($"[WireMock WARN] {string.Format(formatString, args)}");
}
public void Error(string formatString, params object[] args)
{
Console.WriteLine($"[WireMock ERROR] {string.Format(formatString, args)}");
}
public void Error(string formatString, Exception exception)
{
Console.WriteLine($"[WireMock ERROR] {formatString} - {exception}");
}
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest)
{
// Suppress request/response logs to reduce noise
}
}