Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 30 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -333,18 +333,14 @@ False
### format_cep

Formata um CEP (Código de Endereçamento Postal) brasileiro em um formato padrão.
Esta função recebe um CEP como entrada, remove caracteres especiais e, se for um
CEP válido com 8 dígitos, e retorna o formata no padrão "12345-678" ou apenas os
números "12345678" se o parâmetro only_nums for True.
Esta função recebe um CEP como entrada e, se for um CEP válido com 8 dígitos,
o formata no padrão "12345-678".

Argumentos:

- cep (str): O CEP (Código de Endereçamento Postal) de entrada a ser
formatado.

- only_nums (bool): Valor default é False, caso seja passado True como valor
será retornada uma string contendo apenas números

Retorna:

- str: O CEP formatado no formato "12345-678" se for válido, None se não for
Expand All @@ -356,14 +352,37 @@ Example:
>>> from brutils import format_cep
>>> format_cep('01310200')
'01310-200'
>>> format_cep(" 12.345_678 ")
"12345-678"
>>> format_cep("12345678", only_nums=True)
>>> format_cep("12345678")
"12345-678"
>>> format_cep("12345")
None
>>> format_cep("ac345-564")
"ac345-564"
```

### remove_symbols_cep

Remove símbolos específicos de um CEP (Código de Endereçamento Postal)
fornecido. Esta função recebe um CEP como entrada e remove todas as ocorrências
dos caracteres '.' e '-' dele.

Argumentos:

- cep (str): O CEP (Código de Endereçamento Postal) de entrada que contém os
símbolos a serem removidos.

Retorna:

- str: Uma nova string com os símbolos especificados removidos.

Exemplo:

```python
>>> from brutils import remove_symbols_cep
>>> remove_symbols_cep('01310-200')
'01310200'
>>> remove_symbols_cep("123-45.678.9")
"123456789"
>>> remove_symbols_cep("abc.xyz")
"abcxyz"
```

### generate_cep
Expand Down
41 changes: 28 additions & 13 deletions README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -334,19 +334,13 @@ False

### format_cep

This function formats a brazillian postal code (CEP) in the standard format.
It receives a CEP as input, removes all special characters, validates if the
CEP is 8 digits long, and returns the standard format "12345-678" or only the
numbers "12345678" if the parameters only_nums is setted as True.
This function takes a CEP (Postal Code) as input and, if it is a valid
8-digit CEP, formats it into the standard "12345-678" format.

Args:

- cep (str): The input CEP (Postal Code) to be formatted.

- only_nums (bool): The default value is False, in case of the True value be
inputed, the function will return a string with only
numbers

Returns:

- str: The formatted CEP in the "12345-678" format if it's valid,
Expand All @@ -358,14 +352,35 @@ Example:
>>> from brutils import format_cep
>>> format_cep('01310200')
'01310-200'
>>> format_cep(" 12.345_678 ")
"12345-678"
>>> format_cep("12345678", only_nums=True)
>>> format_cep("12345678")
"12345-678"
>>> format_cep("12345")
None
>>> format_cep("ac345-564")
"ac345-564"
```

### remove_symbols_cep

This function takes a CEP (Postal Code) as input and removes all occurrences of
the '.' and '-' characters from it.

Args:

- cep (str): The input CEP (Postal Code) containing symbols to be removed.

Returns:

- str: A new string with the specified symbols removed.

Example:

```python
>>> from brutils import remove_symbols_cep
>>> remove_symbols_cep('01310-200')
'01310200'
>>> remove_symbols_cep("123-45.678.9")
"123456789"
>>> remove_symbols_cep("abc.xyz")
"abcxyz"
```

### generate_cep
Expand Down
2 changes: 2 additions & 0 deletions brutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
)
from brutils.cep import generate as generate_cep
from brutils.cep import is_valid as is_valid_cep
from brutils.cep import remove_symbols as remove_symbols_cep

# CNH Imports
from brutils.cnh import is_valid_cnh as is_valid_cnh
Expand Down Expand Up @@ -94,6 +95,7 @@
"get_cep_information_from_address",
"generate_cep",
"is_valid_cep",
"remove_symbols_cep",
# CNPJ
"format_cnpj",
"generate_cnpj",
Expand Down
52 changes: 28 additions & 24 deletions brutils/cep.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,35 @@
############


def format_cep(cep: str, only_nums=False) -> str | None:
def remove_symbols(dirty: str) -> str:
"""
Removes specific symbols from a given CEP (Postal Code).

This function takes a CEP (Postal Code) as input and removes all occurrences
of the '.' and '-' characters from it.

Args:
cep (str): The input CEP (Postal Code) containing symbols to be removed.

Returns:
str: A new string with the specified symbols removed.

Example:
>>> remove_symbols("123-45.678.9")
"123456789"
>>> remove_symbols("abc.xyz")
"abcxyz"
"""

return "".join(filter(lambda char: char not in ".-", dirty))


def format_cep(cep: str) -> str | None:
"""
Formats a Brazilian CEP (Postal Code) into a standard format.

This function takes a CEP (Postal Code) as input and,
- Removes special characteres;
- Check if the string follows the CEP length pattern;
- Returns None if the string is out of the pattern;
- Return a string with the formatted CEP.
This function takes a CEP (Postal Code) as input and, if it is a valid
8-digit CEP, formats it into the standard "12345-678" format.

Args:
cep (str): The input CEP (Postal Code) to be formatted.
Expand All @@ -31,27 +51,11 @@ def format_cep(cep: str, only_nums=False) -> str | None:
Example:
>>> format_cep("12345678")
"12345-678"
>>> format_cep(" 12.345/678 ", only_nums=True)
"12345678"
>>> format_cep("12345")
None
"""
### Checking data type
if not isinstance(cep, str):
return None

### Removing special characteres
cep = "".join(filter(str.isalnum, cep))

### Checking CEP patterns
if len(cep) != 8:
return None

### Returning CEP value
if only_nums:
return cep
else:
return f"{cep[:5]}-{cep[5:]}"
return f"{cep[:5]}-{cep[5:8]}" if is_valid(cep) else None


# OPERATIONS
Expand Down Expand Up @@ -152,7 +156,7 @@ def get_address_from_cep(
"""
base_api_url = "https://viacep.com.br/ws/{}/json/"

clean_cep = format_cep(cep, only_nums=True)
clean_cep = remove_symbols(cep)
cep_is_valid = is_valid(clean_cep)

if not cep_is_valid:
Expand Down
21 changes: 14 additions & 7 deletions tests/test_cep.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,20 @@
get_address_from_cep,
get_cep_information_from_address,
is_valid,
remove_symbols,
)


class TestCEP(TestCase):
def test_remove_symbols(self):
self.assertEqual(format_cep("00000000"), "00000-000")
self.assertEqual(format_cep("01310-200", only_nums=True), "01310200")
self.assertEqual(format_cep("01..310.-200.-"), "01310-200")
self.assertEqual(format_cep("abc01310200*!*&#"), None)
self.assertEqual(format_cep("ab.c1.--.3-102.-0-.0-.*.-!*&#"), None)
self.assertEqual(remove_symbols("00000000"), "00000000")
self.assertEqual(remove_symbols("01310-200"), "01310200")
self.assertEqual(remove_symbols("01..310.-200.-"), "01310200")
self.assertEqual(remove_symbols("abc01310200*!*&#"), "abc01310200*!*&#")
self.assertEqual(
remove_symbols("ab.c1.--.3-102.-0-.0-.*.-!*&#"), "abc1310200*!*&#"
)
self.assertEqual(remove_symbols("...---..."), "")

def test_is_valid(self):
# When CEP is not string, returns False
Expand Down Expand Up @@ -46,11 +50,14 @@ def test_when_cep_is_valid_returns_True_to_format(self, mock_is_valid):

self.assertEqual(format_cep("01310200"), "01310-200")

def test_when_cep_is_not_valid_returns_error(self, mock_is_valid):
# Checks if function is_valid_cnpj is called
mock_is_valid.assert_called_once_with("01310200")

def test_when_cep_is_not_valid_returns_none(self, mock_is_valid):
mock_is_valid.return_value = False

# When cep isn't valid, returns None
self.assertEqual(format_cep("013102009"), None)
self.assertIsNone(format_cep("013102009"))


@patch("brutils.cep.urlopen")
Expand Down