Skip to content

Commit 82096cf

Browse files
Merge pull request #73 from fabianoflorentino/development
Development to Main
2 parents d6e1009 + db7c1f2 commit 82096cf

File tree

6 files changed

+156
-68
lines changed

6 files changed

+156
-68
lines changed

internal/agrupamento_de_dados/topics.go

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,7 @@ const (
2424
// The topics covered include arrays, slices (with various operations), and maps.
2525
func AgrupamentoDeDados() {
2626
fmt.Printf("\n\n08 - Agrupamento de Dados\n")
27-
28-
executeSection("Array")
29-
executeSection("Slice: literal composta")
30-
executeSection("Slice: for range")
31-
executeSection("Slice: fatiando ou deletando de uma fatia")
32-
executeSection("Slice: anexando a uma slice")
33-
executeSection("Slice: make")
34-
executeSection("Slice: multi dimensional")
35-
executeSection("Slice: a surpresa do array subjacente")
36-
executeSection("Maps: introdução")
37-
executeSection("Maps: range e deletando")
27+
listOfTopics()
3828
}
3929

4030
// MenuAgrupamentoDeDados returns a slice of format.MenuOptions, each representing a menu option
@@ -80,6 +70,29 @@ func HelpMeAgrupamentoDeDados() {
8070
format.PrintHelpMe(hlp)
8171
}
8272

73+
// listOfTopics executes each topic in the list.
74+
// It iterates over a predefined list of topics and calls the executeSection
75+
// function for each topic. This function is used to sequentially execute
76+
// and display the content of each section.
77+
func listOfTopics() {
78+
listOfTopics := []string{
79+
"Array",
80+
"Slice: literal composta",
81+
"Slice: for range",
82+
"Slice: fatiando ou deletando de uma fatia",
83+
"Slice: anexando a uma slice",
84+
"Slice: make",
85+
"Slice: multi dimensional",
86+
"Slice: a surpresa do array subjacente",
87+
"Maps: introdução",
88+
"Maps: range e deletando",
89+
}
90+
91+
for _, topic := range listOfTopics {
92+
executeSection(topic)
93+
}
94+
}
95+
8396
// executeSection formats and processes a specific section of data.
8497
// It takes a section name as a string parameter and uses the FormatSection
8598
// function from the format package to format the section within the root directory.

internal/aplicacoes/topics.go

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,25 +15,12 @@ const (
1515
rootDir = "internal/aplicacoes"
1616
)
1717

18-
// Aplicacoes prints the title of Chapter 16 and executes a series of sections related to various topics.
19-
// The sections include:
20-
// - JSON Documentation
21-
// - JSON marshal (ordering)
22-
// - JSON unmarshal (disordering)
23-
// - The Writer interface
24-
// - The sort package
25-
// - Customizing sort
26-
// - bcrypt
18+
// Aplicacoes prints the chapter title and executes a series of sections
19+
// related to various topics such as JSON handling, interfaces, sorting,
20+
// and encryption using bcrypt.
2721
func Aplicacoes() {
2822
fmt.Printf("\n\nCapítulo 16: Aplicações\n")
29-
30-
executeSections("Documentação JSON")
31-
executeSections("JSON marshal (ordenação)")
32-
executeSections("JSON unmarshal (desornação)")
33-
executeSections("A interface Writer")
34-
executeSections("O pacote sort")
35-
executeSections("Customizando sort")
36-
executeSections("bcrypt")
23+
listOfTopics()
3724
}
3825

3926
// MenuAplicacoes returns a slice of format.MenuOptions, each representing a different command-line option
@@ -80,6 +67,22 @@ func HelpMeAplicacoes() {
8067
format.PrintHelpMe(hlp)
8168
}
8269

70+
func listOfTopics() {
71+
listOfTopics := []string{
72+
"Documentação JSON",
73+
"JSON marshal (ordenação)",
74+
"JSON unmarshal (desornação)",
75+
"A interface Writer",
76+
"O pacote sort",
77+
"Customizando sort",
78+
"bcrypt",
79+
}
80+
81+
for _, topic := range listOfTopics {
82+
executeSections(topic)
83+
}
84+
}
85+
8386
// executeSections processes a given section by formatting it.
8487
// It takes a section name as a string parameter and applies the FormatSection
8588
// function from the format package to the section, using the rootDir as the base directory.

internal/exercicios_ninja_nivel_11/resolution_exercises_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,33 @@ func TestResolucaoNaPraticaExercicio4(t *testing.T) {
110110
t.Errorf("Expected substring not found.\nWant: %q\nGot: %q", expectedSubstring, result)
111111
}
112112
}
113+
114+
// TestResolucaoNaPraticaExercicio5 tests the function ResolucaoNaPraticaExercicio5
115+
// by capturing its output and comparing it to the expected result. If the output
116+
// does not match the expected result, the test will fail. The expected output
117+
// includes instructions for learning how to write tests in Go and a reference
118+
// to the file where the solution can be found.
119+
func TestResolucaoNaPraticaExercicio5(t *testing.T) {
120+
output := output.New()
121+
result, err := output.Capture(ResolucaoNaPraticaExercicio5)
122+
if err != nil {
123+
logger.Log("Failed to capture output: %v", err)
124+
t.Fatalf("unexpected error: %v", err)
125+
}
126+
127+
expected := `
128+
- Nos capítulos seguintes, uma das coisas que veremos é testes.
129+
- Para testar sua habilidade de se virar por conta própria... desafio:
130+
- Utilizando as seguintes fontes: https://godoc.org/testing & http://www.golang-book.com/books/intro/12
131+
- Tente descobrir por conta própria como funcionam testes em Go.
132+
- Pode usar tradutor automático, pode rodar código na sua máquina, pode procurar no Google. Vale tudo.
133+
- O exercício é: crie um teste simples de uma função ou método ou pedaço qualquer de código.
134+
135+
Resolução: internal/exercicios_ninja_nivel_11/resolution_exercises_test.go
136+
`
137+
trim := trim.New()
138+
139+
if !strings.Contains(trim.String(result), trim.String(expected)) {
140+
t.Errorf(expectTemplate, expected, result)
141+
}
142+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Package exercicios_ninja_nivel_12 contains tests for the exercises of level 12 in the "aprendago" project.
2+
// These tests are designed to validate the solutions to the practical exercises, ensuring that the output
3+
// matches the expected results. The package utilizes various helper packages such as logger, output, and trim
4+
// to capture and compare the output of the exercises.
5+
package exercicios_ninja_nivel_12
6+
7+
import (
8+
"strings"
9+
"testing"
10+
11+
"github.com/fabianoflorentino/aprendago/pkg/logger"
12+
"github.com/fabianoflorentino/aprendago/pkg/output"
13+
"github.com/fabianoflorentino/aprendago/pkg/trim"
14+
)
15+
16+
// expectTemplate is a format string used for displaying the expected and actual output
17+
// in a structured manner. It includes placeholders for the expected value ("want")
18+
// and the actual value ("got"), making it easier to compare them in test results.
19+
const (
20+
expectTemplate = "\nwant:\n%s\n\ngot:\n%s\n"
21+
)
22+
23+
// TestResolucaoNaPraticaExercicio1 tests the function ResolucaoNaPraticaExercicio1
24+
// by capturing its output and comparing it to the expected result.
25+
// It uses the output.Capture method to capture the function's output and
26+
// the strings.Contains method to check if the captured output matches the expected output.
27+
// If there is an error capturing the output or if the output does not match the expected result,
28+
// the test will fail and log the appropriate error message.
29+
func TestResolucaoNaPraticaExercicio1(t *testing.T) {
30+
output := output.New()
31+
result, err := output.Capture(ResolucaoNaPraticaExercicio1)
32+
if err != nil {
33+
logger.Log("Error capturing output: %v", err)
34+
t.Fatalf("Error capturing output: %v", err)
35+
}
36+
37+
expected := `
38+
A idade do cachorro em anos humanos é: 21
39+
`
40+
41+
trim := trim.New()
42+
43+
if !strings.Contains(trim.String(result), trim.String(expected)) {
44+
t.Errorf(expectTemplate, expected, result)
45+
}
46+
}

pkg/format/helpme.go

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,41 @@ type HelpMe struct {
2929
Width int
3030
}
3131

32+
// PrintHelpMe formats and prints a slice of HelpMe structs using a predefined template.
33+
// It first calculates the width for each HelpMe item, then sets up a template with custom functions
34+
// for formatting. The template is parsed and executed, rendering the formatted output to os.Stdout.
35+
//
36+
// Parameters:
37+
//
38+
// helpme []HelpMe - A slice of HelpMe structs to be formatted and printed.
39+
func PrintHelpMe(helpme []HelpMe) {
40+
width := parseWidth(helpme)
41+
for i := range helpme {
42+
helpme[i].Width = width
43+
}
44+
45+
// funcMap is a map of functions that can be used in the template.
46+
// In this case, we are using the printf function from the fmt package to format the output.
47+
funcMap := template.FuncMap{
48+
"printf": fmt.Sprintf,
49+
"indent": indent,
50+
}
51+
52+
// tmpl is a template object that contains the help output template.
53+
// The template is a string that contains the formatting for the help output.
54+
tmpl, err := template.New("helpme").Funcs(funcMap).Parse(templateHelpMe)
55+
if err != nil {
56+
panic(err)
57+
}
58+
59+
// The Execute function is used to render the template and print the formatted output.
60+
// The first argument is the output destination (os.Stdout) and the second argument is the data model (helpme).
61+
err = tmpl.Execute(os.Stdout, helpme)
62+
if err != nil {
63+
panic(err)
64+
}
65+
}
66+
3267
// parseWidth takes a slice of HelpMe structs and returns the length of the longest
3368
// flag string within the slice. It iterates through each HelpMe struct, trims any
3469
// leading or trailing whitespace from the flag string, and updates the maximum
@@ -79,38 +114,3 @@ func indent(width int, description string) string {
79114

80115
return strings.Join(lines, "\n")
81116
}
82-
83-
// PrintHelpMe formats and prints a slice of HelpMe structs using a predefined template.
84-
// It first calculates the width for each HelpMe item, then sets up a template with custom functions
85-
// for formatting. The template is parsed and executed, rendering the formatted output to os.Stdout.
86-
//
87-
// Parameters:
88-
//
89-
// helpme []HelpMe - A slice of HelpMe structs to be formatted and printed.
90-
func PrintHelpMe(helpme []HelpMe) {
91-
width := parseWidth(helpme)
92-
for i := range helpme {
93-
helpme[i].Width = width
94-
}
95-
96-
// funcMap is a map of functions that can be used in the template.
97-
// In this case, we are using the printf function from the fmt package to format the output.
98-
funcMap := template.FuncMap{
99-
"printf": fmt.Sprintf,
100-
"indent": indent,
101-
}
102-
103-
// tmpl is a template object that contains the help output template.
104-
// The template is a string that contains the formatting for the help output.
105-
tmpl, err := template.New("helpme").Funcs(funcMap).Parse(templateHelpMe)
106-
if err != nil {
107-
panic(err)
108-
}
109-
110-
// The Execute function is used to render the template and print the formatted output.
111-
// The first argument is the output destination (os.Stdout) and the second argument is the data model (helpme).
112-
err = tmpl.Execute(os.Stdout, helpme)
113-
if err != nil {
114-
panic(err)
115-
}
116-
}

pkg/output/output.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,19 +58,15 @@ func (o *Output) Capture(captureOutput func()) (string, error) {
5858
wg.Add(1)
5959
go func() {
6060
defer wg.Done()
61-
io.Copy(&buf, o.read) // Captura os dados
61+
io.Copy(&buf, o.read)
6262
}()
6363

64-
// Executa a função alvo
6564
captureOutput()
6665

67-
// Fecha o pipe para garantir que todos os dados sejam escritos
6866
o.write.Close()
6967

70-
// Aguarda a goroutine terminar a leitura
7168
wg.Wait()
7269

73-
// **Restaura a saída antes de ler o buffer**
7470
os.Stdout = o.stdout
7571
os.Stderr = o.stderr
7672
log.SetOutput(os.Stderr)

0 commit comments

Comments
 (0)