Skip to content

Commit bf7e281

Browse files
authored
test: mockando chamada a API externa de busca de municípios (#491)
1 parent b8e84bd commit bf7e281

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

tests/ibge/test_municipality.py

+42-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import gzip
2-
from json import JSONDecodeError
2+
from json import JSONDecodeError, dumps
33
from unittest import TestCase, main
44
from unittest.mock import MagicMock, patch
55
from urllib.error import HTTPError
@@ -11,7 +11,47 @@
1111

1212

1313
class TestIBGE(TestCase):
14-
def test_get_municipality_by_code(self):
14+
@patch("brutils.ibge.municipality.urlopen")
15+
def test_get_municipality_by_code(self, mock):
16+
def mock_response(url):
17+
responses = {
18+
"https://servicodados.ibge.gov.br/api/v1/localidades/municipios/3550308": dumps(
19+
{
20+
"nome": "São Paulo",
21+
"microrregiao": {
22+
"mesorregiao": {"UF": {"sigla": "SP"}}
23+
},
24+
}
25+
).encode("utf-8"),
26+
"https://servicodados.ibge.gov.br/api/v1/localidades/municipios/3304557": dumps(
27+
{
28+
"nome": "Rio de Janeiro",
29+
"microrregiao": {
30+
"mesorregiao": {"UF": {"sigla": "RJ"}}
31+
},
32+
}
33+
).encode("utf-8"),
34+
"https://servicodados.ibge.gov.br/api/v1/localidades/municipios/5208707": dumps(
35+
{
36+
"nome": "Goiânia",
37+
"microrregiao": {
38+
"mesorregiao": {"UF": {"sigla": "GO"}}
39+
},
40+
}
41+
).encode("utf-8"),
42+
"https://servicodados.ibge.gov.br/api/v1/localidades/municipios/1234567": b"[]",
43+
}
44+
45+
mock_file = MagicMock()
46+
mock_file.__enter__.return_value = (
47+
mock_file # mock_file is a context manager
48+
)
49+
mock_file.read.return_value = responses.get(url, b"[]")
50+
mock_file.info.return_value = {"Content-Encoding": None}
51+
return mock_file
52+
53+
mock.side_effect = mock_response
54+
1555
self.assertEqual(
1656
get_municipality_by_code("3550308"), ("São Paulo", "SP")
1757
)

0 commit comments

Comments
 (0)