Skip to content
Open
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
38 changes: 11 additions & 27 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,9 @@ Exemplo:

Verifica se os dígitos de verificação do CNPJ (Cadastro Nacional da Pessoa
Jurídica) fornecido correspondem ao seu número base. A entrada deve ser uma
string de dígitos com o comprimento apropriado. Esta função não verifica a
existência do CNPJ; ela só valida o formato da string.
string de dígitos, sem caracteres especiais e com o comprimento apropriado.
Esta função não verifica a existência do CNPJ; ela só valida o formato da
string.

Argumentos:

Expand Down Expand Up @@ -240,6 +241,9 @@ formata com símbolos visuais padrão para fins de exibição.
Argumentos:

- cnpj (str): A string de CNPJ a ser formatada para exibição.
- only_nums (bool, optional): Valor default é False, caso seja passado True como
valor será retornada uma string contendo apenas
números.

Retorna:

Expand All @@ -251,33 +255,12 @@ Exemplo:
>>> from brutils import format_cnpj
>>> format_cnpj("03560714000142")
'03.560.714/0001-42'
>>> format_cnpj("03.560.714/0001-42", only_nums=True)
'03560714000142'
>>> format_cnpj("98765432100100")
None
```

### remove_symbols_cnpj

Remove símbolos específicos de uma string de CNPJ (Cadastro Nacional da Pessoa
Jurídica).
Esta função recebe uma string de CNPJ como entrada e remove todas as
ocorrências dos caracteres '.', '/' e '-' dela.

Argumentos:

- cnpj (str): A string de CNPJ 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_cnpj
>>> remove_symbols_cnpj('00.111.222/0001-00')
'00111222000100'
```

### generate_cnpj

Gera uma string de dígitos CNPJ válida aleatória. Um número de filial
Expand Down Expand Up @@ -342,8 +325,9 @@ 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
- only_nums (bool, optional): Valor default é False, caso seja passado True como
valor será retornada uma string contendo apenas
números.

Retorna:

Expand Down
28 changes: 5 additions & 23 deletions README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,9 @@ formats it with standard visual aid symbols for display purposes.
Args:

- cnpj (str): The CNPJ string to be formatted for display.
- 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:

Expand All @@ -253,33 +256,12 @@ Example:
>>> from brutils import format_cnpj
>>> format_cnpj("03560714000142")
'03.560.714/0001-42'
>>> format_cnpj("03.560.714/0001-42", only_nums=True)
'03560714000142'
>>> format_cnpj("98765432100100")
None
```

### remove_symbols_cnpj

Removes specific symbols from a CNPJ (Brazilian Company Registration Number)
string.
This function takes a CNPJ string as input and removes all occurrences of
the '.', '/' and '-' characters from it.

Args:

- cnpj (str): The CNPJ string containing symbols to be removed.

Returns:

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

Example:

```python
>>> from brutils import remove_symbols_cnpj
>>> remove_symbols_cnpj('00.111.222/0001-00')
'00111222000100'
```

### generate_cnpj

Generates a random valid CNPJ (Brazilian Company Registration Number) digit
Expand Down
1 change: 0 additions & 1 deletion brutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from brutils.cnpj import format_cnpj
from brutils.cnpj import generate as generate_cnpj
from brutils.cnpj import is_valid as is_valid_cnpj
from brutils.cnpj import remove_symbols as remove_symbols_cnpj

# CPF Imports
from brutils.cpf import format_cpf
Expand Down
1 change: 1 addition & 0 deletions brutils/cep.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ def format_cep(cep: str, only_nums=False) -> str | None:

Args:
cep (str): The input CEP (Postal Code) to be formatted.
only_nums (bool, optional): Returns only numbers if the value is True

Returns:
str: The formatted CEP in the "12345-678" format if it's valid,
Expand Down
66 changes: 35 additions & 31 deletions brutils/cnpj.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from itertools import chain
from random import randint

# FORMATTING
# LEGACY BACKWARDS COMPATIBILITY
############


Expand Down Expand Up @@ -33,27 +33,6 @@ def sieve(dirty: str) -> str:
return "".join(filter(lambda char: char not in "./-", dirty))


def remove_symbols(dirty: str) -> str:
"""
This function is an alias for the `sieve` function, offering a more
descriptive name.

Args:
dirty (str): The dirty string containing symbols to be removed.

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

Example:
>>> remove_symbols("12.345/6789-01")
"12345678901"
>>> remove_symbols("98/76.543-2101")
"98765432101"
"""

return sieve(dirty)


def display(cnpj: str) -> str | None:
"""
Will format an adequately formatted numbers-only CNPJ string,
Expand Down Expand Up @@ -90,34 +69,55 @@ def display(cnpj: str) -> str | None:
)


def format_cnpj(cnpj: str) -> str | None:
# FORMATTING
############


def format_cnpj(cnpj: str, only_nums=False) -> str | None:
"""
Formats a CNPJ (Brazilian Company Registration Number) string for visual
display.

This function takes a CNPJ string as input, validates its format, and
formats it with standard visual aid symbols for display purposes.
This function takes a CNPJ string as input and,
- Removes special characteres;
- Check if the string follows the CNPJ length pattern;
- Returns None if the string is out of pattern;
- Return a string with the formatted CNPJ.

Args:
cnpj (str): The CNPJ string to be formatted for display.
cnpj (str): The CNPJ string to be formatted.
only_nums (bool, optional): Returns only numbers if the value is True

Returns:
str: The formatted CNPJ with visual aid symbols if it's valid,
str: The formatted CNPJ if it's valid,
None if it's not valid.

Example:
>>> format_cnpj("03560714000142")
'03.560.714/0001-42'
>>> format_cnpj("03.560.714/0001-42", only_nums=True)
'03560714000142'
>>> format_cnpj("98765432100100")
None
"""
### Checking data type
if not isinstance(cnpj, str):
return None

if not is_valid(cnpj):
### Removing special characteres
cnpj = "".join(filter(str.isalnum, cnpj))

### Checking math validation
if not validate(cnpj):
return None

return "{}.{}.{}/{}-{}".format(
cnpj[:2], cnpj[2:5], cnpj[5:8], cnpj[8:12], cnpj[12:14]
)
### Returning CNPJ value
if only_nums:
return cnpj
else:
return "{}.{}.{}/{}-{}".format(
cnpj[:2], cnpj[2:5], cnpj[5:8], cnpj[8:12], cnpj[12:14]
)


# OPERATIONS
Expand Down Expand Up @@ -178,6 +178,10 @@ def is_valid(cnpj: str) -> bool:
True
>>> is_valid("00111222000133")
False

.. note::
This method should not be used in new code and is only provided for
backward compatibility.
"""

return isinstance(cnpj, str) and validate(cnpj)
Expand Down
35 changes: 17 additions & 18 deletions tests/test_cnpj.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
format_cnpj,
generate,
is_valid,
remove_symbols,
sieve,
validate,
)
Expand All @@ -31,6 +30,14 @@ def test_display(self):
self.assertIsNone(display("0000000000000"))
self.assertIsNone(display("0000000000000a"))

def test_format_cnpj(self):
self.assertEqual(format_cnpj("11862986000125"), "11.862.986/0001-25")
self.assertEqual(
format_cnpj("50.715.656/0001-69", only_nums=True), "50715656000169"
)
self.assertIsNone(format_cnpj("0000000000000"))
self.assertIsNone(format_cnpj("0000000000"))

def test_validate(self):
self.assertIs(validate("34665388000161"), True)
self.assertIs(validate("52599927000100"), False)
Expand Down Expand Up @@ -83,30 +90,22 @@ def test__checksum(self):
self.assertEqual(_checksum("52513127000299"), "99")


@patch("brutils.cnpj.sieve")
class TestRemoveSymbols(TestCase):
def test_remove_symbols(self, mock_sieve):
# When call remove_symbols, it calls sieve
remove_symbols("12.345.678/0001-90")
mock_sieve.assert_called()


@patch("brutils.cnpj.is_valid")
@patch("brutils.cnpj.validate")
class TestIsValidToFormat(TestCase):
def test_when_cnpj_is_valid_returns_true_to_format(self, mock_is_valid):
mock_is_valid.return_value = True
def test_when_cnpj_is_valid_returns_true_to_format(self, mock_validate):
mock_validate.return_value = True

# When cnpj is_valid, returns formatted cnpj
self.assertEqual(format_cnpj("01838723000127"), "01.838.723/0001-27")

# Checks if function is_valid_cnpj is called
mock_is_valid.assert_called_once_with("01838723000127")
# Checks if function validate_cnpj is called
mock_validate.assert_called_once_with("01838723000127")

def test_when_cnpj_is_not_valid_returns_none(self, mock_is_valid):
mock_is_valid.return_value = False
def test_when_cnpj_is_not_valid_returns_none(self, mock_validate):
mock_validate.return_value = False

# When cnpj isn't valid, returns None
self.assertIsNone(format_cnpj("01838723000127"))
# When cnpj isn't valid, returns False
self.assertFalse(format_cnpj("01838723000127"))


if __name__ == "__main__":
Expand Down
Loading