Skip to content

Commit

Permalink
Add new exceptions to VIACEP adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
mstuttgart committed Nov 25, 2024
1 parent e4921eb commit 8921c59
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 17 deletions.
37 changes: 32 additions & 5 deletions brazilcep/viacep.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,42 @@ def fetch_address(cep: str, timeout: Union[None, int], proxies: Union[None, dict
a REST API to query CEP requests.
Args:
cep: CEP to be searched.
timeout: How many seconds to wait for the server to return data before giving up.
proxies: Dictionary mapping protocol to the URL of the proxy.
cep: CEP to be searched
timeout: How many seconds to wait for the server to return data before giving up
proxies: Dictionary mapping protocol to the URL of the proxy
Raises:
exceptions.ConnectionError: raised by a connection error
exceptions.HTTPError: raised by HTTP error
exceptions.URLRequired: raised by using a invalid URL to make a request
exceptions.TooManyRedirects: raised by too many redirects
exceptions.Timeout: raised by request timed out
exceptions.InvalidCEP: raised to invalid CEP requests
exceptions.BlockedByFlood: raised by flood of requests
exceptions.CEPNotFound: raised to CEP not founded requests
exceptions.BrazilCEPException: Base class for exception
Returns:
Respective address data from CEP.
Address data from CEP
"""

response = requests.get(URL.format(cep), timeout=timeout, proxies=proxies)
try:
response = requests.get(URL.format(cep), timeout=timeout, proxies=proxies)

except requests.exceptions.ConnectionError as exc:
raise exceptions.ConnectionError(exc)

except requests.exceptions.HTTPError as exc:
raise exceptions.HTTPError(exc)

except requests.exceptions.URLRequired as exc:
raise exceptions.URLRequired(exc)

except requests.exceptions.TooManyRedirects as exc:
raise exceptions.TooManyRedirects(exc)

except requests.exceptions.Timeout as exc:
raise exceptions.Timeout(exc)

if response.status_code == 200:
# Transforma o objeto requests em um dict
Expand Down
71 changes: 59 additions & 12 deletions tests/test_viacep.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,38 @@
import logging
import os

import dotenv
import pytest
import requests
from dotenv import load_dotenv

from brazilcep import WebService, exceptions, get_address_from_cep

logger = logging.getLogger(__name__)

load_dotenv()
dotenv.load_dotenv()

IN_GITHUB_ACTIONS = os.getenv("GITHUB_ACTIONS") == "true"
SKIP_REAL_TEST = os.getenv("SKIP_REAL_TEST", False)


@pytest.mark.skipif(SKIP_REAL_TEST, reason="Skip real teste API.")
@pytest.mark.skipif(IN_GITHUB_ACTIONS, reason="Test doesn't work in Github Actions.")
def test_get_address_from_cep_success_real():
try:
address = get_address_from_cep("37.503-130", webservice=WebService.VIACEP)
address = get_address_from_cep("37.503-130", webservice=WebService.VIACEP)

assert address["district"] == "Santo Antônio"
assert address["cep"] == "37503-130"
assert address["city"] == "Itajubá"
assert address["complement"] == "até 214/215"
assert address["street"] == "Rua Geraldino Campista"
assert address["uf"] == "MG"
assert address["district"] == "Santo Antônio"
assert address["cep"] == "37503-130"
assert address["city"] == "Itajubá"
assert address["complement"] == "até 214/215"
assert address["street"] == "Rua Geraldino Campista"
assert address["uf"] == "MG"

except requests.exceptions.ConnectionError as exc:
logger.warning(exc)

@pytest.mark.skipif(SKIP_REAL_TEST, reason="Skip real teste API.")
@pytest.mark.skipif(IN_GITHUB_ACTIONS, reason="Test doesn't work in Github Actions.")
def test_get_address_from_cep_not_found_real():
with pytest.raises(exceptions.CEPNotFound):
get_address_from_cep("00000-000", webservice=WebService.VIACEP)


def test_get_address_from_cep_success(requests_mock):
Expand Down Expand Up @@ -91,3 +95,46 @@ def test_fetch_address_404(requests_mock):

with pytest.raises(exceptions.BrazilCEPException):
get_address_from_cep("37503-130", webservice=WebService.VIACEP)


def test_connection_error(requests_mock):
requests_mock.get(
"http://www.viacep.com.br/ws/37503130/json", exc=requests.exceptions.ConnectionError
)

with pytest.raises(exceptions.ConnectionError):
get_address_from_cep("37503-130", webservice=WebService.VIACEP)


def test_http_error(requests_mock):
requests_mock.get(
"http://www.viacep.com.br/ws/37503130/json", exc=requests.exceptions.HTTPError
)

with pytest.raises(exceptions.HTTPError):
get_address_from_cep("37503-130", webservice=WebService.VIACEP)


def test_url_required_error(requests_mock):
requests_mock.get(
"http://www.viacep.com.br/ws/37503130/json", exc=requests.exceptions.URLRequired
)

with pytest.raises(exceptions.URLRequired):
get_address_from_cep("37503-130", webservice=WebService.VIACEP)


def test_too_many_redirects_error(requests_mock):
requests_mock.get(
"http://www.viacep.com.br/ws/37503130/json", exc=requests.exceptions.TooManyRedirects
)

with pytest.raises(exceptions.TooManyRedirects):
get_address_from_cep("37503-130", webservice=WebService.VIACEP)


def test_timeout_error(requests_mock):
requests_mock.get("http://www.viacep.com.br/ws/37503130/json", exc=requests.exceptions.Timeout)

with pytest.raises(exceptions.Timeout):
get_address_from_cep("37503-130", webservice=WebService.VIACEP)

0 comments on commit 8921c59

Please sign in to comment.