Compare commits

..

3 Commits

Author SHA1 Message Date
75bbbb4408 chore(tests):
Some checks failed
Gitea Build Check / Build (push) Failing after 26s
refactored & fixed old test cases
2024-08-13 11:07:14 +02:00
cfc7e5362d chore: Add comments and improve JSON annotations for better data structuring and clarity across the codebase 2024-08-13 10:54:21 +02:00
b4e8152cb4 chore: removed dead code 2024-08-13 10:35:01 +02:00
19 changed files with 82 additions and 439 deletions

View File

@ -8,7 +8,18 @@ import (
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
) )
func HandleError(ctx context.Context, span trace.Span, logger *log.Entry, error error) error { // HandleError logs the provided error, records it in the given trace span,
// sets the span status to error, and returns the error.
//
// Parameters:
// - ctx: context.Context, the context in which the error occurred.
// - span: trace.Span, the trace span where the error will be recorded.
// - logger: *log.Entry, a log entry used to log the error message.
// - error: error, the error to be handled.
//
// Returns:
// - error: The same error that was passed in.
func HandleError(_ context.Context, span trace.Span, logger *log.Entry, error error) error {
logger.Error(error) logger.Error(error)
span.RecordError(error) span.RecordError(error)
span.SetStatus(codes.Error, error.Error()) span.SetStatus(codes.Error, error.Error())

View File

@ -1,11 +0,0 @@
package utils
func GetOrDefault(data map[string]any, key string, defaultVal any) any {
val, ok := data[key]
if !ok {
return defaultVal
}
return val
}

View File

@ -1,60 +0,0 @@
package utils
import (
"reflect"
"testing"
)
func TestGetOrDefault(t *testing.T) {
type args struct {
data map[string]any
key string
defaultVal any
}
tests := []struct {
name string
args args
want any
}{
{
name: "Test 1: Nil map",
args: args{
data: nil,
key: "key1",
defaultVal: "default",
},
want: "default",
},
{
name: "Test 2: Existing key",
args: args{
data: map[string]interface{}{
"key1": "value1",
"key2": "value2",
},
key: "key1",
defaultVal: "default",
},
want: "value1",
},
{
name: "Test 3: Non-existing key",
args: args{
data: map[string]interface{}{
"key1": "value1",
"key2": "value2",
},
key: "key3",
defaultVal: "default",
},
want: "default",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GetOrDefault(tt.args.data, tt.args.key, tt.args.defaultVal); !reflect.DeepEqual(got, tt.want) {
t.Errorf("GetOrDefault() = %v, want %v", got, tt.want)
}
})
}
}

View File

@ -7,6 +7,7 @@ import (
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
) )
// SetupTracing initializes a new trace span and logger for the given context and tracer.
func SetupTracing(ctx context.Context, tracer trace.Tracer, tracerName string) (context.Context, trace.Span, *log.Entry) { func SetupTracing(ctx context.Context, tracer trace.Tracer, tracerName string) (context.Context, trace.Span, *log.Entry) {
ctx, span := tracer.Start(ctx, tracerName) ctx, span := tracer.Start(ctx, tracerName)
localLogger := log.WithContext(ctx) localLogger := log.WithContext(ctx)
@ -14,6 +15,7 @@ func SetupTracing(ctx context.Context, tracer trace.Tracer, tracerName string) (
return ctx, span, localLogger return ctx, span, localLogger
} }
// HandleEvent logs the provided event name and adds it to the given trace span.
func HandleEvent(span trace.Span, logger *log.Entry, eventName string) { func HandleEvent(span trace.Span, logger *log.Entry, eventName string) {
logger.Debug(eventName) logger.Debug(eventName)
span.AddEvent(eventName) span.AddEvent(eventName)

View File

@ -28,9 +28,16 @@ var (
logger = log.New() logger = log.New()
) )
// Connect to the Database
func Connect(ctx context.Context, config models.DatabaseConfig) error { func Connect(ctx context.Context, config models.DatabaseConfig) error {
setupTelemetry()
// Setup open telemetry
tracer = otel.Tracer(tracingName)
hook := otellogrus.NewHook(tracingName)
logger.AddHook(hook)
// Debug enabled?
if config.Debug { if config.Debug {
log.SetLevel(log.DebugLevel) log.SetLevel(log.DebugLevel)
} }
@ -75,6 +82,7 @@ func Connect(ctx context.Context, config models.DatabaseConfig) error {
return nil return nil
} }
// migrateDatabase handels the migration of ann SQL files in the migrations subfolder
func migrateDatabase(ctx context.Context, dbPool *gorm.DB, config models.DatabaseConfig) error { func migrateDatabase(ctx context.Context, dbPool *gorm.DB, config models.DatabaseConfig) error {
ctx, span, localLogger := utils.SetupTracing(ctx, tracer, "migrateDatabase") ctx, span, localLogger := utils.SetupTracing(ctx, tracer, "migrateDatabase")
defer span.End() defer span.End()
@ -114,13 +122,7 @@ func migrateDatabase(ctx context.Context, dbPool *gorm.DB, config models.Databas
return nil return nil
} }
func setupTelemetry() { // GetGorm returns a ready to use gorm.DB client
tracer = otel.Tracer(tracingName)
hook := otellogrus.NewHook(tracingName)
logger.AddHook(hook)
}
func GetGorm(ctx context.Context) (*gorm.DB, error) { func GetGorm(ctx context.Context) (*gorm.DB, error) {
ctx, span, localLogger := utils.SetupTracing(ctx, tracer, "GetGorm") ctx, span, localLogger := utils.SetupTracing(ctx, tracer, "GetGorm")
defer span.End() defer span.End()

View File

@ -2,79 +2,26 @@ package error
import "testing" import "testing"
func TestEntityAlreadyExists_Error(t *testing.T) { func TestDatabase_Error(t *testing.T) {
type fields struct {
Reason string
}
tests := []struct { tests := []struct {
name string name string
want string fields fields
want string
}{ }{
{ {
name: "Test : Valid error String", name: "Test 1: Reason",
want: "EntityAlreadyExists error", fields: fields{Reason: "TEST ERROR"},
want: "Database error: TEST ERROR",
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
e := &EntityAlreadyExists{} e := Database{
if got := e.Error(); got != tt.want { Reason: tt.fields.Reason,
t.Errorf("Error() = %v, want %v", got, tt.want) }
}
})
}
}
func TestNoDataFound_Error(t *testing.T) {
tests := []struct {
name string
want string
}{
{
name: "Test : Valid error String",
want: "NoDataFound error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := &NoDataFound{}
if got := e.Error(); got != tt.want {
t.Errorf("Error() = %v, want %v", got, tt.want)
}
})
}
}
func TestNoDataWritten_Error(t *testing.T) {
tests := []struct {
name string
want string
}{
{
name: "Test : Valid error String",
want: "NoDataWritten error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := &NoDataWritten{}
if got := e.Error(); got != tt.want {
t.Errorf("Error() = %v, want %v", got, tt.want)
}
})
}
}
func TestNoRelationCreated_Error(t *testing.T) {
tests := []struct {
name string
want string
}{
{
name: "Test : Valid error String",
want: "relationship creation error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := &NoRelationCreated{}
if got := e.Error(); got != tt.want { if got := e.Error(); got != tt.want {
t.Errorf("Error() = %v, want %v", got, tt.want) t.Errorf("Error() = %v, want %v", got, tt.want)
} }

View File

@ -3,9 +3,6 @@ package error
import "fmt" import "fmt"
const ( const (
UserIDIsEmpty = "postID cannot be empty"
UserIDToShort = "postID needs to be 25 characters long"
SourceListIsEmpty = "sourceList cannot be empty" SourceListIsEmpty = "sourceList cannot be empty"
SourceIDIsEmpty = "SourceID cannot be empty" SourceIDIsEmpty = "SourceID cannot be empty"
SourceIDToShort = "sourceID needs to be 25 characters long" SourceIDToShort = "sourceID needs to be 25 characters long"
@ -15,10 +12,8 @@ const (
UserSourceIDToShort = "userSourceID needs to be 25 characters long" UserSourceIDToShort = "userSourceID needs to be 25 characters long"
TagListIsEmpty = "tagList cannot be empty" TagListIsEmpty = "tagList cannot be empty"
TagNameIsEmpty = "tagName cannot be empty"
TagAliasListIsEmpty = "tagAliasList cannot be empty" TagAliasListIsEmpty = "tagAliasList cannot be empty"
TagAliasNameIsEmpty = "tagAliasName cannot be empty"
TagGroupListIsEmpty = "tagGroupList cannot be empty" TagGroupListIsEmpty = "tagGroupList cannot be empty"
TagGroupNameIsEmpty = "tagGroupName cannot be empty" TagGroupNameIsEmpty = "tagGroupName cannot be empty"

View File

@ -1,5 +0,0 @@
package models
type FavoriteList struct {
Posts []Post `json:"posts,omitempty"`
}

View File

@ -13,8 +13,8 @@ type ID interface {
type BaseModel[T ID] struct { type BaseModel[T ID] struct {
ID T `json:"id" gorm:"primaryKey"` ID T `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"-"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"-"` UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"` DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
} }

View File

@ -4,7 +4,7 @@ package models
type Post struct { type Post struct {
BaseModel[PostID] BaseModel[PostID]
Rating Rating `json:"rating" gorm:"type:enum('safe','questionable','explicit')"` Rating Rating `json:"rating" gorm:"type:enum('safe','questionable','explicit')"`
Tags []Tag `json:"-" gorm:"many2many:post_tags;"` Tags []Tag `json:"tags,omitempty" gorm:"many2many:post_tags;"`
Favorites []UserFavorite `json:"-" gorm:"foreignKey:PostID"` Favorites []UserFavorite `json:"-" gorm:"foreignKey:PostID"`
References []PostReference `json:"references" gorm:"foreignKey:PostID"` References []PostReference `json:"references" gorm:"foreignKey:PostID"`
} }

View File

@ -3,42 +3,9 @@ package models
import "testing" import "testing"
func TestPostReference_TableName(t *testing.T) { func TestPostReference_TableName(t *testing.T) {
type fields struct { postReference := PostReference{}
PostID string expectedTableName := "PostReference"
SourceID string if tableName := postReference.TableName(); tableName != expectedTableName {
URL string t.Fatalf("expected %s, but got %s", expectedTableName, tableName)
SourcePostID string
FullFileURL string
PreviewFileURL string
SampleFileURL string
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test 1: PostReference",
fields: fields{},
want: "PostReference",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
po := PostReference{
PostID: tt.fields.PostID,
SourceID: tt.fields.SourceID,
URL: tt.fields.URL,
PostReferenceConfig: PostReferenceConfig{
SourcePostID: tt.fields.SourcePostID,
FullFileURL: tt.fields.FullFileURL,
PreviewFileURL: tt.fields.PreviewFileURL,
SampleFileURL: tt.fields.SampleFileURL,
},
}
if got := po.TableName(); got != tt.want {
t.Errorf("TableName() = %v, want %v", got, tt.want)
}
})
} }
} }

View File

@ -3,36 +3,9 @@ package models
import "testing" import "testing"
func TestPost_TableName(t *testing.T) { func TestPost_TableName(t *testing.T) {
type fields struct { post := Post{}
BaseModel BaseModel[PostID] expectedTableName := "Post"
Rating Rating if tableName := post.TableName(); tableName != expectedTableName {
Tags []Tag t.Fatalf("expected %s, but got %s", expectedTableName, tableName)
Favorites []UserFavorite
References []PostReference
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test 1: Is name Post",
fields: fields{},
want: "Post",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
po := Post{
BaseModel: tt.fields.BaseModel,
Rating: tt.fields.Rating,
Tags: tt.fields.Tags,
Favorites: tt.fields.Favorites,
References: tt.fields.References,
}
if got := po.TableName(); got != tt.want {
t.Errorf("TableName() = %v, want %v", got, tt.want)
}
})
} }
} }

View File

@ -3,38 +3,9 @@ package models
import "testing" import "testing"
func TestSource_TableName(t *testing.T) { func TestSource_TableName(t *testing.T) {
type fields struct { source := Source{}
BaseModel BaseModel[SourceID] expectedTableName := "Source"
DisplayName string if tableName := source.TableName(); tableName != expectedTableName {
Domain string t.Fatalf("expected %s, but got %s", expectedTableName, tableName)
Icon string
UserSources []UserSource
References []PostReference
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test 1: Is name Source",
fields: fields{},
want: "Source",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
so := Source{
BaseModel: tt.fields.BaseModel,
DisplayName: tt.fields.DisplayName,
Domain: tt.fields.Domain,
Icon: tt.fields.Icon,
UserSources: tt.fields.UserSources,
References: tt.fields.References,
}
if got := so.TableName(); got != tt.want {
t.Errorf("TableName() = %v, want %v", got, tt.want)
}
})
} }
} }

View File

@ -4,9 +4,9 @@ package models
type Tag struct { type Tag struct {
Name TagName `json:"name" gorm:"primaryKey"` Name TagName `json:"name" gorm:"primaryKey"`
Type TagType `json:"type" gorm:"column:tag_type"` Type TagType `json:"type" gorm:"column:tag_type"`
Aliases []TagAlias `json:"aliases" gorm:"foreignKey:TagID"` Aliases []TagAlias `json:"aliases,omitempty" gorm:"foreignKey:TagID"`
Groups []TagGroup `json:"groups" gorm:"foreignKey:TagID"` Groups []TagGroup `json:"groups,omitempty" gorm:"foreignKey:TagID"`
Posts []Post `json:"posts" gorm:"many2many:post_tags;"` Posts []Post `json:"posts,omitempty" gorm:"many2many:post_tags;"`
} }
func (Tag) TableName() string { func (Tag) TableName() string {

View File

@ -3,94 +3,25 @@ package models
import "testing" import "testing"
func TestTagAlias_TableName(t *testing.T) { func TestTagAlias_TableName(t *testing.T) {
type fields struct { tagAlias := TagAlias{}
Name string expectedTableName := "TagAlias"
TagID string if tableName := tagAlias.TableName(); tableName != expectedTableName {
} t.Fatalf("expected %s, but got %s", expectedTableName, tableName)
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test 1: Is Name TagAlias",
fields: fields{},
want: "TagAlias",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ta := TagAlias{
Name: tt.fields.Name,
TagID: tt.fields.TagID,
}
if got := ta.TableName(); got != tt.want {
t.Errorf("TableName() = %v, want %v", got, tt.want)
}
})
} }
} }
func TestTagGroup_TableName(t *testing.T) { func TestTagGroup_TableName(t *testing.T) {
type fields struct { tagGroup := TagGroup{}
Name string expectedTableName := "TagGroup"
TagID string if tableName := tagGroup.TableName(); tableName != expectedTableName {
} t.Fatalf("expected %s, but got %s", expectedTableName, tableName)
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test 1: Is name TagGroup",
fields: fields{},
want: "TagGroup",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ta := TagGroup{
Name: tt.fields.Name,
TagID: tt.fields.TagID,
}
if got := ta.TableName(); got != tt.want {
t.Errorf("TableName() = %v, want %v", got, tt.want)
}
})
} }
} }
func TestTag_TableName(t *testing.T) { func TestTags_TableName(t *testing.T) {
type fields struct { tag := Tag{}
Name string expectedTableName := "Tag"
Type TagType if tableName := tag.TableName(); tableName != expectedTableName {
Aliases []TagAlias t.Fatalf("expected %s, but got %s", expectedTableName, tableName)
Groups []TagGroup
Posts []Post
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test 1: Is name Tag",
fields: fields{},
want: "Tag",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ta := Tag{
Name: tt.fields.Name,
Type: tt.fields.Type,
Aliases: tt.fields.Aliases,
Groups: tt.fields.Groups,
Posts: tt.fields.Posts,
}
if got := ta.TableName(); got != tt.want {
t.Errorf("TableName() = %v, want %v", got, tt.want)
}
})
} }
} }

View File

@ -1,37 +1,11 @@
package models package models
import ( import "testing"
"testing"
"time"
)
func TestUserFavorite_TableName(t *testing.T) { func TestUserFavorite_TableName(t *testing.T) {
type fields struct { userFavorite := UserFavorite{}
UserID string expectedTableName := "UserFavorites"
PostID string if tableName := userFavorite.TableName(); tableName != expectedTableName {
CreatedAt time.Time t.Fatalf("expected %s, but got %s", expectedTableName, tableName)
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test 1: Is name UserFavorite",
fields: fields{},
want: "UserFavorite",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
us := UserFavorite{
UserID: tt.fields.UserID,
PostID: tt.fields.PostID,
CreatedAt: tt.fields.CreatedAt,
}
if got := us.TableName(); got != tt.want {
t.Errorf("TableName() = %v, want %v", got, tt.want)
}
})
} }
} }

View File

@ -13,7 +13,7 @@ type UserSource struct {
AccountID string `json:"account_id"` AccountID string `json:"account_id"`
LastScrapeTime time.Time `json:"last_scrape_time"` LastScrapeTime time.Time `json:"last_scrape_time"`
AccountValidate bool `json:"account_validate"` AccountValidate bool `json:"account_validate"`
AccountValidationKey string `json:"-"` AccountValidationKey string `json:"account_validation_key"`
} }
func (UserSource) TableName() string { func (UserSource) TableName() string {

View File

@ -3,40 +3,9 @@ package models
import "testing" import "testing"
func TestUserSource_TableName(t *testing.T) { func TestUserSource_TableName(t *testing.T) {
type fields struct { userSource := UserSource{}
User User expectedTableName := "UserSource"
UserID UserID if tableName := userSource.TableName(); tableName != expectedTableName {
Source Source t.Fatalf("expected %s, but got %s", expectedTableName, tableName)
SourceID SourceID
ScrapeTimeInterval string
AccountUsername string
AccountID string
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test 1: Is name UserSource",
fields: fields{},
want: "UserSource",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
us := UserSource{
User: tt.fields.User,
UserID: tt.fields.UserID,
Source: tt.fields.Source,
SourceID: tt.fields.SourceID,
ScrapeTimeInterval: tt.fields.ScrapeTimeInterval,
AccountUsername: tt.fields.AccountUsername,
AccountID: tt.fields.AccountID,
}
if got := us.TableName(); got != tt.want {
t.Errorf("TableName() = %v, want %v", got, tt.want)
}
})
} }
} }

View File

@ -3,32 +3,9 @@ package models
import "testing" import "testing"
func TestUser_TableName(t *testing.T) { func TestUser_TableName(t *testing.T) {
type fields struct { user := User{}
BaseModel BaseModel[UserID] expectedTableName := "User"
Favorites []UserFavorite if tableName := user.TableName(); tableName != expectedTableName {
Sources []UserSource t.Fatalf("expected %s, but got %s", expectedTableName, tableName)
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "Test 1: Is name User",
fields: fields{},
want: "User",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
us := User{
BaseModel: tt.fields.BaseModel,
Favorites: tt.fields.Favorites,
Sources: tt.fields.Sources,
}
if got := us.TableName(); got != tt.want {
t.Errorf("TableName() = %v, want %v", got, tt.want)
}
})
} }
} }