-
-
Notifications
You must be signed in to change notification settings - Fork 108
Create Municipality Method #412
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
48d598a
Update CHANGELOG.md
jaimenunes 73046f1
Create Municipality Method
jaimenunes 1bb9a0d
Update Format
jaimenunes b1a79a4
resolve conflict
jaimenunes c9d7d13
Merge branch 'main' into 398
jaimenunes 2b4f455
fix readme
jaimenunes 43483ad
updated changelog
jaimenunes 9d6ff2d
Merge branch 'main' into 398
jaimenunes d701f1f
Apply suggestions from code review
camilamaia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| import gzip | ||
| import io | ||
| import json | ||
| from urllib.error import HTTPError | ||
| from urllib.request import urlopen | ||
|
|
||
|
|
||
| def get_municipality_by_code(code): # type: (str) -> Tuple[str, str] | None | ||
| """ | ||
| Returns the municipality name and UF for a given IBGE code. | ||
|
|
||
| This function takes a string representing an IBGE municipality code | ||
| and returns a tuple with the municipality's name and its corresponding UF. | ||
|
|
||
| Args: | ||
| code (str): The IBGE code of the municipality. | ||
|
|
||
| Returns: | ||
| tuple: A tuple formatted as ("Município", "UF"). | ||
| - Returns None if the code is not valid. | ||
|
|
||
| Example: | ||
| >>> get_municipality_by_code("3550308") | ||
| ("São Paulo", "SP") | ||
| """ | ||
| baseUrl = ( | ||
| f"https://servicodados.ibge.gov.br/api/v1/localidades/municipios/{code}" | ||
| ) | ||
| try: | ||
| with urlopen(baseUrl) as f: | ||
| compressed_data = f.read() | ||
| if f.info().get("Content-Encoding") == "gzip": | ||
| try: | ||
| with gzip.GzipFile( | ||
| fileobj=io.BytesIO(compressed_data) | ||
| ) as gzip_file: | ||
| decompressed_data = gzip_file.read() | ||
| except OSError as e: | ||
| print(f"Erro ao descomprimir os dados: {e}") | ||
| return None | ||
| except Exception as e: | ||
| print(f"Erro desconhecido ao descomprimir os dados: {e}") | ||
| return None | ||
| else: | ||
| decompressed_data = compressed_data | ||
|
|
||
| if _is_empty(decompressed_data): | ||
| print(f"{code} é um código inválido") | ||
| return None | ||
|
|
||
| except HTTPError as e: | ||
| if e.code == 404: | ||
| print(f"{code} é um código inválido") | ||
| return None | ||
| else: | ||
| print(f"Erro HTTP ao buscar o código {code}: {e}") | ||
| return None | ||
|
|
||
| except Exception as e: | ||
| print(f"Erro desconhecido ao buscar o código {code}: {e}") | ||
| return None | ||
|
|
||
| try: | ||
| json_data = json.loads(decompressed_data) | ||
| return _get_values(json_data) | ||
| except json.JSONDecodeError as e: | ||
| print(f"Erro ao decodificar os dados JSON: {e}") | ||
| return None | ||
| except KeyError as e: | ||
| print(f"Erro ao acessar os dados do município: {e}") | ||
| return None | ||
|
|
||
|
|
||
| def _get_values(data): | ||
| municipio = data["nome"] | ||
| estado = data["microrregiao"]["mesorregiao"]["UF"]["sigla"] | ||
| return (municipio, estado) | ||
|
|
||
|
|
||
| def _is_empty(zip): | ||
| return zip == b"[]" or len(zip) == 0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import gzip | ||
| from json import JSONDecodeError | ||
| from unittest import TestCase, main | ||
| from unittest.mock import MagicMock, patch | ||
| from urllib.error import HTTPError | ||
|
|
||
| from brutils.ibge.municipality import get_municipality_by_code | ||
|
|
||
|
|
||
| class TestIBGE(TestCase): | ||
| def test_get_municipality_by_code(self): | ||
| self.assertEqual( | ||
| get_municipality_by_code("3550308"), ("São Paulo", "SP") | ||
| ) | ||
| self.assertEqual( | ||
| get_municipality_by_code("3304557"), ("Rio de Janeiro", "RJ") | ||
| ) | ||
| self.assertEqual(get_municipality_by_code("5208707"), ("Goiânia", "GO")) | ||
| self.assertIsNone(get_municipality_by_code("1234567")) | ||
|
|
||
| @patch("brutils.ibge.municipality.urlopen") | ||
| def test_get_municipality_http_error(self, mock): | ||
| mock.side_effect = HTTPError( | ||
| "http://fakeurl.com", 404, "Not Found", None, None | ||
| ) | ||
| result = get_municipality_by_code("342432") | ||
| self.assertIsNone(result) | ||
|
|
||
| @patch("brutils.ibge.municipality.urlopen") | ||
| def test_get_municipality_http_error_1(self, mock): | ||
| mock.side_effect = HTTPError( | ||
| "http://fakeurl.com", 401, "Denied", None, None | ||
| ) | ||
| result = get_municipality_by_code("342432") | ||
| self.assertIsNone(result) | ||
|
|
||
| @patch("brutils.ibge.municipality.urlopen") | ||
| def test_get_municipality_excpetion(self, mock): | ||
| mock.side_effect = Exception("Erro desconhecido") | ||
| result = get_municipality_by_code("342432") | ||
| self.assertIsNone(result) | ||
|
|
||
| @patch("brutils.ibge.municipality.urlopen") | ||
| def test_successfull_decompression(self, mock_urlopen): | ||
| valid_json = '{"nome":"São Paulo","microrregiao":{"mesorregiao":{"UF":{"sigla":"SP"}}}}' | ||
| compressed_data = gzip.compress(valid_json.encode("utf-8")) | ||
| mock_response = MagicMock() | ||
| mock_response.read.return_value = compressed_data | ||
| mock_response.info.return_value.get.return_value = "gzip" | ||
| mock_urlopen.return_value.__enter__.return_value = mock_response | ||
|
|
||
| result = get_municipality_by_code("3550308") | ||
| self.assertEqual(result, ("São Paulo", "SP")) | ||
|
|
||
| @patch("brutils.ibge.municipality.urlopen") | ||
| def test_successful_json_without_compression(self, mock_urlopen): | ||
| valid_json = '{"nome":"São Paulo","microrregiao":{"mesorregiao":{"UF":{"sigla":"SP"}}}}' | ||
| mock_response = MagicMock() | ||
| mock_response.read.return_value = valid_json | ||
| mock_urlopen.return_value.__enter__.return_value = mock_response | ||
|
|
||
| result = get_municipality_by_code("3550308") | ||
| self.assertEqual(result, ("São Paulo", "SP")) | ||
|
|
||
| @patch("gzip.GzipFile.read", side_effect=OSError("Erro na descompressão")) | ||
| def test_error_decompression(self, mock_gzip_read): | ||
| result = get_municipality_by_code("3550308") | ||
| self.assertIsNone(result) | ||
|
|
||
| @patch( | ||
| "gzip.GzipFile.read", | ||
| side_effect=Exception("Erro desconhecido na descompressão"), | ||
| ) | ||
| def test_error_decompression_generic_exception(self, mock_gzip_read): | ||
| result = get_municipality_by_code("3550308") | ||
| self.assertIsNone(result) | ||
|
|
||
| @patch("json.loads", side_effect=JSONDecodeError("error", "city.json", 1)) | ||
| def test_error_json_load(self, mock_json_loads): | ||
| result = get_municipality_by_code("3550308") | ||
| self.assertIsNone(result) | ||
|
|
||
| @patch("json.loads", side_effect=KeyError) | ||
| def test_error_json_key_error(self, mock_json_loads): | ||
| result = get_municipality_by_code("3550308") | ||
| self.assertIsNone(result) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.