Skip to content

Commit d2bc7b9

Browse files
Merge pull request #52 from brazzcore/feature/51-standardize-country-specific-struct-naming-convention
[Feature/51] :: standardize country specific struct naming convention
2 parents bb343f1 + 076b2be commit d2bc7b9

File tree

30 files changed

+651
-572
lines changed

30 files changed

+651
-572
lines changed

README.md

Lines changed: 80 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -7,82 +7,127 @@
77
A Go library for generating test data, allowing for the simple and efficient creation of mocks for entities.
88

99
## 📖 Description
10-
**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.
10+
**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.
1111

1212
## 🌟 Curiosity about the Name
13-
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. 🇧🇷
13+
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. 🇧🇷
1414

1515
## 🛠️ Main Features
16-
- **Random Data Generation:** Create mocks of entities with varied and realistic data.
17-
- **Consistency:** Ensure that the generated data is consistent and suitable for testing.
18-
- **Ease of Use:** Simple and intuitive interface for quick integration into your projects.
19-
- **Extensibility:** Add new entities or customize existing ones according to your needs.
16+
- **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).
17+
- **Consistency:** Ensures generated data is consistent and suitable for testing.
18+
- **Ease of Use:** Simple and intuitive API for quick integration.
19+
- **Extensibility:** Easily add new entities or languages. The architecture is modular and ready for expansion.
2020
- **Open Source:** Collaborate, suggest improvements, and contribute to the growth of the library.
2121

22+
## 📦 Supported Entities
23+
- Person (with gender, age, CPF)
24+
- Address (street, number, city, state, UF, ZIP)
25+
- Phone (area code, number)
26+
- Company (name, CNPJ)
27+
- CPF (Brazilian individual taxpayer registry)
28+
- CNPJ (Brazilian company registry)
29+
- Certificates (Birth, Marriage, Death)
30+
- National ID (RG)
31+
- Voter Registration (Título de Eleitor)
32+
33+
## 🌐 Language Support
34+
- **ptbr** (Brazilian Portuguese) is currently supported. The structure allows for easy addition of new languages in the future.
35+
2236
## 🚀 Why Use Mocaí?
23-
- **Productivity:** Reduce the time spent on creating test data.
24-
- **Quality:** Improve the coverage and effectiveness of your tests with realistic data.
25-
- **Flexibility:** Adapt the mocks to the specific needs of your project.
37+
- **Productivity:** Reduce the time spent creating test data.
38+
- **Quality:** Improve test coverage and effectiveness with realistic data.
39+
- **Flexibility:** Adapt mocks to your project's specific needs.
2640
- **Community:** Be part of an open-source community that values collaboration and innovation.
2741

42+
## ⚙️ Requirements
43+
- Go 1.23.4 or higher
2844

2945
## 🚀 How to Get Started
3046
### Installation
31-
To start using Mocaí, install the library with the following command:
47+
To start using Mocaí, install the library with:
3248

33-
```
49+
```sh
3450
go get github.com/brazzcore/mocai
3551
```
3652

37-
Basic Usage
38-
Import the library into your project and start generating mocks:
53+
### Basic Usage
54+
Import the library and generate mocks using the `Mocker` struct methods:
3955

4056
```go
41-
// Create a Mocker instance for Portuguese
42-
ptMocker, err := mocai.NewMocker("ptbr", true)
43-
if err != nil {
44-
log.Fatal(err)
57+
package main
58+
59+
import (
60+
"fmt"
61+
"log"
62+
"github.com/brazzcore/mocai/pkg/mocai"
63+
)
64+
65+
func main() {
66+
// Create a Mocker instance for Brazilian Portuguese
67+
mocker := mocai.NewMocker("ptbr", true, nil) // isFormatted: true for formatted docs (e.g., CPF/CNPJ)
68+
69+
// Generate a mock address
70+
address, err := mocker.NewAddress()
71+
if err != nil {
72+
log.Fatal(err)
73+
}
74+
fmt.Printf("Address: %s, %d - %s, %s (%s) - %s\n", address.Street, address.Number, address.City, address.State, address.UF, address.ZIP)
75+
76+
// Generate a mock person
77+
person, err := mocker.NewPerson()
78+
if err != nil {
79+
log.Fatal(err)
80+
}
81+
fmt.Printf("Person: %s %s, Gender: %s, Age: %d, CPF: %s\n", person.FirstNameMale, person.LastName, person.Gender.Identity, person.Age, person.CPF.Number)
82+
83+
// Generate a mock company
84+
company, err := mocker.NewCompany()
85+
if err != nil {
86+
log.Fatal(err)
87+
}
88+
fmt.Printf("Company: %s, CNPJ: %s\n", company.BrazilianCompany.Name, company.BrazilianCompany.CNPJ)
4589
}
90+
```
4691

47-
// Access mock data
48-
fmt.Printf("Address: %s\n", ptMocker.Address.Street)
49-
fmt.Printf("Phone: %s\n", ptMocker.Phone.Number)
92+
> **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).
5093
51-
// For data in a different language, create a new instance
52-
enMocker, err := mocai.NewMocker("en", true)
53-
if err != nil {
54-
log.Fatal(err)
55-
}
56-
```
94+
#### About Languages
95+
Currently, only "ptbr" is implemented. To support other languages, contribute with new translation and mock data files.
5796

58-
> **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.
97+
#### About Formatting
98+
The `isFormatted` parameter controls whether documents like CPF/CNPJ are returned formatted (e.g., `123.456.789-00`) or as plain numbers (`12345678900`).
5999

60100
### Examples
61-
The ***examples*** folder contains samples of how to use the library:
101+
The ***examples*** folder contains usage samples:
62102

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

65-
To run an example, navigate to the desired directory and run:
66-
```
105+
To run an example:
106+
```sh
107+
cd examples/mocker
67108
go run main.go
68109
```
69110

111+
## 🧪 Running Tests
112+
To run all tests:
113+
```sh
114+
go test ./...
115+
```
116+
70117
## 🤝 Contribute
71118
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.
72119

73120
### How to Contribute
74121
1. **Report Issues:** Found a bug or have a suggestion? Open an issue.
75-
76-
2. **Submit Pull Requests:** Follow the contribution guidelines and submit your improvements.
77-
122+
2. **Submit Pull Requests:** Follow the contribution guidelines and submit your improvements. Always run tests before submitting.
78123
3. **Discuss Ideas:** Join discussions and share your ideas for the project.
79124

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

85-
## 📄 Licence
130+
## 📄 License
86131
Mocaí is distributed under the **MIT License**.
87132

88133
### 🌟 Mocaí: Generating mocks, simplifying tests, accelerating development.

docs/localization/pt/README-PT.md

Lines changed: 78 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,76 +3,121 @@
33
![mocai](../../.././img/mocai.svg)
44

55
Uma biblioteca Go para geração de dados de teste, permitindo criar mocks de entidades de forma simples e eficiente.
6-
6+
77
## 📖 Descrição
8-
**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.
8+
**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.
99

1010
## 🌟 Curiosidade sobre o Nome
11-
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. 🇧🇷
11+
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. 🇧🇷
1212

1313
## 🛠️ Principais Recursos
14-
- **Geração de Dados Aleatórios:** Crie mocks de entidades com dados variados e realistas.
15-
- **Consistência:** Garanta que os dados gerados sejam consistentes e adequados para testes.
16-
- **Facilidade de Uso:** Interface simples e intuitiva para integração rápida em seus projetos.
17-
- **Extensibilidade:** Adicione novas entidades ou personalize as existentes conforme suas necessidades.
14+
- **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).
15+
- **Consistência:** Garante que os dados gerados sejam consistentes e adequados para testes.
16+
- **Facilidade de Uso:** API simples e intuitiva para integração rápida.
17+
- **Extensibilidade:** Adicione facilmente novas entidades ou idiomas. A arquitetura é modular e pronta para expansão.
1818
- **Open Source:** Colabore, sugira melhorias e contribua para o crescimento da biblioteca.
1919

20+
## 📦 Entidades Suportadas
21+
- Pessoa (com gênero, idade, CPF)
22+
- Endereço (rua, número, cidade, estado, UF, CEP)
23+
- Telefone (DDD, número)
24+
- Empresa (nome, CNPJ)
25+
- CPF (Cadastro de Pessoa Física)
26+
- CNPJ (Cadastro Nacional de Pessoa Jurídica)
27+
- Certidões (Nascimento, Casamento, Óbito)
28+
- RG (Identidade)
29+
- Título de Eleitor
30+
31+
## 🌐 Suporte a Idiomas
32+
- **ptbr** (Português do Brasil) atualmente suportado. A estrutura permite fácil adição de novos idiomas no futuro.
33+
2034
## 🚀 Por que usar o Mocai?
2135
- **Produtividade:** Reduza o tempo gasto na criação de dados de teste.
2236
- **Qualidade:** Melhore a cobertura e a eficácia dos seus testes com dados realistas.
2337
- **Flexibilidade:** Adapte os mocks às necessidades específicas do seu projeto.
2438
- **Comunidade:** Faça parte de uma comunidade open-source que valoriza a colaboração e a inovação.
2539

40+
## ⚙️ Requisitos
41+
- Go 1.23.4 ou superior
2642

2743
## 🚀 Como Começar
2844
### Instalação
29-
Para começar a usar o Mocai, instale a biblioteca com o seguinte comando:
45+
Para começar a usar o Mocai, instale a biblioteca com:
3046

31-
```
47+
```sh
3248
go get github.com/brazzcore/mocai
3349
```
3450

35-
Uso Básico
36-
Importe a biblioteca em seu projeto e comece a gerar mocks:
51+
### Uso Básico
52+
Importe a biblioteca e gere mocks usando os métodos da struct `Mocker`:
3753

3854
```go
39-
// Cria uma instância do Mocker para português
40-
ptMocker, err := mocai.NewMocker("ptbr", true)
41-
if err != nil {
42-
log.Fatal(err)
55+
package main
56+
57+
import (
58+
"fmt"
59+
"log"
60+
"github.com/brazzcore/mocai/pkg/mocai"
61+
)
62+
63+
func main() {
64+
// Cria uma instância do Mocker para português do Brasil
65+
mocker := mocai.NewMocker("ptbr", true, nil) // isFormatted: true para documentos formatados (ex: CPF/CNPJ)
66+
67+
// Gera um endereço fictício
68+
address, err := mocker.NewAddress()
69+
if err != nil {
70+
log.Fatal(err)
71+
}
72+
fmt.Printf("Endereço: %s, %d - %s, %s (%s) - %s\n", address.Street, address.Number, address.City, address.State, address.UF, address.ZIP)
73+
74+
// Gera uma pessoa fictícia
75+
person, err := mocker.NewPerson()
76+
if err != nil {
77+
log.Fatal(err)
78+
}
79+
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)
80+
81+
// Gera uma empresa fictícia
82+
company, err := mocker.NewCompany()
83+
if err != nil {
84+
log.Fatal(err)
85+
}
86+
fmt.Printf("Empresa: %s, CNPJ: %s\n", company.BrazilianCompany.Name, company.BrazilianCompany.CNPJ)
4387
}
88+
```
4489

45-
// Acessa os dados mock
46-
fmt.Printf("Endereço: %s\n", ptMocker.Address.Street)
47-
fmt.Printf("Telefone: %s\n", ptMocker.Phone.Number)
90+
> **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).
4891
49-
// Para dados em outro idioma, crie uma nova instância
50-
enMocker, err := mocai.NewMocker("en", true)
51-
if err != nil {
52-
log.Fatal(err)
53-
}
54-
```
92+
#### Sobre Idiomas
93+
Atualmente, apenas "ptbr" está implementado. Para suportar outros idiomas, contribua com novos arquivos de tradução e mocks.
5594

56-
> **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.
95+
#### Sobre Formatação
96+
O parâmetro `isFormatted` controla se documentos como CPF/CNPJ são retornados formatados (ex: `123.456.789-00`) ou apenas números (`12345678900`).
5797

5898
### Exemplos
59-
O diretório ***examples*** contém exemplos de como usar a biblioteca:
99+
O diretório ***examples*** contém exemplos de uso:
60100

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

63-
Para executar um exemplo, acesse o diretório desejado e execute:
64-
```
103+
Para executar um exemplo:
104+
```sh
105+
cd examples/mocker
65106
go run main.go
66107
```
67108

109+
## 🧪 Rodando os Testes
110+
Para rodar todos os testes:
111+
```sh
112+
go test ./...
113+
```
114+
68115
## 🤝 Contribua
69116
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.
70117

71118
### Como Contribuir
72119
1. **Reporte Problemas:** Encontrou um bug ou tem uma sugestão? Abra uma issue.
73-
74-
2. **Envie Pull Requests:** Siga as diretrizes de contribuição e envie suas melhorias.
75-
120+
2. **Envie Pull Requests:** Siga as diretrizes de contribuição e envie suas melhorias. Sempre rode os testes antes de enviar.
76121
3. **Discuta Ideias:** Participe das discussões e compartilhe suas ideias para o projeto.
77122

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

83128
## 📄 Licença
84-
O Mocai é distribuído sob a **licença MIT**.
129+
O Mocai é distribuído sob a **MIT License**.
85130

86131
### 🌟 Mocai: Gerando mocks, simplificando testes, acelerando desenvolvimento.
87132
Seja bem-vindo ao projeto e sinta-se à vontade para explorar, usar e contribuir!

examples/mocker/main.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package main
22

33
import (
44
"fmt"
5-
"log"
65

76
"github.com/brazzcore/mocai/internal/cli"
87
"github.com/brazzcore/mocai/pkg/mocai"
@@ -13,17 +12,18 @@ func main() {
1312
fmt.Println(cli.HeaderMain)
1413
fmt.Println(cli.SubHeader)
1514

16-
// Initialize mocai and set a supported language
17-
// If the language is not available, the default language pt-BR will be set
18-
m, err := mocai.NewMocker("ptbr", true)
15+
m := mocai.NewMocker("ptbr", true, nil)
16+
17+
address, err := m.NewAddress()
1918
if err != nil {
20-
log.Println(err)
19+
fmt.Println(err)
20+
} else {
21+
fmt.Printf("Address: %s, %d - %s, %s (%s) - %s\n",
22+
address.Street, address.Number, address.City, address.State, address.UF, address.ZIP)
2123
}
22-
// Generate mock data
23-
// You can select which entity attributes to use
24-
// by accessing the entity and its fields
25-
fmt.Printf("Address: %s, %d - %s, %s (%s) - %s\n",
26-
m.Address.Street, m.Address.Number, m.Address.City, m.Address.State, m.Address.UF, m.Address.ZIP)
24+
25+
certificate, _ := m.NewCertificate()
26+
fmt.Println("Brazilian birth certificate:", certificate.Brazil.BirthCertificate.Number)
2727

2828
fmt.Println(cli.Footer)
2929
}

0 commit comments

Comments
 (0)