Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hw10 program optimization #10

Merged
merged 25 commits into from
Dec 27, 2024
Merged
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
15 changes: 15 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,21 @@ linters-settings:
funlen:
lines: 150
statements: 80
depguard:
rules:
main:
allow:
- github.com/DimVlas/otus_hw/hw09_struct_validator/rules
- github.com/stretchr/testify/require
- github.com/stretchr/testify/assert
- github.com/mailru/easyjson
- $gostd
exhaustive:
explicit-exhaustive-switch: true
gci:
custom-order: true
no-lex-order: true
skip-generated: true

issues:
exclude-rules:
Expand Down
Empty file removed hw09_struct_validator/.sync
Empty file.
3 changes: 2 additions & 1 deletion hw09_struct_validator/go.mod
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
module github.com/DimVlas/otus_hw/hw09_struct_validator
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень важно, чтобы PR содержал только файлы, относящиеся к текущему ДЗ


go 1.22

require github.com/stretchr/testify v1.9.0

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
)
19 changes: 0 additions & 19 deletions hw09_struct_validator/rules/RULES.md

This file was deleted.

61 changes: 53 additions & 8 deletions hw09_struct_validator/rules/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,80 @@ package rules
import (
"errors"
"fmt"
"strings"
)

var (
ErrRequireStruct = errors.New("validate requires structure")
ErrEmptyRule = errors.New("the rule cannot be empty")
ErrUnknowRule = errors.New("unknow rule")
ErrNotImplement = errors.New("the rule has no implementation")
ErrRequireStruct = errors.New("'Validate' requires structure")
ErrEmptyRule = errors.New("the rule cannot be empty")
ErrUnknowRule = errors.New("unknow rule")
ErrRuleNotImplement = errors.New("the rule has no implementation")
ErrKindNoRules = errors.New("for this field kind no validation rules")
)

// ошибка валидации поля структуры
var (
// программные ошибки функций валидации.
// // правило применимо только к строкам
// ErrOnlyStringRule = errors.New("rule applies only to the string")
// // правило применимо только к целым
// ErrOnlyIntRule = errors.New("rule applies only to the int")
// недопустимое условие для правила.
ErrInvalidCond = errors.New("invalid condition for the rule")
// ошибка компиляции регулярного выражения.
ErrRegexpCompile = errors.New("regex compilation error")
)

// ошибки валидации строк.
var (
// длина строки не равна.
ErrStrLenNotEqual = errors.New("length of the string not equal to")
// строка не содержит совпадений с регулярным выражением.
ErrStrReExpNotMatch = errors.New("string does not contain any matches to the regular expression")
// строка на входит в список.
ErrStrNotInList = errors.New("string is not in the list")
)

// ошибки валидации целых.
var (
// целое не может быть меньше условия.
ErrIntCantBeLess = errors.New("cannot be less")
// целое не содержит совпадений с регулярным выражением.
ErrIntCantBeGreater = errors.New("cannot be greater")
// целое на входит в список.
ErrIntNotInList = errors.New("int is not in the list")
)

// ошибка валидации поля структуры.
type ValidationError struct {
Field string
Err error
}

// слайс ошибок валидации полей структуры.
type ValidationErrors []ValidationError

func (v ValidationError) Error() string {
if len(v.Field) == 0 {
return fmt.Sprintf("%v", v.Err)
}
return fmt.Sprintf("%s: %v", v.Field, v.Err)
}

// слайс ошибок валидации полей структуры
type ValidationErrors []ValidationError
func (v ValidationError) Unwrap() error {
return v.Err
}

func (v ValidationErrors) Error() string {
cnt := len(v)
if cnt < 1 {
return ""
}
return fmt.Sprintf("%d structure validation errors found", cnt)

return func() string {
s := strings.Builder{}
for _, e := range v {
s.WriteString(fmt.Sprintf("field %s: %s\n", e.Field, e.Err.Error()))
}
return s.String()
}()
}
77 changes: 77 additions & 0 deletions hw09_struct_validator/rules/errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package rules

import (
"errors"
"testing"

"github.com/stretchr/testify/require"
)

func TestValidationError(t *testing.T) {
tests := []struct {
name string
data ValidationError
exp string
}{
{
name: "ValidationError_full",
data: ValidationError{
Field: "field",
Err: errors.New("test error"),
},
exp: "field: test error",
},
{
name: "ValidationError_without_field",
data: ValidationError{
Field: "",
Err: errors.New("test error"),
},
exp: "test error",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
s := test.data.Error()

require.Equal(t, test.exp, s)
})
}
}

func TestValidationErrors(t *testing.T) {
tests := []struct {
name string
data ValidationErrors
exp string
}{
{
name: "ValidationErrors_full",
data: ValidationErrors{
{
Field: "f1",
Err: errors.New("error1"),
},
{
Field: "f2",
Err: errors.New("error2"),
},
},
exp: "field f1: error1\nfield f2: error2\n",
},
{
name: "ValidationErrors_empty",
data: ValidationErrors{},
exp: "",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
s := test.data.Error()

require.Equal(t, test.exp, s)
})
}
}
111 changes: 0 additions & 111 deletions hw09_struct_validator/rules/rule.go

This file was deleted.

53 changes: 0 additions & 53 deletions hw09_struct_validator/rules/rule_test.go

This file was deleted.

Loading
Loading