summaryrefslogtreecommitdiffstats
path: root/tests/LookupTest.php
blob: 03dee5748561c525e863803b0b9ddef45928caa7 (plain)
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
<?php

declare(strict_types=1);

namespace Cepis\Tests;

use Cepis\CepNotFoundException;
use Cepis\InvalidCepException;
use Cepis\InvalidResponseException;

final class LookupTest extends ServerTestCase
{
    /**
     * The `faixa` the API sends on the 404 of a CEP that does not exist but
     * falls inside a municipality's range. `25845000` is the textbook case: it
     * is the DNE's own start for Areal, it is the number everyone guesses, and
     * it was never issued — which is why `cep_ini` is `25845001`.
     */
    private const AREAL_FAIXA = [
        'localidade' => 'Areal',
        'uf' => 'RJ',
        'estado' => 'Rio de Janeiro',
        'regiao' => 'Sudeste',
        'ibge' => '3300225',
        'cep_ini' => '25845001',
        'cep_fim' => '25849899',
        'ceps' => 118,
    ];

    public function testSuccessfulLookup(): void
    {
        $this->server->respond('/01001000', [self::json(self::SE_ADDRESS)]);
        $address = $this->client->lookup('01001-000');

        self::assertSame('Praça da Sé', $address->logradouro);
        self::assertSame('São Paulo', $address->localidade);
        self::assertSame('SP', $address->uf);
        self::assertSame('01001000', $address->cep);
        self::assertSame('01001-000', $address->formattedCep());
        self::assertNull($address->geo);
    }

    public function testReadsTheCoordinateWhenPresent(): void
    {
        $body = self::SE_ADDRESS + [];
        $body['geo'] = ['lat' => -23.567202, 'lon' => -46.649659, 'raio_m' => 1084, 'precisao' => 'logradouro'];
        $this->server->respond('/01310100', [self::json($body)]);
        $address = $this->client->lookup('01310100');

        self::assertNotNull($address->geo);
        self::assertEqualsWithDelta(-23.567202, $address->geo->lat, 1e-9);
        self::assertEqualsWithDelta(-46.649659, $address->geo->lon, 1e-9);
        self::assertSame(1084, $address->geo->raio_m);
        self::assertSame('logradouro', $address->geo->precisao);
        self::assertTrue($address->geo->isPrecise());
    }

    public function testMunicipalityCoordinateIsNotPrecise(): void
    {
        $body = self::SE_ADDRESS;
        $body['geo'] = ['lat' => -23.5, 'lon' => -46.6, 'raio_m' => 22000, 'precisao' => 'localidade'];
        $this->server->respond('/01001000', [self::json($body)]);

        $geo = $this->client->lookup('01001000')->geo;
        self::assertNotNull($geo);
        self::assertFalse($geo->isPrecise());
    }

    public function testMalformedGeoDoesNotLoseTheAddress(): void
    {
        $body = self::SE_ADDRESS;
        $body['geo'] = ['lat' => 'not a number'];
        $this->server->respond('/01001000', [self::json($body)]);
        $address = $this->client->lookup('01001000');

        self::assertNull($address->geo);
        self::assertSame('São Paulo', $address->localidade);
    }

    public function testNewApiFieldDoesNotBreak(): void
    {
        $body = self::SE_ADDRESS;
        $body['campo_do_futuro'] = 'value';
        $this->server->respond('/01001000', [self::json($body)]);
        $address = $this->client->lookup('01001000');

        self::assertSame('value', $address->raw['campo_do_futuro']);
        self::assertSame('value', $address->field('campo_do_futuro'));
        self::assertNull($address->field('nao_existe'));
        self::assertSame('São Paulo', $address->localidade);
    }

    public function testMissingFieldsBecomeEmptyStringsNotNull(): void
    {
        $this->server->respond('/01001000', [self::json(['cep' => '01001000'])]);
        $address = $this->client->lookup('01001000');

        self::assertSame('', $address->logradouro);
        self::assertSame('', $address->uf);
    }

    public function testNotFound(): void
    {
        $this->server->respond('/99999999', [self::json(
            ['erro' => 'cep_nao_encontrado', 'mensagem' => 'CEP não existe na base do DNE'],
            404,
        )]);

        try {
            $this->client->lookup('99999999');
            self::fail('expected CepNotFoundException');
        } catch (CepNotFoundException $exception) {
            self::assertStringContainsString('99999999', $exception->getMessage());
            self::assertNull($exception->faixa);
        }
    }

    public function testNotFoundCarriesTheFaixaWhenTheApiSendsOne(): void
    {
        $this->server->respond('/25845000', [self::json(
            [
                'erro' => 'cep_nao_encontrado',
                'mensagem' => 'CEP não existe na base do DNE',
                'faixa' => self::AREAL_FAIXA,
            ],
            404,
        )]);

        try {
            $this->client->lookup('25845-000');
            self::fail('expected CepNotFoundException');
        } catch (CepNotFoundException $exception) {
            $faixa = $exception->faixa;
            self::assertNotNull($faixa);
            self::assertSame('Areal', $faixa->localidade);
            self::assertSame('RJ', $faixa->uf);
            self::assertSame('Rio de Janeiro', $faixa->estado);
            self::assertSame('Sudeste', $faixa->regiao);
            self::assertSame('3300225', $faixa->ibge);
            self::assertSame(118, $faixa->ceps);
            self::assertSame('Areal/RJ', $faixa->label());

            // The bounds are the CEPs that exist, not the ones the Correios
            // publish: the CEP that just failed is the DNE's own start for
            // Areal and is below cep_ini for exactly that reason.
            self::assertSame('25845001', $faixa->cep_ini);
            self::assertSame('25849899', $faixa->cep_fim);
            self::assertTrue($faixa->cep_ini > '25845000');

            // 118 CEPs over ~4,900 numbers: the pair is a range, never a list.
            self::assertLessThan(
                (int) $faixa->cep_fim - (int) $faixa->cep_ini,
                $faixa->ceps,
            );

            self::assertStringContainsString('Areal/RJ', $exception->getMessage());
            self::assertStringContainsString('25845000', $exception->getMessage());
        }
    }

    public function testFaixaIsStillANotFoundAndNotAnAddress(): void
    {
        $this->server->respond('/25845000', [self::json(
            ['erro' => 'cep_nao_encontrado', 'faixa' => self::AREAL_FAIXA],
            404,
        )]);

        $this->expectException(CepNotFoundException::class);
        $this->client->lookup('25845000');
    }

    /**
     * A `faixa` this client cannot read costs nothing: the answer is the same
     * not-found it would have been without one. Anything else would trade a
     * useful exception for an unhelpful parse failure.
     */
    public function testUnreadableFaixaStillGivesACleanNotFound(): void
    {
        $shapes = [
            'null' => null,
            'empty object' => [],
            'a string' => 'Areal',
            'a number' => 42,
            'a list' => ['Areal', 'RJ'],
            'no municipality' => ['uf' => 'RJ', 'cep_ini' => '25845001'],
            'empty municipality' => ['localidade' => '', 'uf' => 'RJ'],
            'nested junk' => ['localidade' => ['Areal'], 'ceps' => 'many'],
        ];

        $specs = [];
        foreach ($shapes as $faixa) {
            $specs[] = self::json(['erro' => 'cep_nao_encontrado', 'faixa' => $faixa], 404);
        }
        $this->server->respond('/25845000', $specs);

        foreach (array_keys($shapes) as $name) {
            try {
                $this->client->lookup('25845000');
                self::fail('expected CepNotFoundException for ' . $name);
            } catch (CepNotFoundException $exception) {
                self::assertNull($exception->faixa, $name);
                self::assertStringContainsString('25845000', $exception->getMessage(), $name);
            }
        }
    }

    public function testPartialFaixaKeepsWhatItCanRead(): void
    {
        $this->server->respond('/25845000', [self::json(
            ['erro' => 'cep_nao_encontrado', 'faixa' => ['localidade' => 'Areal', 'ceps' => 'many']],
            404,
        )]);

        try {
            $this->client->lookup('25845000');
            self::fail('expected CepNotFoundException');
        } catch (CepNotFoundException $exception) {
            self::assertNotNull($exception->faixa);
            self::assertSame('Areal', $exception->faixa->localidade);
            self::assertSame('', $exception->faixa->uf);
            self::assertSame('', $exception->faixa->cep_ini);
            self::assertSame(0, $exception->faixa->ceps);
            self::assertSame('Areal', $exception->faixa->label());
        }
    }

    public function testUnreadableNotFoundBodyStillGivesACleanNotFound(): void
    {
        $this->server->respond('/25845000', [self::raw(404, '<html>proxy says no</html>')]);

        try {
            $this->client->lookup('25845000');
            self::fail('expected CepNotFoundException');
        } catch (CepNotFoundException $exception) {
            self::assertNull($exception->faixa);
        }
    }

    public function testNotFoundIsNotRetried(): void
    {
        $this->server->respond('/99999999', [self::json(['erro' => 'cep_nao_encontrado'], 404)]);

        $this->expectException(CepNotFoundException::class);

        try {
            $this->client->lookup('99999999');
        } finally {
            self::assertSame(1, $this->server->countCalls('/99999999'));
        }
    }

    public function testInvalidCepNeverLeavesTheMachine(): void
    {
        try {
            $this->client->lookup('123');
            self::fail('expected InvalidCepException');
        } catch (InvalidCepException) {
            self::assertSame([], $this->server->calls());
        }
    }

    public function testApi400BecomesInvalidCep(): void
    {
        $this->server->respond('/00000000', [self::json(
            ['erro' => 'cep_invalido', 'mensagem' => 'rejected by the API'],
            400,
        )]);

        try {
            $this->client->lookup('00000000');
            self::fail('expected InvalidCepException');
        } catch (InvalidCepException $exception) {
            self::assertSame('rejected by the API', $exception->getMessage());
            self::assertSame(1, $this->server->countCalls('/00000000'));
        }
    }

    public function testResponseThatIsNotJson(): void
    {
        $this->server->respond('/01001000', [self::raw(200, '<html>captive portal</html>')]);

        $this->expectException(InvalidResponseException::class);
        $this->client->lookup('01001000');
    }

    public function testJsonArrayIsNotAnObject(): void
    {
        $this->server->respond('/01001000', [self::raw(200, '[1, 2, 3]')]);

        $this->expectException(InvalidResponseException::class);
        $this->client->lookup('01001000');
    }
}