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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Utilitário `list_all_legal_nature` [#653](https://github.com/brazilian-utils/python/pull/653)
- Utilitário `is_valid_cnh` [#651](https://github.com/brazilian-utils/brutils-python/pull/651)
- Utilitário `is_valid_renavam` [#652](https://github.com/brazilian-utils/brutils-python/pull/652)
- Utilitário `is_valid_passport` [#579](https://github.com/brazilian-utils/python/issues/579)
- Utilitário `generate_passport` [#579](https://github.com/brazilian-utils/python/issues/579)
- Utilitário `format_passport` [#579](https://github.com/brazilian-utils/python/issues/579)
- Utilitário `remove_symbols_passport` [#579](https://github.com/brazilian-utils/python/issues/579)

### Fixed

Expand Down
96 changes: 95 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ False
```

# Utilitários

- [CPF](#cpf)
- [is\_valid\_cpf](#is_valid_cpf)
- [format\_cpf](#format_cpf)
Expand Down Expand Up @@ -109,6 +108,11 @@ False
- [is_valid_legal_nature](#is_valid_legal_nature)
- [get_legal_nature_description](#get_legal_nature_description)
- [list_all_legal_nature](#list_all_legal_nature)
- [Passaporte](#passaporte)
- [is_valid_passport](#is_valid_passport)
- [format_passport](#format_passport)
- [remove_symbols_passport](#remove_symbols_passport)
- [generate_passport](#generate_passport)

## CPF

Expand Down Expand Up @@ -1446,6 +1450,8 @@ Retorna uma cópia do dicionário completo `{codigo: descricao}`.
True
>>> data["2062"]
'Sociedade Empresária Limitada'
```

## RENAVAM

### is_valid_renavam
Expand Down Expand Up @@ -1473,6 +1479,94 @@ True
False
```

## Passaporte

### is_valid_passport

Verifica se um número de passaporte brasileiro é válido.

Para ser considerado válido, a entrada deve ser uma string contendo exatamente dois caracteres alfabéticos seguidos de exatamente seis dígitos numéricos.

Esta função não verifica se a entrada é um número de passaporte real, pois não existem dígitos verificadores para o passaporte brasileiro.

Argumentos:
- passport (str): A string contendo o número do passaporte a ser verificado.

Retorna:
- bool: True se o número do passaporte for válido (2 letras seguidas de 6 dígitos). False caso contrário.

Exemplo:
```python
>>> from brutils import is_valid_passport
>>> is_valid_passport("Ab123456")
True
>>> is_valid_passport("12345678")
False
>>> is_valid_passport("DC-221345")
False
```
### format_passport

Formata um número de passaporte brasileiro para exibição.

Esta função recebe uma string representando um número de passaporte válido e o retorna formatado (maiúsculas, sem símbolos).

Argumentos:
- passport (str | None): Um número de passaporte brasileiro (minúsculas ou maiúsculas, possivelmente incluindo símbolos)

Retorna:
- str: O número do passaporte formatado (maiúsculas, sem símbolos) ou None se a entrada for inválida

Exemplo:
```python
>>> from brutils import format_passport
>>> format_passport("Ab123456")
AB123456
>>> format_passport("Ab-123456")
AB123456
>>> format_passport("111111")
None
```
### remove_symbols_passport

Remove símbolos ('-', '.' e espaços em branco) de um número de passaporte.

Esta função recebe uma string com um número de passaporte como entrada e remove todas as ocorrências dos caracteres '.', '-' e espaço em branco.

Argumentos:
- passport (str): A string contendo um número de passaporte

Retorna:
- str: O número do passaporte com hífens (-), pontos (.) e espaços em branco ( ) removidos.

Exemplo:
```python
>>> from brutils import remove_symbols_passport
>>> remove_symbols_passport("Ab123456")
Ab123456
>>> remove_symbols_passport("Ab-123456")
Ab123456
>>> remove_symbols_passport("Ab -. 123456")
Ab123456
```
### generate_passport

Gera uma string com um número de passaporte brasileiro válido aleatório.

Esta função gera uma string com um número de passaporte brasileiro aleatório.

Retorna:
- str: Uma string com um número de passaporte válido aleatório.

Exemplo:
```python
>>> from brutils import generate_passport
>>> generate_passport()
"RY393097"
>>> generate_passport()
"ZS840088"
```

# Novos Utilitários e Reportar Bugs

Caso queira sugerir novas funcionalidades ou reportar bugs, basta criar
Expand Down
95 changes: 94 additions & 1 deletion README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ False
```

# Utilities

- [CPF](#cpf)
- [is\_valid\_cpf](#is_valid_cpf)
- [format\_cpf](#format_cpf)
Expand Down Expand Up @@ -108,6 +107,11 @@ False
- [is_valid_legal_nature](#is_valid_legal_nature)
- [get_legal_nature_description](#get_legal_nature_description)
- [list_all_legal_nature](#list_all_legal_nature)
- [Passport](#passport)
- [is_valid_passport](#is_valid_passport)
- [format_passport](#format_passport)
- [remove_symbols_passport](#remove_symbols_passport)
- [generate_passport](#generate_passport)

## CPF

Expand Down Expand Up @@ -1476,6 +1480,95 @@ Example:
True
>>> is_valid_renavam("12345678901")
False
```

## Passport

### is_valid_passport

Checks if a Brazilian passport number is valid.

To be considered valid, the input must be a string containing exactly two alphabetical characters followed by exactly six numerical digits.

This function does not verify is the input is a real passport number, as there are no checksums for the Brazilian passport.

Args:
- passport (str): The string containing the passport number to be checked.

Returns:
- bool: True if the passport number is valid (2 letters followed by 6 digits). False otherwise.

Example:
```python
>>> from brutils import is_valid_passport
>>> is_valid_passport("Ab123456")
True
>>> is_valid_passport("12345678")
False
>>> is_valid_passport("DC-221345")
False
```
### format_passport

Formats a Brazilian passport number for display.

This function takes a string representing a valid passport number and returns it formatted (uppercase, without symbols).

Args:
- passport (str | None): A Brazilian passport number (lower or uppercase, possibly including symbols)

Returns:
- str: The formatted passport number (uppercase, without symbols) or None if the input is invalid

Example:
```python
>>> format_passport("Ab123456")
AB123456
>>> format_passport("Ab-123456")
AB123456
>>> format_passport("111111")
None
```

### remove_symbols_passport

Removes symbols ('-', '.', and whitespaces) from a passport number.

This function takes a passport number string as input and removes all occurrences of
the '.', '-', and whitespace characters from it.

Args:
- passport (str): The string containing a passport number

Returns:
- str: The passport numbers with dashes (-), dots (.), and whitespaces ( ) removed.

Example:
```python
>>> remove_symbols_passport("Ab123456")
Ab123456
>>> remove_symbols_passport("Ab-123456")
Ab123456
>>> remove_symbols_passport("Ab -. 123456")
Ab123456
```

### generate_passport

Generate a random valid Brazilian passport number string.

This function generates a random Brazilian passport number string.

Returns:
- str: A random valid passport number string.

Example:
```python
>>> generate()
"RY393097"
>>> generate()
"ZS840088"
```

# Feature Request and Bug Report

Expand Down
11 changes: 11 additions & 0 deletions brutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@
from brutils.license_plate import is_valid as is_valid_license_plate
from brutils.license_plate import remove_symbols as remove_symbols_license_plate

# Passport Imports
from brutils.passport import format_passport
from brutils.passport import generate as generate_passport
from brutils.passport import is_valid as is_valid_passport
from brutils.passport import remove_symbols as remove_symbols_passport

# Phone Imports
from brutils.phone import (
format_phone,
Expand Down Expand Up @@ -155,4 +161,9 @@
"is_valid_legal_nature",
"get_natureza_legal_nature",
"list_all_legal_nature",
# Passport
"is_valid_passport",
"remove_symbols_passport",
"format_passport",
"generate_passport",
]
107 changes: 107 additions & 0 deletions brutils/passport.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import random
import re
import string


def is_valid(passport: str) -> bool:
"""
Checks if a Brazilian passport number is valid.

To be considered valid, the input must be a string containing exactly two alphabetical characters followed by exactly six numerical digits.

This function does not verify is the input is a real passport number, as there are no checksums for the Brazilian passport.

Args:
passport (str): The string containing the passport number to be checked.

Returns:
bool: True if the passport number is valid (2 letters followed by 6 digits). False otherwise.

Example:
>>> is_valid("Ab123456")
True
>>> is_valid("12345678")
False
>>> is_valid("DC-221345")
False
"""

if not isinstance(passport, str):
return False

pattern = re.compile("^[A-Z]{2}[0-9]{6}$")
match = re.match(pattern, passport)
return match is not None


def remove_symbols(passport: str) -> str:
"""
Removes symbols ('-', '.', and whitespaces) from a passport number.

This function takes a passport number string as input and removes all occurrences of
the '.', '-', and whitespace characters from it.

Args:
passport (str): The string containing a passport number

Returns:
str: The passport numbers with dashes (-), dots (.), and whitespaces ( ) removed.

Example:
>>> remove_symbols("Ab123456")
Ab123456
>>> remove_symbols("Ab-123456")
Ab123456
>>> remove_symbols("Ab -. 123456")
Ab123456
"""

return "".join(filter(lambda c: c not in ".- ", passport))


def format_passport(passport: str) -> str | None:
"""
Formats a Brazilian passport number for display.

This function takes a string representing a valid passport number and returns it formatted (uppercase, without symbols).

Args:
passport (str | None): A Brazilian passport number (lower or uppercase, possibly including symbols)

Returns:
str: The formatted passport number (uppercase, without symbols) or None if the input is invalid

Example:
>>> format_passport("Ab123456")
AB123456
>>> format_passport("Ab-123456")
AB123456
>>> format_passport("111111")
None
"""

passport = remove_symbols(passport.upper())

return passport if is_valid(passport) else None


def generate() -> str:
"""
Generate a random valid Brazilian passport number string.

This function generates a random Brazilian passport number string.

Returns:
str: A random valid passport number string.

Example:
>>> generate()
"RY393097"
>>> generate()
"ZS840088"
"""

letters = "".join(random.choices(string.ascii_uppercase, k=2))
digits = "".join(random.choices(string.digits, k=6))

return f"{letters}{digits}"
Loading
Loading