From 383beb80b5f99c2148183df4131f6c4768ba26ae Mon Sep 17 00:00:00 2001 From: Roger Floriano <31597636+petruki@users.noreply.github.com> Date: Mon, 16 Sep 2024 19:16:41 -0700 Subject: [PATCH] Improved respository and log packages (#39) --- src/controller/account.go | 12 ++-- src/controller/account_test.go | 2 +- src/core/handler.go | 36 +++++----- src/db/mongo.go | 4 +- src/repository/account.go | 118 ++++++++++++++------------------- src/repository/account_test.go | 4 +- src/server/app.go | 4 +- src/utils/http.go | 2 +- src/utils/log.go | 35 ++++++++++ src/utils/log_test.go | 11 +++ src/utils/util.go | 21 ++---- src/utils/util_test.go | 68 ++++++++----------- 12 files changed, 157 insertions(+), 160 deletions(-) create mode 100644 src/utils/log.go create mode 100644 src/utils/log_test.go diff --git a/src/controller/account.go b/src/controller/account.go index a3c4660..0b02720 100644 --- a/src/controller/account.go +++ b/src/controller/account.go @@ -55,7 +55,7 @@ func (controller *AccountController) CreateAccountHandler(w http.ResponseWriter, accountCreated, err := controller.accountRepository.Create(&accountRequest) if err != nil { - utils.Log(utils.LogLevelError, "Error creating account: %s", err.Error()) + utils.LogError("Error creating account: %s", err.Error()) utils.ResponseJSON(w, ErrorResponse{Error: "Error creating account"}, http.StatusInternalServerError) return } @@ -73,7 +73,7 @@ func (controller *AccountController) FetchAccountHandler(w http.ResponseWriter, account, err := controller.accountRepository.FetchByDomainIdEnvironment(domainId, enviroment) if err != nil { - utils.Log(utils.LogLevelError, "Error fetching account: %s", err.Error()) + utils.LogError("Error fetching account: %s", err.Error()) utils.ResponseJSON(w, ErrorResponse{Error: "Account not found"}, http.StatusNotFound) return } @@ -86,7 +86,7 @@ func (controller *AccountController) FetchAllAccountsByDomainIdHandler(w http.Re accounts := controller.accountRepository.FetchAllByDomainId(domainId) if accounts == nil { - utils.Log(utils.LogLevelError, "Not found accounts for domain: %s", domainId) + utils.LogError("Not found accounts for domain: %s", domainId) utils.ResponseJSON(w, ErrorResponse{Error: "Not found accounts for domain: " + domainId}, http.StatusNotFound) return } @@ -98,7 +98,7 @@ func (controller *AccountController) UpdateAccountHandler(w http.ResponseWriter, var accountRequest model.Account err := json.NewDecoder(r.Body).Decode(&accountRequest) if err != nil { - utils.Log(utils.LogLevelError, "Error updating account: %s", err.Error()) + utils.LogError("Error updating account: %s", err.Error()) utils.ResponseJSON(w, ErrorResponse{Error: "Invalid request"}, http.StatusBadRequest) return } @@ -110,7 +110,7 @@ func (controller *AccountController) UpdateAccountHandler(w http.ResponseWriter, accountUpdated, err := controller.accountRepository.Update(&accountRequest) if err != nil { - utils.Log(utils.LogLevelError, "Error updating account: %s", err.Error()) + utils.LogError("Error updating account: %s", err.Error()) utils.ResponseJSON(w, ErrorResponse{Error: "Error updating account"}, http.StatusInternalServerError) return } @@ -124,7 +124,7 @@ func (controller *AccountController) DeleteAccountHandler(w http.ResponseWriter, err := controller.accountRepository.DeleteByDomainIdEnvironment(domainId, enviroment) if err != nil { - utils.Log(utils.LogLevelError, "Error deleting account: %s", err.Error()) + utils.LogError("Error deleting account: %s", err.Error()) utils.ResponseJSON(w, ErrorResponse{Error: "Error deleting account: " + err.Error()}, http.StatusInternalServerError) return } diff --git a/src/controller/account_test.go b/src/controller/account_test.go index 84547e7..611e056 100644 --- a/src/controller/account_test.go +++ b/src/controller/account_test.go @@ -233,7 +233,7 @@ func TestDeleteAccountHandler(t *testing.T) { // Assert assert.Equal(t, http.StatusInternalServerError, response.Code) - assert.Equal(t, "{\"error\":\"Error deleting account: Account not found for domain.id: not-found\"}", response.Body.String()) + assert.Equal(t, "{\"error\":\"Error deleting account: account not found\"}", response.Body.String()) }) } diff --git a/src/core/handler.go b/src/core/handler.go index ff9e2b5..497a475 100644 --- a/src/core/handler.go +++ b/src/core/handler.go @@ -25,7 +25,7 @@ type CoreHandler struct { } func NewCoreHandler(accountRepository repository.AccountRepository, apiService IAPIService, comparatorService IComparatorService) *CoreHandler { - timeWindow, unitWindow := getTimeWindow(config.GetEnv("HANDLER_WAITING_TIME")) + timeWindow, unitWindow := utils.GetTimeWindow(config.GetEnv("HANDLER_WAITING_TIME")) waitingTime := time.Duration(timeWindow) * unitWindow return &CoreHandler{ @@ -64,7 +64,7 @@ func (c *CoreHandler) InitCoreHandlerGoroutine() (int, error) { } func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitService) { - utils.Log(utils.LogLevelInfo, "[%s] Starting account handler", accountId) + utils.LogInfo("[%s] Starting account handler", accountId) for { // Refresh account settings @@ -72,13 +72,13 @@ func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitServi if account == nil { // Terminate the goroutine (account was deleted) - utils.Log(utils.LogLevelInfo, "[%s] Account was deleted, terminating account handler", accountId) + utils.LogInfo("[%s] Account was deleted, terminating account handler", accountId) return } // Wait for account to be active if !account.Settings.Active { - utils.Log(utils.LogLevelInfo, "[%s - %s (%s)] Account is not active, waiting for activation", + utils.LogInfo("[%s - %s (%s)] Account is not active, waiting for activation", accountId, account.Domain.Name, account.Environment) c.updateDomainStatus(*account, model.StatusPending, "Account was deactivated") @@ -93,7 +93,7 @@ func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitServi repositoryData, err := gitService.GetRepositoryData(account.Environment) if err != nil { - utils.Log(utils.LogLevelError, "[%s - %s (%s)] Failed to fetch repository data - %s", + utils.LogError("[%s - %s (%s)] Failed to fetch repository data - %s", accountId, account.Domain.Name, account.Environment, err.Error()) c.updateDomainStatus(*account, model.StatusError, "Failed to fetch repository data - "+err.Error()) @@ -105,7 +105,7 @@ func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitServi snapshotVersionPayload, err := c.apiService.FetchSnapshotVersion(account.Domain.ID, account.Environment) if err != nil { - utils.Log(utils.LogLevelError, "[%s - %s (%s)] Failed to fetch snapshot version - %s", + utils.LogError("[%s - %s (%s)] Failed to fetch snapshot version - %s", accountId, account.Domain.Name, account.Environment, err.Error()) c.updateDomainStatus(*account, model.StatusError, "Failed to fetch snapshot version - "+err.Error()) @@ -119,13 +119,13 @@ func (c *CoreHandler) StartAccountHandler(accountId string, gitService IGitServi } // Wait for the next cycle - timeWindow, unitWindow := getTimeWindow(account.Settings.Window) + timeWindow, unitWindow := utils.GetTimeWindow(account.Settings.Window) time.Sleep(time.Duration(timeWindow) * unitWindow) } } func (c *CoreHandler) syncUp(account model.Account, repositoryData *model.RepositoryData, gitService IGitService) { - utils.Log(utils.LogLevelInfo, "[%s - %s (%s)] Syncing up", account.ID.Hex(), account.Domain.Name, account.Environment) + utils.LogInfo("[%s - %s (%s)] Syncing up", account.ID.Hex(), account.Domain.Name, account.Environment) // Update account status: Out of sync account.Domain.LastCommit = repositoryData.CommitHash @@ -136,6 +136,9 @@ func (c *CoreHandler) syncUp(account model.Account, repositoryData *model.Reposi diff, snapshotApi, err := c.checkForChanges(account, repositoryData.Content) if err != nil { + utils.LogError("[%s - %s (%s)] Failed to check for changes - %s", + account.ID.Hex(), account.Domain.Name, account.Environment, err.Error()) + c.updateDomainStatus(account, model.StatusError, "Failed to check for changes - "+err.Error()) return } @@ -144,7 +147,7 @@ func (c *CoreHandler) syncUp(account model.Account, repositoryData *model.Reposi changeSource, account, err := c.applyChanges(snapshotApi, account, repositoryData, diff, gitService) if err != nil { - utils.Log(utils.LogLevelError, "[%s - %s (%s)] Failed to apply changes [%s] - %s", + utils.LogError("[%s - %s (%s)] Failed to apply changes [%s] - %s", account.ID.Hex(), account.Domain.Name, account.Environment, changeSource, err.Error()) c.updateDomainStatus(account, model.StatusError, "Failed to apply changes ["+changeSource+"] - "+err.Error()) @@ -181,7 +184,7 @@ func (c *CoreHandler) checkForChanges(account model.Account, content string) (mo func (c *CoreHandler) applyChanges(snapshotApi model.Snapshot, account model.Account, repositoryData *model.RepositoryData, diff model.DiffResult, gitService IGitService) (string, model.Account, error) { - utils.Log(utils.LogLevelDebug, "[%s - %s (%s)] SnapshotAPI version: %s - SnapshotRepo version: %s", + utils.LogDebug("[%s - %s (%s)] SnapshotAPI version: %s - SnapshotRepo version: %s", account.ID.Hex(), account.Domain.Name, account.Environment, fmt.Sprint(snapshotApi.Domain.Version), fmt.Sprint(account.Domain.Version)) err := error(nil) @@ -192,7 +195,7 @@ func (c *CoreHandler) applyChanges(snapshotApi model.Snapshot, account model.Acc if c.isRepositoryOutSync(repositoryData, diff) { account, err = c.applyChangesToRepository(account, snapshotApi, gitService) } else { - utils.Log(utils.LogLevelInfo, "[%s - %s (%s)] Repository is up to date", + utils.LogInfo("[%s - %s (%s)] Repository is up to date", account.ID.Hex(), account.Domain.Name, account.Environment) account.Domain.Version = snapshotApi.Domain.Version @@ -206,7 +209,7 @@ func (c *CoreHandler) applyChanges(snapshotApi model.Snapshot, account model.Acc } func (c *CoreHandler) applyChangesToAPI(account model.Account, repositoryData *model.RepositoryData, diff model.DiffResult) model.Account { - utils.Log(utils.LogLevelInfo, "[%s - %s (%s)] Pushing changes to API", account.ID.Hex(), account.Domain.Name, account.Environment) + utils.LogInfo("[%s - %s (%s)] Pushing changes to API", account.ID.Hex(), account.Domain.Name, account.Environment) // Removed deleted if force prune is disabled if !account.Settings.ForcePrune { @@ -223,7 +226,7 @@ func (c *CoreHandler) applyChangesToAPI(account model.Account, repositoryData *m } func (c *CoreHandler) applyChangesToRepository(account model.Account, snapshot model.Snapshot, gitService IGitService) (model.Account, error) { - utils.Log(utils.LogLevelInfo, "[%s - %s (%s)] Pushing changes to repository", account.ID.Hex(), account.Domain.Name, account.Environment) + utils.LogInfo("[%s - %s (%s)] Pushing changes to repository", account.ID.Hex(), account.Domain.Name, account.Environment) // Remove version from domain snapshotContent := snapshot @@ -245,7 +248,7 @@ func (c *CoreHandler) applyChangesToRepository(account model.Account, snapshot m func (c *CoreHandler) isOutSync(account model.Account, lastCommit string, snapshotVersionPayload string) bool { snapshotVersion := c.apiService.NewDataFromJson([]byte(snapshotVersionPayload)).Snapshot.Domain.Version - utils.Log(utils.LogLevelDebug, "[%s - %s (%s)] Checking account - Last commit: %s - Domain Version: %d - Snapshot Version: %d", + utils.LogDebug("[%s - %s (%s)] Checking account - Last commit: %s - Domain Version: %d - Snapshot Version: %d", account.ID.Hex(), account.Domain.Name, account.Environment, account.Domain.LastCommit, account.Domain.Version, snapshotVersion) return account.Domain.LastCommit == "" || // First sync @@ -264,8 +267,3 @@ func (c *CoreHandler) updateDomainStatus(account model.Account, status string, m account.Domain.LastDate = time.Now().Format(time.ANSIC) c.accountRepository.Update(&account) } - -func getTimeWindow(window string) (int, time.Duration) { - duration, _ := time.ParseDuration(window) - return 1, duration -} diff --git a/src/db/mongo.go b/src/db/mongo.go index 0c21fad..4a126b1 100644 --- a/src/db/mongo.go +++ b/src/db/mongo.go @@ -24,9 +24,9 @@ func InitDb() *mongo.Database { err = client.Ping(context.Background(), nil) if err != nil { - utils.Log(utils.LogLevelError, "Error connecting to MongoDB: %s", err.Error()) + utils.LogError("Error connecting to MongoDB: %s", err.Error()) } - utils.Log(utils.LogLevelInfo, "Connected to MongoDB!") + utils.LogInfo("Connected to MongoDB!") return client.Database(config.GetEnv("MONGO_DB")) } diff --git a/src/repository/account.go b/src/repository/account.go index f1263bd..922269f 100644 --- a/src/repository/account.go +++ b/src/repository/account.go @@ -49,59 +49,74 @@ func (repo *AccountRepositoryMongo) Create(account *model.Account) (*model.Accou return account, nil } -func (repo *AccountRepositoryMongo) FetchByAccountId(accountId string) (*model.Account, error) { +func (repo *AccountRepositoryMongo) Update(account *model.Account) (*model.Account, error) { collection, ctx, cancel := getDbContext(repo) defer cancel() - var account model.Account - objectId, _ := primitive.ObjectIDFromHex(accountId) - filter := bson.M{"_id": objectId} - err := collection.FindOne(ctx, filter).Decode(&account) + filter := primitive.M{domainIdFilter: account.Domain.ID, environmentFilter: account.Environment} + update := getUpdateFields(account) + + var updatedAccount model.Account + err := collection.FindOneAndUpdate(ctx, filter, update, options.FindOneAndUpdate(). + SetReturnDocument(options.After)). + Decode(&updatedAccount) + if err != nil { return nil, err } - return &account, nil + return &updatedAccount, nil } -func (repo *AccountRepositoryMongo) FetchByDomainIdEnvironment(domainId string, environment string) (*model.Account, error) { - collection, ctx, cancel := getDbContext(repo) - defer cancel() +func (repo *AccountRepositoryMongo) FetchByAccountId(accountId string) (*model.Account, error) { + objectId, _ := primitive.ObjectIDFromHex(accountId) + filter := bson.M{"_id": objectId} + return repo.fetchOne(filter) +} - var account model.Account +func (repo *AccountRepositoryMongo) FetchByDomainIdEnvironment(domainId string, environment string) (*model.Account, error) { filter := primitive.M{domainIdFilter: domainId, environmentFilter: environment} - err := collection.FindOne(ctx, filter).Decode(&account) - if err != nil { - return nil, err - } - - return &account, nil + return repo.fetchOne(filter) } func (repo *AccountRepositoryMongo) FetchAllByDomainId(domainId string) []model.Account { + filter := primitive.M{domainIdFilter: domainId} + return repo.fetchMany(filter) +} + +func (repo *AccountRepositoryMongo) FetchAllAccounts() []model.Account { + filter := bson.M{} + return repo.fetchMany(filter) +} + +func (repo *AccountRepositoryMongo) DeleteByAccountId(accountId string) error { + objectId, _ := primitive.ObjectIDFromHex(accountId) + filter := bson.M{"_id": objectId} + return repo.deleteOne(filter) +} + +func (repo *AccountRepositoryMongo) DeleteByDomainIdEnvironment(domainId string, environment string) error { + filter := primitive.M{domainIdFilter: domainId, environmentFilter: environment} + return repo.deleteOne(filter) +} + +func (repo *AccountRepositoryMongo) deleteOne(filter primitive.M) error { collection, ctx, cancel := getDbContext(repo) defer cancel() - filter := primitive.M{domainIdFilter: domainId} - cursor, _ := collection.Find(ctx, filter) - - var accounts []model.Account - for cursor.Next(ctx) { - var account model.Account - err := cursor.Decode(&account) - if err == nil { - accounts = append(accounts, account) - } + result, err := collection.DeleteOne(ctx, filter) + if result.DeletedCount == 0 { + return errors.New("account not found") } - return accounts + return err } -func (repo *AccountRepositoryMongo) FetchAllAccounts() []model.Account { +func (repo *AccountRepositoryMongo) fetchMany(filter primitive.M) []model.Account { collection, ctx, cancel := getDbContext(repo) defer cancel() - cursor, _ := collection.Find(ctx, primitive.M{}) + cursor, _ := collection.Find(ctx, filter) var accounts []model.Account for cursor.Next(ctx) { @@ -115,52 +130,17 @@ func (repo *AccountRepositoryMongo) FetchAllAccounts() []model.Account { return accounts } -func (repo *AccountRepositoryMongo) Update(account *model.Account) (*model.Account, error) { +func (repo *AccountRepositoryMongo) fetchOne(filter primitive.M) (*model.Account, error) { collection, ctx, cancel := getDbContext(repo) defer cancel() - filter := primitive.M{domainIdFilter: account.Domain.ID, environmentFilter: account.Environment} - update := getUpdateFields(account) - - var updatedAccount model.Account - err := collection.FindOneAndUpdate(ctx, filter, update, options.FindOneAndUpdate(). - SetReturnDocument(options.After)). - Decode(&updatedAccount) - + var account model.Account + err := collection.FindOne(ctx, filter).Decode(&account) if err != nil { return nil, err } - return &updatedAccount, nil -} - -func (repo *AccountRepositoryMongo) DeleteByAccountId(accountId string) error { - collection, ctx, cancel := getDbContext(repo) - defer cancel() - - objectId, _ := primitive.ObjectIDFromHex(accountId) - filter := bson.M{"_id": objectId} - result, err := collection.DeleteOne(ctx, filter) - - if result.DeletedCount == 0 { - return errors.New("Account not found for id: " + accountId) - } - - return err -} - -func (repo *AccountRepositoryMongo) DeleteByDomainIdEnvironment(domainId string, environment string) error { - collection, ctx, cancel := getDbContext(repo) - defer cancel() - - filter := primitive.M{domainIdFilter: domainId, environmentFilter: environment} - result, err := collection.DeleteOne(ctx, filter) - - if result.DeletedCount == 0 { - return errors.New("Account not found for domain.id: " + domainId) - } - - return err + return &account, nil } func getDbContext(repo *AccountRepositoryMongo) (*mongo.Collection, context.Context, context.CancelFunc) { @@ -182,7 +162,7 @@ func registerAccountRepositoryValidators(db *mongo.Database) { _, err := collection.Indexes().CreateOne(context.Background(), indexModel) if err != nil { - utils.Log(utils.LogLevelError, "Error creating index for account (environment, domain.id): %s", err.Error()) + utils.LogError("Error creating index for account (environment, domain.id): %s", err.Error()) } } diff --git a/src/repository/account_test.go b/src/repository/account_test.go index 045aa0c..945d5e2 100644 --- a/src/repository/account_test.go +++ b/src/repository/account_test.go @@ -193,7 +193,7 @@ func TestDeleteAccount(t *testing.T) { // Assert assert.NotNil(t, err) - assert.Equal(t, "Account not found for id: non_existent_id", err.Error()) + assert.Equal(t, "account not found", err.Error()) }) t.Run("Should delete an account by domain ID and environment", func(t *testing.T) { @@ -215,6 +215,6 @@ func TestDeleteAccount(t *testing.T) { // Assert assert.NotNil(t, err) - assert.Equal(t, "Account not found for domain.id: non_existent_domain_id", err.Error()) + assert.Equal(t, "account not found", err.Error()) }) } diff --git a/src/server/app.go b/src/server/app.go index 5f12072..8dd6ba8 100644 --- a/src/server/app.go +++ b/src/server/app.go @@ -42,12 +42,12 @@ func (app *App) Start() error { go func() { if err := app.httpServer.ListenAndServe(); err != nil { - utils.Log(utils.LogLevelError, "Failed to listen and serve: %s", err.Error()) + utils.LogError("Failed to listen and serve: %s", err.Error()) os.Exit(1) } }() - utils.Log(utils.LogLevelInfo, "Server started on port %s", port) + utils.LogInfo("Server started on port %s", port) quit := make(chan os.Signal, 1) signal.Notify(quit, os.Interrupt, os.Interrupt) diff --git a/src/utils/http.go b/src/utils/http.go index 973d882..b94ab9f 100644 --- a/src/utils/http.go +++ b/src/utils/http.go @@ -11,7 +11,7 @@ func ResponseJSON(w http.ResponseWriter, data interface{}, status int) { encodedData, err := json.Marshal(data) if err != nil { - Log(LogLevelError, "Error encoding JSON: %s", err.Error()) + LogError("Error encoding JSON: %s", err.Error()) return } diff --git a/src/utils/log.go b/src/utils/log.go new file mode 100644 index 0000000..cd80232 --- /dev/null +++ b/src/utils/log.go @@ -0,0 +1,35 @@ +package utils + +import ( + "fmt" + "log" + + "github.com/switcherapi/switcher-gitops/src/config" +) + +const ( + LogLevelInfo = "INFO" + LogLevelError = "ERROR" + LogLevelDebug = "DEBUG" +) + +func LogInfo(message string, args ...interface{}) { + Log(LogLevelInfo, message, args...) +} + +func LogError(message string, args ...interface{}) { + Log(LogLevelError, message, args...) +} + +func LogDebug(message string, args ...interface{}) { + Log(LogLevelDebug, message, args...) +} + +func Log(logLevel string, message string, args ...interface{}) { + currentLogLevel := config.GetEnv("LOG_LEVEL") + + if currentLogLevel == LogLevelDebug || currentLogLevel == LogLevelError || + currentLogLevel == logLevel || LogLevelError == logLevel { + log.Printf("[%s] %s\n", logLevel, fmt.Sprintf(message, args...)) + } +} diff --git a/src/utils/log_test.go b/src/utils/log_test.go new file mode 100644 index 0000000..5cfb5ee --- /dev/null +++ b/src/utils/log_test.go @@ -0,0 +1,11 @@ +package utils + +import ( + "testing" +) + +func TestLog(t *testing.T) { + LogDebug("This is a debug message") + LogInfo("This is an info message") + LogError("This is an error message") +} diff --git a/src/utils/util.go b/src/utils/util.go index dd3ed35..438d448 100644 --- a/src/utils/util.go +++ b/src/utils/util.go @@ -7,26 +7,13 @@ import ( "encoding/base64" "encoding/json" "errors" - "fmt" - "log" "os" - - "github.com/switcherapi/switcher-gitops/src/config" -) - -const ( - LogLevelInfo = "INFO" - LogLevelError = "ERROR" - LogLevelDebug = "DEBUG" + "time" ) -func Log(logLevel string, message string, args ...interface{}) { - currentLogLevel := config.GetEnv("LOG_LEVEL") - - if currentLogLevel == LogLevelDebug || currentLogLevel == LogLevelError || - currentLogLevel == logLevel || LogLevelError == logLevel { - log.Printf("[%s] %s\n", logLevel, fmt.Sprintf(message, args...)) - } +func GetTimeWindow(window string) (int, time.Duration) { + duration, _ := time.ParseDuration(window) + return 1, duration } func FormatJSON(jsonString string) string { diff --git a/src/utils/util_test.go b/src/utils/util_test.go index 8422014..4e74c55 100644 --- a/src/utils/util_test.go +++ b/src/utils/util_test.go @@ -2,9 +2,9 @@ package utils import ( "os" - "strings" "testing" + "github.com/stretchr/testify/assert" "github.com/switcherapi/switcher-gitops/src/config" "github.com/switcherapi/switcher-gitops/src/model" ) @@ -15,38 +15,34 @@ func TestMain(m *testing.M) { m.Run() } -func TestLog(t *testing.T) { - Log(LogLevelInfo, "Test log") -} - func TestToJsonFromObject(t *testing.T) { account := givenAccount(true) actual := ToJsonFromObject(account) - AssertNotNil(t, actual) + assert.NotNil(t, actual) } func TestToMapFromObject(t *testing.T) { account := givenAccount(true) actual := ToMapFromObject(account) - AssertNotNil(t, actual) + assert.NotNil(t, actual) } func TestFormatJSON(t *testing.T) { account := givenAccount(true) accountJSON := ToJsonFromObject(account) actual := FormatJSON(accountJSON) - AssertNotNil(t, actual) + assert.NotNil(t, actual) } func TestFormatJSONError(t *testing.T) { actual := FormatJSON("invalid") - AssertNotNil(t, actual) + assert.NotNil(t, actual) } func TestReadJsonFileToObject(t *testing.T) { json := ReadJsonFromFile("../../resources/fixtures/util/default.json") - AssertNotNil(t, json) - AssertContains(t, json, "Release 1") + assert.NotNil(t, json) + assert.Contains(t, json, "Release 1") } func TestEncrypDecrypt(t *testing.T) { @@ -54,11 +50,11 @@ func TestEncrypDecrypt(t *testing.T) { text := "github_pat_XXXXXXXXXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" encrypted := Encrypt(text, privatKey) - AssertNotNil(t, encrypted) + assert.NotNil(t, encrypted) decrypted, err := Decrypt(encrypted, privatKey) - AssertNil(t, err) - AssertEqual(t, text, decrypted) + assert.Nil(t, err) + assert.Equal(t, text, decrypted) } func TestEncrypDecryptError(t *testing.T) { @@ -66,11 +62,25 @@ func TestEncrypDecryptError(t *testing.T) { text := "github_pat..." encrypted := Encrypt(text, privatKey) - AssertNotNil(t, encrypted) + assert.NotNil(t, encrypted) decrypted, err := Decrypt("invalid", privatKey) - AssertNotNil(t, err) - AssertEqual(t, "", decrypted) + assert.NotNil(t, err) + assert.Equal(t, "", decrypted) +} + +func TestGetTimeWindow(t *testing.T) { + t.Run("valid", func(t *testing.T) { + actual, unit := GetTimeWindow("10m") + assert.NotNil(t, actual) + assert.NotNil(t, unit) + }) + + t.Run("invalid", func(t *testing.T) { + actual, unit := GetTimeWindow("invalid") + assert.NotNil(t, actual) + assert.NotNil(t, unit) + }) } // Fixtures @@ -105,27 +115,3 @@ func GetDir() string { return directory } - -func AssertNotNil(t *testing.T, object interface{}) { - if object == nil { - t.Errorf("Object is nil") - } -} - -func AssertNil(t *testing.T, object interface{}) { - if object != nil { - t.Errorf("Object is not nil") - } -} - -func AssertEqual(t *testing.T, actual interface{}, expected interface{}) { - if actual != expected { - t.Errorf("Expected %v, got %v", actual, expected) - } -} - -func AssertContains(t *testing.T, actual string, expected string) { - if !strings.Contains(actual, expected) { - t.Errorf("Expected %v to contain %v", actual, expected) - } -}