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
|
/**
* Integration tests.
*
* These bring up a real HTTP server on loopback and point the client at it via
* $(D ClientConfig.baseUrl). No test touches the network and no test fakes the
* HTTP layer: the code path exercised is the one that runs in production,
* request construction and error body reading included.
*
* It doubles as the test that $(D baseUrl) works — if it did not, none of this
* would run.
*
* The fixture field names stay Portuguese because they mirror the API's JSON.
*/
module cepis_test;
import core.sync.mutex : Mutex;
import core.thread : Thread;
import core.time : Duration, MonoTime, dur;
import std.algorithm : canFind, filter, map, startsWith;
import std.array : array, join;
import std.conv : to;
import std.exception : assertThrown;
import std.format : format;
import std.socket : InternetAddress, Socket, SocketOption, SocketOptionLevel,
SocketShutdown, TcpSocket;
import std.string : indexOf, split, toLower;
import std.typecons : Nullable, nullable;
import cepis;
private enum string SE_ADDRESS = `{
"cep": "01001000", "logradouro": "Praça da Sé", "complemento": "lado ímpar",
"unidade": "", "bairro": "Sé", "localidade": "São Paulo", "uf": "SP",
"estado": "São Paulo", "regiao": "Sudeste", "ibge": "3550308", "gia": "1004",
"ddd": "11", "siafi": "7107"
}`;
/**
* A 404 that knows which municipality the CEP would have belonged to.
*
* `25845000` is the DNE's own start for Areal and does not exist; the smallest
* one that does is `25845001`. Fixed here rather than fetched: production does
* not serve `faixa` yet, so a live call would pass for the wrong reason.
*/
private enum string AREAL_NOT_FOUND = `{
"erro": "cep_nao_encontrado", "mensagem": "CEP não existe na base do DNE",
"faixa": {
"localidade": "Areal", "uf": "RJ", "estado": "Rio de Janeiro",
"regiao": "Sudeste", "ibge": "3300225", "cep_ini": "25845001",
"cep_fim": "25849899", "ceps": 118
}
}`;
private enum string CSV_HEADER = "cep,logradouro,complemento,unidade,bairro,localidade,uf,"
~ "estado,regiao,ibge,gia,ddd,siafi";
private enum string SE_ROW = "01001000,Praça da Sé,lado ímpar,,Sé,São Paulo,SP,São Paulo,Sudeste,3550308,1004,11,7107";
private enum string RJ_ROW = "20040020,Avenida Rio Branco,,,Centro,Rio de Janeiro,RJ,"
~ "Rio de Janeiro,Sudeste,3304557,,21,6001";
private enum string MISSING_ROW = "99999999,,,,,,,,,,,,";
/// One canned response: status, body and extra headers.
private struct Reply
{
ushort status;
string content;
string[2][] headers;
}
/**
* A throwaway HTTP server on a random loopback port.
*
* Routes are matched by longest prefix, so `/csv` catches `/csv?ceps=...`. A
* route may hold several replies: each request consumes the next one, which is
* how retrying is tested, and the last one repeats once the list runs out.
*
* The accept loop runs on a daemon thread that ends with the test process;
* nothing here outlives `dub test`.
*/
private final class TestServer
{
private Socket listener;
private Mutex lock;
private Reply[][string] routes;
private string[] calls;
private string[][] headers;
private ushort port;
this()
{
lock = new Mutex();
listener = new TcpSocket();
listener.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true);
listener.bind(new InternetAddress("127.0.0.1", 0));
listener.listen(32);
port = listener.localAddress.toPortString.to!ushort;
auto worker = new Thread(&run);
worker.isDaemon = true;
worker.start();
}
string url() const
{
return "http://127.0.0.1:" ~ port.to!string;
}
Client client(uint maxAttempts = 3)
{
ClientConfig config;
config.baseUrl = url;
config.timeout = dur!"seconds"(5);
config.backoffBase = dur!"msecs"(1);
config.backoffMax = dur!"msecs"(10);
config.maxAttempts = maxAttempts;
return Client(config);
}
void respond(string path, Reply[] replies...)
{
synchronized (lock)
routes[path] = replies.dup;
}
size_t calledTimes()
{
synchronized (lock)
return calls.length;
}
size_t calledTimes(string prefix)
{
synchronized (lock)
return calls.filter!(c => c.startsWith(prefix)).array.length;
}
string[] lastHeaders()
{
synchronized (lock)
return headers.length ? headers[$ - 1].dup : null;
}
private void run()
{
while (true)
{
Socket peer;
try
peer = listener.accept();
catch (Exception)
return;
try
serve(peer);
catch (Exception)
{
}
try
{
peer.shutdown(SocketShutdown.BOTH);
peer.close();
}
catch (Exception)
{
}
}
}
private void serve(Socket peer)
{
char[] request;
ubyte[4096] buffer;
while (request.indexOf("\r\n\r\n") < 0)
{
const received = peer.receive(buffer[]);
if (received <= 0)
break;
request ~= cast(char[]) buffer[0 .. received];
}
auto lines = request.idup.split("\r\n");
if (lines.length == 0)
return;
auto fields = lines[0].split(" ");
const path = fields.length > 1 ? fields[1] : "/";
Reply reply;
synchronized (lock)
{
calls ~= path;
headers ~= lines.length > 1 ? lines[1 .. $].dup : null;
string best;
bool matched;
foreach (route; routes.byKey)
if (path.startsWith(route) && (!matched || route.length > best.length))
{
best = route;
matched = true;
}
if (!matched)
reply = Reply(404, `{"erro":"cep_nao_encontrado"}`);
else
{
auto replies = best in routes;
reply = (*replies)[0];
if (replies.length > 1)
*replies = (*replies)[1 .. $];
}
}
auto head = format!"HTTP/1.1 %d Status\r\n"(reply.status);
foreach (header; reply.headers)
head ~= header[0] ~ ": " ~ header[1] ~ "\r\n";
head ~= format!"Content-Length: %d\r\nConnection: close\r\n\r\n"(reply.content.length);
sendAll(peer, head);
sendAll(peer, reply.content);
}
private static void sendAll(Socket peer, const(void)[] data)
{
while (data.length > 0)
{
const sent = peer.send(data);
if (sent <= 0)
return;
data = data[sent .. $];
}
}
}
private string csvBody(string[] rows...)
{
return CSV_HEADER ~ "\n" ~ rows.join("\n") ~ "\n";
}
private string withGeo(string precisao, long raio_m)
{
enum string template_ = `{"cep":"01310100","logradouro":"Avenida Paulista","complemento":"",`
~ `"unidade":"","bairro":"Bela Vista","localidade":"São Paulo","uf":"SP",`
~ `"estado":"São Paulo","regiao":"Sudeste","ibge":"3550308","gia":"1004",`
~ `"ddd":"11","siafi":"7107","geo":{"lat":-23.5,"lon":-46.6,"raio_m":%d,`
~ `"precisao":"%s"}}`;
return format!template_(raio_m, precisao);
}
@("a successful lookup reads every field")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(200, SE_ADDRESS));
const address = server.client.lookup("01001-000");
assert(address.localidade == "São Paulo");
assert(address.uf == "SP");
assert(address.logradouro == "Praça da Sé");
assert(address.complemento == "lado ímpar");
assert(address.ibge == "3550308");
assert(address.formattedCep == "01001-000");
assert(address.geo.isNull);
}
@("the request carries the user agent and an accept header")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(200, SE_ADDRESS));
server.client.lookup("01001000");
const sent = server.lastHeaders.map!(h => h.toLower).array;
assert(sent.filter!(h => h.startsWith("user-agent: cepis-d/")).array.length == 1);
assert(sent.filter!(h => h.startsWith("accept: application/json")).array.length == 1);
}
@("the coordinate is read when present")
unittest
{
auto server = new TestServer();
server.respond("/01310100", Reply(200, withGeo("logradouro", 120)));
const geo = server.client.lookup("01310100").geo.get;
assert(geo.lat > -23.6 && geo.lat < -23.4);
assert(geo.lon > -46.7 && geo.lon < -46.5);
assert(geo.raio_m == 120);
assert(geo.isPrecise);
}
@("a municipality coordinate is flagged as imprecise")
unittest
{
auto server = new TestServer();
server.respond("/01310100", Reply(200, withGeo("localidade", 22_000)));
const geo = server.client.lookup("01310100").geo.get;
assert(!geo.isPrecise);
assert(geo.raio_m == 22_000);
}
@("a malformed geo block does not lose the address")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(200,
`{"cep":"01001000","localidade":"São Paulo","uf":"SP","geo":{"lat":"nowhere"}}`));
const address = server.client.lookup("01001000");
assert(address.geo.isNull);
assert(address.localidade == "São Paulo");
}
@("a new api field does not break the client")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(200,
`{"cep":"01001000","localidade":"São Paulo","campo_do_futuro":"value"}`));
const address = server.client.lookup("01001000");
assert(address.raw["campo_do_futuro"].str == "value");
assert(address.localidade == "São Paulo");
}
@("a missing cep is not found, and is not retried")
unittest
{
auto server = new TestServer();
server.respond("/99999999", Reply(404,
`{"erro":"cep_nao_encontrado","mensagem":"CEP não existe na base do DNE"}`));
auto client = server.client;
bool caught;
try
client.lookup("99999999");
catch (CepNotFoundException error)
{
caught = true;
assert(error.cep == "99999999");
assert(!error.retriable);
}
assert(caught);
assert(server.calledTimes("/99999999") == 1);
}
@("a not-found says which municipality the cep would have belonged to")
unittest
{
auto server = new TestServer();
server.respond("/25845000", Reply(404, AREAL_NOT_FOUND));
auto client = server.client;
bool caught;
try
client.lookup("25845-000");
catch (CepNotFoundException error)
{
caught = true;
assert(error.cep == "25845000");
assert(!error.retriable);
assert(!error.faixa.isNull);
const faixa = error.faixa.get;
assert(faixa.localidade == "Areal");
assert(faixa.uf == "RJ");
assert(faixa.estado == "Rio de Janeiro");
assert(faixa.regiao == "Sudeste");
assert(faixa.ibge == "3300225");
assert(faixa.cep_ini == "25845001");
assert(faixa.cep_fim == "25849899");
assert(faixa.ceps == 118);
assert(error.msg.canFind("Areal/RJ"));
}
assert(caught);
assert(server.calledTimes("/25845000") == 1);
}
@("a not-found in a band nobody owns carries no faixa")
unittest
{
auto server = new TestServer();
server.respond("/99999999", Reply(404,
`{"erro":"cep_nao_encontrado","mensagem":"CEP não existe na base do DNE"}`));
auto client = server.client;
bool caught;
try
client.lookup("99999999");
catch (CepNotFoundException error)
{
caught = true;
assert(error.faixa.isNull);
assert(error.msg.canFind("99999999"));
}
assert(caught);
}
@("a malformed faixa is still an ordinary not-found")
unittest
{
foreach (content; [
`{"erro":"cep_nao_encontrado","faixa":{}}`,
`{"erro":"cep_nao_encontrado","faixa":{"uf":"RJ"}}`,
`{"erro":"cep_nao_encontrado","faixa":"Areal"}`,
`{"erro":"cep_nao_encontrado","faixa":null}`, `<html>gateway</html>`, ``
])
{
auto server = new TestServer();
server.respond("/99999999", Reply(404, content));
auto client = server.client;
bool caught;
try
client.lookup("99999999");
catch (CepNotFoundException error)
{
caught = true;
assert(error.faixa.isNull);
}
assert(caught);
}
}
@("an invalid cep never leaves the machine")
unittest
{
auto server = new TestServer();
assertThrown!InvalidCepException(server.client.lookup("123"));
assert(server.calledTimes == 0);
}
@("a 400 from the api becomes an invalid cep carrying its message")
unittest
{
auto server = new TestServer();
server.respond("/00000000", Reply(400,
`{"erro":"cep_invalido","mensagem":"rejected by the API"}`));
auto client = server.client;
bool caught;
try
client.lookup("00000000");
catch (InvalidCepException error)
{
caught = true;
assert(error.msg == "rejected by the API");
}
assert(caught);
assert(server.calledTimes("/00000000") == 1);
}
@("a response that is not json is diagnosed")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(200, "<html>captive portal</html>"));
assertThrown!InvalidResponseException(server.client.lookup("01001000"));
}
@("a 500 is retried and then succeeds")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(500, `{"erro":"interno"}`), Reply(200, SE_ADDRESS));
const address = server.client.lookup("01001000");
assert(address.localidade == "São Paulo");
assert(server.calledTimes("/01001000") == 2);
}
@("the attempts run out and the server error surfaces")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(503, `{"erro":"interno"}`));
auto client = server.client;
bool caught;
try
client.lookup("01001000");
catch (ServerException error)
{
caught = true;
assert(error.status == 503);
assert(error.retriable);
}
assert(caught);
assert(server.calledTimes("/01001000") == 3);
}
@("one attempt disables retrying")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(500, "{}"));
assertThrown!ServerException(server.client(1).lookup("01001000"));
assert(server.calledTimes("/01001000") == 1);
}
@("rate limiting exposes retry-after")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(429, "{}", [["Retry-After", "7"]]));
auto client = server.client;
bool caught;
try
client.lookup("01001000");
catch (RateLimitedException error)
{
caught = true;
assert(error.retryAfter.get == dur!"seconds"(7));
assert(error.retriable);
}
assert(caught);
}
@("a wild retry-after is capped")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(429, "{}", [["Retry-After", "3600"]]));
const started = MonoTime.currTime;
assertThrown!RateLimitedException(server.client.lookup("01001000"));
assert(MonoTime.currTime - started < dur!"seconds"(5));
}
@("retry-after as an http date is understood and still capped")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(429, "{}", [
["Retry-After", "Wed, 21 Oct 2099 07:28:00 GMT"]
]));
const started = MonoTime.currTime;
auto client = server.client;
bool caught;
try
client.lookup("01001000");
catch (RateLimitedException error)
{
caught = true;
assert(error.retryAfter.get > dur!"days"(1));
}
assert(caught);
assert(MonoTime.currTime - started < dur!"seconds"(5));
}
@("nothing listening is a network error")
unittest
{
ClientConfig config;
config.baseUrl = "http://127.0.0.1:1";
config.maxAttempts = 2;
config.timeout = dur!"seconds"(1);
config.backoffBase = dur!"msecs"(1);
config.backoffMax = dur!"msecs"(10);
auto client = Client(config);
bool caught;
try
client.lookup("01001000");
catch (NetworkException error)
{
caught = true;
assert(error.retriable);
}
assert(caught);
}
@("the total timeout bounds the whole call")
unittest
{
auto server = new TestServer();
server.respond("/01001000", Reply(500, "{}"));
ClientConfig config;
config.baseUrl = server.url;
config.timeout = dur!"seconds"(5);
config.maxAttempts = 50;
config.backoffBase = dur!"msecs"(50);
config.backoffMax = dur!"msecs"(50);
config.totalTimeout = dur!"msecs"(300);
const started = MonoTime.currTime;
assertThrown!CepisException(Client(config).lookup("01001000"));
assert(MonoTime.currTime - started < dur!"seconds"(3));
assert(server.calledTimes("/01001000") < 50);
}
@("a batch keeps order and marks the missing entry")
unittest
{
auto server = new TestServer();
server.respond("/csv", Reply(200, csvBody(SE_ROW, MISSING_ROW, RJ_ROW)));
auto result = server.client.lookupMany(["01001000", "99999999", "20040020"]);
assert(result.length == 3);
assert(result[0].get.localidade == "São Paulo");
assert(result[1].isNull);
assert(result[2].get.uf == "RJ");
assert(result[2].get.logradouro == "Avenida Rio Branco");
}
@("a batch carries no coordinate")
unittest
{
auto server = new TestServer();
server.respond("/csv", Reply(200, csvBody(
"01001000,Praça da Sé,,,Sé,São Paulo,SP,São Paulo,Sudeste,3550308,1004,11,7107")));
auto result = server.client.lookupMany(["01001000"]);
assert(result[0].get.geo.isNull);
}
@("a quoted field containing a comma is parsed")
unittest
{
auto server = new TestServer();
server.respond("/csv", Reply(200,
csvBody(`01001000,"Rua Um, Dois",,,Centro,São Paulo,SP,São Paulo,Sudeste,1,,11,1`)));
auto result = server.client.lookupMany(["01001000"]);
assert(result[0].get.logradouro == "Rua Um, Dois");
}
@("an empty batch makes no request")
unittest
{
auto server = new TestServer();
assert(server.client.lookupMany([]).length == 0);
assert(server.calledTimes == 0);
}
@("a batch above the api limit is chunked")
unittest
{
auto server = new TestServer();
auto ceps = new string[501];
foreach (index; 0 .. ceps.length)
ceps[index] = format!"%08d"(index);
string row(string cep)
{
return cep ~ ",,,,,X,SP,São Paulo,Sudeste,1,,11,1";
}
server.respond("/csv", Reply(200, csvBody(ceps[0 .. 500].map!row.array)),
Reply(200, csvBody(ceps[500 .. $].map!row.array)));
auto result = server.client.lookupMany(ceps);
assert(result.length == 501);
assert(server.calledTimes("/csv") == 2);
foreach (address; result)
assert(!address.isNull);
}
@("a truncated batch pads instead of shifting")
unittest
{
auto server = new TestServer();
server.respond("/csv", Reply(200,
csvBody("01001000,,,,,São Paulo,SP,São Paulo,Sudeste,1,,11,1")));
auto result = server.client.lookupMany(["01001000", "20040020"]);
assert(result.length == 2);
assert(!result[0].isNull);
assert(result[1].isNull);
}
@("health reports the live database")
unittest
{
auto server = new TestServer();
server.respond("/health", Reply(200,
`{"status":"ok","dne":"26071","ceps":1596168,"geo":894489,`
~ `"base_gerada_em":"2026-07-24T03:48:28Z"}`));
const health = server.client.health();
assert(health.ok);
assert(health.dne == "26071");
assert(health.ceps == 1_596_168);
assert(health.geo == 894_489);
assert(health.base_gerada_em == "2026-07-24T03:48:28Z");
}
@("a degraded api is not an error")
unittest
{
auto server = new TestServer();
server.respond("/health", Reply(503, `{"status":"degradado","dne":"","ceps":0,"geo":0}`));
const health = server.client.health();
assert(!health.ok);
assert(health.status == "degradado");
assert(server.calledTimes("/health") == 1);
}
|