|
1 | 1 | import gzip
|
2 |
| -from json import JSONDecodeError |
| 2 | +from json import JSONDecodeError, dumps |
3 | 3 | from unittest import TestCase, main
|
4 | 4 | from unittest.mock import MagicMock, patch
|
5 | 5 | from urllib.error import HTTPError
|
|
11 | 11 |
|
12 | 12 |
|
13 | 13 | 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 | + |
15 | 55 | self.assertEqual(
|
16 | 56 | get_municipality_by_code("3550308"), ("São Paulo", "SP")
|
17 | 57 | )
|
|
0 commit comments