Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
e421ed8
refactor(mocker): renamed certificate attr
wellfernandes Mar 21, 2026
7ba132d
refactor(certificate-generator): simplified func names
wellfernandes Mar 21, 2026
a3486e2
feat(certificate): adjusted brazilian cert data creation and added er…
wellfernandes Mar 21, 2026
b4e3459
feat: added tags for error internationalization
wellfernandes Mar 21, 2026
3ea70d6
refactor(error): adjusted error returns
wellfernandes Mar 21, 2026
02b4c56
feat: added error translations for ptbr
wellfernandes Mar 21, 2026
2cee36a
refactor(certificate): adjusted brazilian cert generation
wellfernandes Mar 21, 2026
950c0b6
refactor(certificate): adjusted brazilian cert generation
wellfernandes Mar 21, 2026
444df09
refactor(address): adjusted address generation
wellfernandes Mar 21, 2026
091466b
refactor(company): adjusted brazilian company generation
wellfernandes Mar 21, 2026
7afa03a
refactor(company): adjusted company creation generation
wellfernandes Mar 21, 2026
00b8136
refactor(cpf): adjusted cpf generation
wellfernandes Mar 21, 2026
9b194f2
refactor(cpf): adjusted cpf validator
wellfernandes Mar 21, 2026
7e50f43
refactor(gender): adjusted gender generation
wellfernandes Mar 21, 2026
c546895
refactor(rg): adjusted rg document generation
wellfernandes Mar 21, 2026
ae3e34d
refactor(rg): adjusted rg document generation
wellfernandes Mar 21, 2026
afaca89
refactor(person): adjusted person generation
wellfernandes Mar 21, 2026
34c6ca0
refactor(phone): adjusted phone data generation
wellfernandes Mar 21, 2026
cf2ec43
refactor: adjusted brazilian voter card generation
wellfernandes Mar 21, 2026
726c140
refactor(voter-registration): adjusted voter registration generation
wellfernandes Mar 21, 2026
2e96812
refactor: adjusted ptbr translation list
wellfernandes Mar 21, 2026
ab00171
refactor: adjusted translation registration logic
wellfernandes Mar 21, 2026
134b22d
test: updated company generator tests
wellfernandes Mar 21, 2026
a4c6dd1
refactor(mocker): adjusted main generation file for mocai mock
wellfernandes Mar 21, 2026
b3917c0
docs(example): adjusted mocai usage examples
wellfernandes Mar 21, 2026
5d21ecb
docs(readme): update main readme
wellfernandes Mar 21, 2026
82933a4
docs(readme): update ptbr readme
wellfernandes Mar 21, 2026
0102eaf
docs(readme): update main readme
wellfernandes Mar 21, 2026
0fbbe3f
docs(readme): update ptbr readme
wellfernandes Mar 21, 2026
076b2be
refactor(company): ensure reproducibility using injected random sourc…
wellfernandes Mar 21, 2026
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
115 changes: 80 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,82 +7,127 @@
A Go library for generating test data, allowing for the simple and efficient creation of mocks for entities.

## 📖 Description
**Mocaí** is an open-source library in Go designed to simplify the generation of mocks for entities such as Person, Address, Phone, and many others. Our goal is to make the development and testing of applications more efficient by providing random yet consistent data that simulates real-world scenarios in a practical and reliable manner.
**Mocaí** is an open-source Go library designed to simplify the generation of realistic mock data for entities such as Person, Address, Phone, Company, CPF, CNPJ, Certificates, National ID (RG), and Voter Registration. The goal is to make development and testing more efficient by providing random yet consistent data that simulates real-world scenarios in a practical and reliable way.

## 🌟 Curiosity about the Name
The name Mocaí is a tribute to the Brazilian initiative behind the library. It originated from the combination of "mock" (the English term for simulation or fictitious data) with "açaí," a typical fruit from the Brazilian Amazon, known for its energy and versatility. Just as açaí is essential for many Brazilians, Mocaí aims to be an essential tool for developers who need efficient and high-quality test data. 🇧🇷
The name Mocaí is a tribute to the Brazilian initiative behind the library. It originated from the combination of "mock" (simulation or fake data) with "açaí," a typical fruit from the Brazilian Amazon, known for its energy and versatility. Just as açaí is essential for many Brazilians, Mocaí aims to be an essential tool for developers who need efficient and high-quality test data. 🇧🇷

## 🛠️ Main Features
- **Random Data Generation:** Create mocks of entities with varied and realistic data.
- **Consistency:** Ensure that the generated data is consistent and suitable for testing.
- **Ease of Use:** Simple and intuitive interface for quick integration into your projects.
- **Extensibility:** Add new entities or customize existing ones according to your needs.
- **Random Data Generation:** Generate mocks for entities with varied and realistic data (Person, Address, Phone, Company, CPF, CNPJ, Certificates, National ID, Voter Registration, and more).
- **Consistency:** Ensures generated data is consistent and suitable for testing.
- **Ease of Use:** Simple and intuitive API for quick integration.
- **Extensibility:** Easily add new entities or languages. The architecture is modular and ready for expansion.
- **Open Source:** Collaborate, suggest improvements, and contribute to the growth of the library.

## 📦 Supported Entities
- Person (with gender, age, CPF)
- Address (street, number, city, state, UF, ZIP)
- Phone (area code, number)
- Company (name, CNPJ)
- CPF (Brazilian individual taxpayer registry)
- CNPJ (Brazilian company registry)
- Certificates (Birth, Marriage, Death)
- National ID (RG)
- Voter Registration (Título de Eleitor)

## 🌐 Language Support
- **ptbr** (Brazilian Portuguese) is currently supported. The structure allows for easy addition of new languages in the future.

## 🚀 Why Use Mocaí?
- **Productivity:** Reduce the time spent on creating test data.
- **Quality:** Improve the coverage and effectiveness of your tests with realistic data.
- **Flexibility:** Adapt the mocks to the specific needs of your project.
- **Productivity:** Reduce the time spent creating test data.
- **Quality:** Improve test coverage and effectiveness with realistic data.
- **Flexibility:** Adapt mocks to your project's specific needs.
- **Community:** Be part of an open-source community that values collaboration and innovation.

## ⚙️ Requirements
- Go 1.23.4 or higher

## 🚀 How to Get Started
### Installation
To start using Mocaí, install the library with the following command:
To start using Mocaí, install the library with:

```
```sh
go get github.com/brazzcore/mocai
```

Basic Usage
Import the library into your project and start generating mocks:
### Basic Usage
Import the library and generate mocks using the `Mocker` struct methods:

```go
// Create a Mocker instance for Portuguese
ptMocker, err := mocai.NewMocker("ptbr", true)
if err != nil {
log.Fatal(err)
package main

import (
"fmt"
"log"
"github.com/brazzcore/mocai/pkg/mocai"
)

func main() {
// Create a Mocker instance for Brazilian Portuguese
mocker := mocai.NewMocker("ptbr", true, nil) // isFormatted: true for formatted docs (e.g., CPF/CNPJ)

// Generate a mock address
address, err := mocker.NewAddress()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Address: %s, %d - %s, %s (%s) - %s\n", address.Street, address.Number, address.City, address.State, address.UF, address.ZIP)

// Generate a mock person
person, err := mocker.NewPerson()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Person: %s %s, Gender: %s, Age: %d, CPF: %s\n", person.FirstNameMale, person.LastName, person.Gender.Identity, person.Age, person.CPF.Number)

// Generate a mock company
company, err := mocker.NewCompany()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Company: %s, CNPJ: %s\n", company.BrazilianCompany.Name, company.BrazilianCompany.CNPJ)
}
```

// Access mock data
fmt.Printf("Address: %s\n", ptMocker.Address.Street)
fmt.Printf("Phone: %s\n", ptMocker.Phone.Number)
> **Note:** Each call to a method like `NewPerson()` or `NewAddress()` generates a new mock with random data. The `Mocker` instance is immutable regarding its configuration (language, formatting, random source).

// For data in a different language, create a new instance
enMocker, err := mocai.NewMocker("en", true)
if err != nil {
log.Fatal(err)
}
```
#### About Languages
Currently, only "ptbr" is implemented. To support other languages, contribute with new translation and mock data files.

> **Important**: Each Mocker instance is immutable and contains data in the language specified at creation time. To get data in a different language, always create a new instance using NewMocker.
#### About Formatting
The `isFormatted` parameter controls whether documents like CPF/CNPJ are returned formatted (e.g., `123.456.789-00`) or as plain numbers (`12345678900`).

### Examples
The ***examples*** folder contains samples of how to use the library:
The ***examples*** folder contains usage samples:

- `mocker/`: Example using a main entry point `mocai.NewMocker(lang string, isFormatted bool)` to generate mocks in a fluent and simplified way.
- `mocker/`: Example using the main entry point `mocai.NewMocker(lang string, isFormatted bool, rnd RandSource)` to generate mocks in a fluent and simplified way.

To run an example, navigate to the desired directory and run:
```
To run an example:
```sh
cd examples/mocker
go run main.go
```

## 🧪 Running Tests
To run all tests:
```sh
go test ./...
```

## 🤝 Contribute
Mocaí is an open-source project, and your contribution is very welcome! Whether it's reporting bugs, suggesting new features, or submitting pull requests, your participation helps improve the library for everyone.

### How to Contribute
1. **Report Issues:** Found a bug or have a suggestion? Open an issue.

2. **Submit Pull Requests:** Follow the contribution guidelines and submit your improvements.

2. **Submit Pull Requests:** Follow the contribution guidelines and submit your improvements. Always run tests before submitting.
3. **Discuss Ideas:** Join discussions and share your ideas for the project.

### Contribution Guidelines
1. Follow the project's coding standards.
2. Add tests for new features.
3. If necessary, document your changes in the **README.md**.

## 📄 Licence
## 📄 License
Mocaí is distributed under the **MIT License**.

### 🌟 Mocaí: Generating mocks, simplifying tests, accelerating development.
Expand Down
111 changes: 78 additions & 33 deletions docs/localization/pt/README-PT.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,76 +3,121 @@
![mocai](../../.././img/mocai.svg)

Uma biblioteca Go para geração de dados de teste, permitindo criar mocks de entidades de forma simples e eficiente.

## 📖 Descrição
**Mocaí** é uma biblioteca open-source em Go projetada para simplificar a geração de mocks de entidades como Pessoa, Endereço, Telefone e muitas outras. Nosso objetivo é tornar o desenvolvimento e teste de aplicações mais eficiente, fornecendo dados aleatórios, porém consistentes, que simulam cenários reais de forma prática e confiável.
**Mocaí** é uma biblioteca open-source em Go projetada para simplificar a geração de dados fictícios realistas para entidades como Pessoa, Endereço, Telefone, Empresa, CPF, CNPJ, Certidões, RG e Título de Eleitor. O objetivo é tornar o desenvolvimento e os testes mais eficientes, fornecendo dados aleatórios, porém consistentes, que simulam cenários reais de forma prática e confiável.

## 🌟 Curiosidade sobre o Nome
O nome Mocai é uma homenagem à iniciativa brasileira por trás da biblioteca. Ele surgiu da combinação de "mock" (termo em inglês para simulação ou dados fictícios) com "açaí", uma fruta típica da Amazônia brasileira, conhecida por sua energia e versatilidade. Assim como o açaí é essencial para muitos brasileiros, o Mocai busca ser uma ferramenta essencial para desenvolvedores que precisam de dados de teste eficientes e de qualidade. 🇧🇷
O nome Mocai é uma homenagem à iniciativa brasileira por trás da biblioteca. Ele surgiu da combinação de "mock" (simulação ou dado fictício) com "açaí", uma fruta típica da Amazônia brasileira, conhecida por sua energia e versatilidade. Assim como o açaí é essencial para muitos brasileiros, o Mocai busca ser uma ferramenta essencial para desenvolvedores que precisam de dados de teste eficientes e de qualidade. 🇧🇷

## 🛠️ Principais Recursos
- **Geração de Dados Aleatórios:** Crie mocks de entidades com dados variados e realistas.
- **Consistência:** Garanta que os dados gerados sejam consistentes e adequados para testes.
- **Facilidade de Uso:** Interface simples e intuitiva para integração rápida em seus projetos.
- **Extensibilidade:** Adicione novas entidades ou personalize as existentes conforme suas necessidades.
- **Geração de Dados Aleatórios:** Gere mocks para entidades com dados variados e realistas (Pessoa, Endereço, Telefone, Empresa, CPF, CNPJ, Certidões, RG, Título de Eleitor e mais).
- **Consistência:** Garante que os dados gerados sejam consistentes e adequados para testes.
- **Facilidade de Uso:** API simples e intuitiva para integração rápida.
- **Extensibilidade:** Adicione facilmente novas entidades ou idiomas. A arquitetura é modular e pronta para expansão.
- **Open Source:** Colabore, sugira melhorias e contribua para o crescimento da biblioteca.

## 📦 Entidades Suportadas
- Pessoa (com gênero, idade, CPF)
- Endereço (rua, número, cidade, estado, UF, CEP)
- Telefone (DDD, número)
- Empresa (nome, CNPJ)
- CPF (Cadastro de Pessoa Física)
- CNPJ (Cadastro Nacional de Pessoa Jurídica)
- Certidões (Nascimento, Casamento, Óbito)
- RG (Identidade)
- Título de Eleitor

## 🌐 Suporte a Idiomas
- **ptbr** (Português do Brasil) atualmente suportado. A estrutura permite fácil adição de novos idiomas no futuro.

## 🚀 Por que usar o Mocai?
- **Produtividade:** Reduza o tempo gasto na criação de dados de teste.
- **Qualidade:** Melhore a cobertura e a eficácia dos seus testes com dados realistas.
- **Flexibilidade:** Adapte os mocks às necessidades específicas do seu projeto.
- **Comunidade:** Faça parte de uma comunidade open-source que valoriza a colaboração e a inovação.

## ⚙️ Requisitos
- Go 1.23.4 ou superior

## 🚀 Como Começar
### Instalação
Para começar a usar o Mocai, instale a biblioteca com o seguinte comando:
Para começar a usar o Mocai, instale a biblioteca com:

```
```sh
go get github.com/brazzcore/mocai
```

Uso Básico
Importe a biblioteca em seu projeto e comece a gerar mocks:
### Uso Básico
Importe a biblioteca e gere mocks usando os métodos da struct `Mocker`:

```go
// Cria uma instância do Mocker para português
ptMocker, err := mocai.NewMocker("ptbr", true)
if err != nil {
log.Fatal(err)
package main

import (
"fmt"
"log"
"github.com/brazzcore/mocai/pkg/mocai"
)

func main() {
// Cria uma instância do Mocker para português do Brasil
mocker := mocai.NewMocker("ptbr", true, nil) // isFormatted: true para documentos formatados (ex: CPF/CNPJ)

// Gera um endereço fictício
address, err := mocker.NewAddress()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Endereço: %s, %d - %s, %s (%s) - %s\n", address.Street, address.Number, address.City, address.State, address.UF, address.ZIP)

// Gera uma pessoa fictícia
person, err := mocker.NewPerson()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Pessoa: %s %s, Gênero: %s, Idade: %d, CPF: %s\n", person.FirstNameMale, person.LastName, person.Gender.Identity, person.Age, person.CPF.Number)

// Gera uma empresa fictícia
company, err := mocker.NewCompany()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Empresa: %s, CNPJ: %s\n", company.BrazilianCompany.Name, company.BrazilianCompany.CNPJ)
}
```

// Acessa os dados mock
fmt.Printf("Endereço: %s\n", ptMocker.Address.Street)
fmt.Printf("Telefone: %s\n", ptMocker.Phone.Number)
> **Nota:** Cada chamada de método como `NewPerson()` ou `NewAddress()` gera um novo mock com dados aleatórios. A instância do `Mocker` é imutável quanto à configuração (idioma, formatação, fonte de aleatoriedade).

// Para dados em outro idioma, crie uma nova instância
enMocker, err := mocai.NewMocker("en", true)
if err != nil {
log.Fatal(err)
}
```
#### Sobre Idiomas
Atualmente, apenas "ptbr" está implementado. Para suportar outros idiomas, contribua com novos arquivos de tradução e mocks.

> **Importante**: Cada instância do Mocker é imutável e contém dados no idioma especificado no momento da criação. Para obter dados em um idioma diferente, sempre crie uma nova instância usando NewMocker.
#### Sobre Formatação
O parâmetro `isFormatted` controla se documentos como CPF/CNPJ são retornados formatados (ex: `123.456.789-00`) ou apenas números (`12345678900`).

### Exemplos
O diretório ***examples*** contém exemplos de como usar a biblioteca:
O diretório ***examples*** contém exemplos de uso:

- `mocker/`: Exemplo usando um ponto de entrada principal `mocai.NewMocker(lang string, isFormatted bool)` para gerar mocks de maneira fluida e simplificada.
- `mocker/`: Exemplo usando o ponto de entrada principal `mocai.NewMocker(lang string, isFormatted bool, rnd RandSource)` para gerar mocks de maneira fluida e simplificada.

Para executar um exemplo, acesse o diretório desejado e execute:
```
Para executar um exemplo:
```sh
cd examples/mocker
go run main.go
```

## 🧪 Rodando os Testes
Para rodar todos os testes:
```sh
go test ./...
```

## 🤝 Contribua
O Mocai é um projeto open-source, e sua contribuição é muito bem-vinda! Seja reportando bugs, sugerindo novas funcionalidades ou enviando pull requests, sua participação ajuda a melhorar a biblioteca para todos.

### Como Contribuir
1. **Reporte Problemas:** Encontrou um bug ou tem uma sugestão? Abra uma issue.

2. **Envie Pull Requests:** Siga as diretrizes de contribuição e envie suas melhorias.

2. **Envie Pull Requests:** Siga as diretrizes de contribuição e envie suas melhorias. Sempre rode os testes antes de enviar.
3. **Discuta Ideias:** Participe das discussões e compartilhe suas ideias para o projeto.

### Diretrizes de Contribuição
Expand All @@ -81,7 +126,7 @@ O Mocai é um projeto open-source, e sua contribuição é muito bem-vinda! Seja
3. Caso necessário, documente suas alterações no **README.md**.

## 📄 Licença
O Mocai é distribuído sob a **licença MIT**.
O Mocai é distribuído sob a **MIT License**.

### 🌟 Mocai: Gerando mocks, simplificando testes, acelerando desenvolvimento.
Seja bem-vindo ao projeto e sinta-se à vontade para explorar, usar e contribuir!
Expand Down
20 changes: 10 additions & 10 deletions examples/mocker/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"fmt"
"log"

"github.com/brazzcore/mocai/internal/cli"
"github.com/brazzcore/mocai/pkg/mocai"
Expand All @@ -13,17 +12,18 @@ func main() {
fmt.Println(cli.HeaderMain)
fmt.Println(cli.SubHeader)

// Initialize mocai and set a supported language
// If the language is not available, the default language pt-BR will be set
m, err := mocai.NewMocker("ptbr", true)
m := mocai.NewMocker("ptbr", true, nil)

address, err := m.NewAddress()
if err != nil {
log.Println(err)
fmt.Println(err)
} else {
fmt.Printf("Address: %s, %d - %s, %s (%s) - %s\n",
address.Street, address.Number, address.City, address.State, address.UF, address.ZIP)
}
// Generate mock data
// You can select which entity attributes to use
// by accessing the entity and its fields
fmt.Printf("Address: %s, %d - %s, %s (%s) - %s\n",
m.Address.Street, m.Address.Number, m.Address.City, m.Address.State, m.Address.UF, m.Address.ZIP)

certificate, _ := m.NewCertificate()
fmt.Println("Brazilian birth certificate:", certificate.Brazil.BirthCertificate.Number)

fmt.Println(cli.Footer)
}
Loading
Loading