add validator + tests

This commit is contained in:
2023-09-10 14:50:39 +02:00
parent 5a43b094bb
commit d831c3e0aa
6 changed files with 154 additions and 28 deletions
+14 -22
View File
@@ -1,39 +1,31 @@
package config
import (
"errors"
"fmt"
"github.com/go-playground/validator/v10"
)
// SMTPConfig handles mandatory parameters for the STMP server connection
type SMTPConfig struct {
User string
Password string
Url string
Port string
User string `validate:"required"`
Password string `validate:"required"`
Url string `validate:"required"`
Port string `validate:"required"`
}
func NewSMTPConfig(user, password, url, port string) (SMTPConfig, error) {
var config SMTPConfig
if user == "" {
return config, errors.New("SMTP user can't be empty")
config := SMTPConfig{
User: user,
Password: password,
Url: url,
Port: port,
}
config.User = user
if password == "" {
return config, errors.New("SMTP password can't be empty")
validate := validator.New(validator.WithRequiredStructEnabled())
if err := validate.Struct(config); err != nil {
return config, err
}
config.Password = password
if url == "" {
return config, errors.New("SMTP server url can't be empty")
}
config.Url = url
if port == "" {
return config, errors.New("SMTP server port can't be empty")
}
config.Port = port
return config, nil
}
+26
View File
@@ -0,0 +1,26 @@
package config
import (
"testing"
"github.com/go-playground/validator/v10"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSMTPConfig(t *testing.T) {
t.Run("right config", func(t *testing.T) {
_, err := NewSMTPConfig("test", "test", "test", "test")
require.NoError(t, err)
})
t.Run("empty user", func(t *testing.T) {
_, err := NewSMTPConfig("", "test", "test", "test")
require.Error(t, err)
_, ok := err.(*validator.InvalidValidationError)
require.False(t, ok)
assert.Contains(t, err.Error(), "validation for 'User'")
})
}