owl-blogs/app/author_service_test.go

86 lines
2.4 KiB
Go
Raw Normal View History

2023-07-08 11:28:06 +00:00
package app_test
import (
"owl-blogs/app"
"owl-blogs/infra"
"owl-blogs/test"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
type testConfig struct {
}
func (c *testConfig) SECRET_KEY() string {
return "test"
}
func getAutherService() *app.AuthorService {
db := test.NewMockDb()
authorRepo := infra.NewDefaultAuthorRepo(db)
authorService := app.NewAuthorService(authorRepo, &testConfig{})
return authorService
}
func TestAuthorCreate(t *testing.T) {
authorService := getAutherService()
author, err := authorService.Create("test", "test")
require.NoError(t, err)
require.Equal(t, "test", author.Name)
require.NotEmpty(t, author.PasswordHash)
require.NotEqual(t, "test", author.PasswordHash)
}
func TestAuthorFindByName(t *testing.T) {
authorService := getAutherService()
_, err := authorService.Create("test", "test")
require.NoError(t, err)
author, err := authorService.FindByName("test")
require.NoError(t, err)
require.Equal(t, "test", author.Name)
require.NotEmpty(t, author.PasswordHash)
require.NotEqual(t, "test", author.PasswordHash)
}
func TestAuthorAuthenticate(t *testing.T) {
authorService := getAutherService()
_, err := authorService.Create("test", "test")
require.NoError(t, err)
require.True(t, authorService.Authenticate("test", "test"))
require.False(t, authorService.Authenticate("test", "test1"))
require.False(t, authorService.Authenticate("test1", "test"))
}
func TestAuthorCreateToken(t *testing.T) {
authorService := getAutherService()
_, err := authorService.Create("test", "test")
require.NoError(t, err)
token, err := authorService.CreateToken("test")
require.NoError(t, err)
require.NotEmpty(t, token)
require.NotEqual(t, "test", token)
}
func TestAuthorValidateToken(t *testing.T) {
authorService := getAutherService()
_, err := authorService.Create("test", "test")
require.NoError(t, err)
token, err := authorService.CreateToken("test")
require.NoError(t, err)
2023-07-13 19:55:08 +00:00
valid, name := authorService.ValidateToken(token)
require.True(t, valid)
require.Equal(t, "test", name)
valid, _ = authorService.ValidateToken(token[:len(token)-2])
require.False(t, valid)
valid, _ = authorService.ValidateToken("test")
require.False(t, valid)
valid, _ = authorService.ValidateToken("test.test")
require.False(t, valid)
valid, _ = authorService.ValidateToken(strings.Replace(token, "test", "test1", 1))
require.False(t, valid)
2023-07-08 11:28:06 +00:00
}