From cbe97650906523c4c2eb8e2896861dfca722cc0d Mon Sep 17 00:00:00 2001 From: maxwelbm Date: Mon, 9 Dec 2024 21:52:39 -0300 Subject: [PATCH] test: test unit service of the ledger :rotating_light: --- .../internal/adapters/http/in/ledger.go | 3 +- .../internal/adapters/http/in/routes.go | 8 +- .../adapters/mongodb/metadata.mock.go | 47 ++-- .../adapters/mongodb/metadata.mongodb.go | 5 +- .../adapters/postgres/product/product.mock.go | 3 +- .../services/command/create-account_test.go | 228 +++++++++++---- .../services/command/create-asset_test.go | 162 ++++++++--- .../services/command/create-ledger.go | 4 +- .../services/command/create-ledger_test.go | 152 +++++++--- .../services/command/create-metadata_test.go | 131 ++++++--- .../command/create-organization_test.go | 146 +++++++--- .../services/command/create-portfolio_test.go | 216 ++++++++++++++- .../services/command/create-product_test.go | 164 ++++++++--- .../services/command/delete-account_test.go | 104 ++++++- .../services/command/delete-asset_test.go | 262 +++++++++++++++++- .../services/command/delete-ledger_test.go | 95 ++++--- .../services/command/delete-metadata_test.go | 53 ---- .../command/delete-organization_test.go | 92 +++--- .../services/command/delete-portfolio_test.go | 98 ++++--- .../services/command/delete-product_test.go | 98 ++++--- .../command/update-account-id_test.go | 123 ++++++++ .../services/command/update-account_test.go | 194 ++++++++----- .../services/command/update-asset_test.go | 178 ++++++++---- .../services/command/update-ledger_test.go | 162 +++++++---- .../services/command/update-metadata_test.go | 161 ++++++++--- .../command/update-organization_test.go | 151 +++++++--- .../services/command/update-portfolio_test.go | 172 ++++++++---- .../services/command/update-product_test.go | 170 ++++++++---- .../services/query/get-alias-accounts_test.go | 99 +++++++ .../services/query/get-all-accounts_test.go | 190 ++++++++----- .../services/query/get-all-asset_test.go | 151 +++++++--- .../services/query/get-all-ledgers_test.go | 147 +++++++--- .../query/get-all-metadata-accounts_test.go | 100 ++++--- .../query/get-all-metadata-asset_test.go | 117 +++++--- .../query/get-all-metadata-ledgers_test.go | 114 +++++--- .../get-all-metadata-organizations_test.go | 113 +++++--- .../query/get-all-metadata-portfolios_test.go | 130 ++++++--- .../query/get-all-metadata-products_test.go | 128 ++++++--- .../query/get-all-organizations_test.go | 126 ++++++--- .../services/query/get-all-portfolios_test.go | 131 ++++++--- .../services/query/get-all-products_test.go | 131 ++++++--- .../query/get-id-account-with-deleted_test.go | 174 ++++++------ .../services/query/get-id-account_test.go | 171 +++++++----- .../services/query/get-id-asset_test.go | 133 ++++++--- .../services/query/get-id-ledger_test.go | 123 +++++--- .../services/query/get-id-metadata_test.go | 58 ---- .../query/get-id-organization_test.go | 117 +++++--- .../services/query/get-id-portfolio_test.go | 133 ++++++--- .../services/query/get-id-product_test.go | 133 ++++++--- .../services/query/get-ids-accounts_test.go | 99 +++++++ scripts/coverage.sh | 6 + scripts/coverage_ignore.txt | 12 + 52 files changed, 4495 insertions(+), 1723 deletions(-) delete mode 100644 components/ledger/internal/services/command/delete-metadata_test.go create mode 100644 components/ledger/internal/services/command/update-account-id_test.go create mode 100644 components/ledger/internal/services/query/get-alias-accounts_test.go delete mode 100644 components/ledger/internal/services/query/get-id-metadata_test.go create mode 100644 components/ledger/internal/services/query/get-ids-accounts_test.go create mode 100644 scripts/coverage.sh create mode 100644 scripts/coverage_ignore.txt diff --git a/components/ledger/internal/adapters/http/in/ledger.go b/components/ledger/internal/adapters/http/in/ledger.go index c5d4f7e6..fc6e84be 100644 --- a/components/ledger/internal/adapters/http/in/ledger.go +++ b/components/ledger/internal/adapters/http/in/ledger.go @@ -1,10 +1,11 @@ package in import ( - "go.mongodb.org/mongo-driver/bson" "os" "reflect" + "go.mongodb.org/mongo-driver/bson" + "github.com/LerianStudio/midaz/components/ledger/internal/services/command" "github.com/LerianStudio/midaz/components/ledger/internal/services/query" "github.com/LerianStudio/midaz/pkg" diff --git a/components/ledger/internal/adapters/http/in/routes.go b/components/ledger/internal/adapters/http/in/routes.go index b7009979..cf44e7ab 100644 --- a/components/ledger/internal/adapters/http/in/routes.go +++ b/components/ledger/internal/adapters/http/in/routes.go @@ -1,16 +1,16 @@ package in import ( + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/cors" + fiberSwagger "github.com/swaggo/fiber-swagger" + _ "github.com/LerianStudio/midaz/components/ledger/api" "github.com/LerianStudio/midaz/pkg/mcasdoor" "github.com/LerianStudio/midaz/pkg/mlog" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/mopentelemetry" "github.com/LerianStudio/midaz/pkg/net/http" - - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/cors" - "github.com/swaggo/fiber-swagger" ) // NewRouter registerNewRouters routes to the Server. diff --git a/components/ledger/internal/adapters/mongodb/metadata.mock.go b/components/ledger/internal/adapters/mongodb/metadata.mock.go index d95e7087..6f321101 100644 --- a/components/ledger/internal/adapters/mongodb/metadata.mock.go +++ b/components/ledger/internal/adapters/mongodb/metadata.mock.go @@ -1,9 +1,9 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb (interfaces: Repository) +// Source: /home/max/Workspace/midaz/components/ledger/internal/adapters/mongodb/metadata.mongodb.go // // Generated by this command: // -// mockgen --destination=metadata.mock.go --package=mongodb . Repository +// mockgen -source=/home/max/Workspace/midaz/components/ledger/internal/adapters/mongodb/metadata.mongodb.go -destination=/home/max/Workspace/midaz/components/ledger/internal/adapters/mongodb/metadata.mongodb_mock.go -package mongodb // // Package mongodb is a generated GoMock package. @@ -11,16 +11,17 @@ package mongodb import ( context "context" - gomock "go.uber.org/mock/gomock" reflect "reflect" http "github.com/LerianStudio/midaz/pkg/net/http" + gomock "go.uber.org/mock/gomock" ) // MockRepository is a mock of Repository interface. type MockRepository struct { ctrl *gomock.Controller recorder *MockRepositoryMockRecorder + isgomock struct{} } // MockRepositoryMockRecorder is the mock recorder for MockRepository. @@ -41,73 +42,73 @@ func (m *MockRepository) EXPECT() *MockRepositoryMockRecorder { } // Create mocks base method. -func (m *MockRepository) Create(arg0 context.Context, arg1 string, arg2 *Metadata) error { +func (m *MockRepository) Create(ctx context.Context, collection string, metadata *Metadata) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Create", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "Create", ctx, collection, metadata) ret0, _ := ret[0].(error) return ret0 } // Create indicates an expected call of Create. -func (mr *MockRepositoryMockRecorder) Create(arg0, arg1, arg2 any) *gomock.Call { +func (mr *MockRepositoryMockRecorder) Create(ctx, collection, metadata any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockRepository)(nil).Create), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockRepository)(nil).Create), ctx, collection, metadata) } // Delete mocks base method. -func (m *MockRepository) Delete(arg0 context.Context, arg1, arg2 string) error { +func (m *MockRepository) Delete(ctx context.Context, collection, id string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "Delete", ctx, collection, id) ret0, _ := ret[0].(error) return ret0 } // Delete indicates an expected call of Delete. -func (mr *MockRepositoryMockRecorder) Delete(arg0, arg1, arg2 any) *gomock.Call { +func (mr *MockRepositoryMockRecorder) Delete(ctx, collection, id any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockRepository)(nil).Delete), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockRepository)(nil).Delete), ctx, collection, id) } // FindByEntity mocks base method. -func (m *MockRepository) FindByEntity(arg0 context.Context, arg1, arg2 string) (*Metadata, error) { +func (m *MockRepository) FindByEntity(ctx context.Context, collection, id string) (*Metadata, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FindByEntity", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "FindByEntity", ctx, collection, id) ret0, _ := ret[0].(*Metadata) ret1, _ := ret[1].(error) return ret0, ret1 } // FindByEntity indicates an expected call of FindByEntity. -func (mr *MockRepositoryMockRecorder) FindByEntity(arg0, arg1, arg2 any) *gomock.Call { +func (mr *MockRepositoryMockRecorder) FindByEntity(ctx, collection, id any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindByEntity", reflect.TypeOf((*MockRepository)(nil).FindByEntity), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindByEntity", reflect.TypeOf((*MockRepository)(nil).FindByEntity), ctx, collection, id) } // FindList mocks base method. -func (m *MockRepository) FindList(arg0 context.Context, arg1 string, arg2 http.QueryHeader) ([]*Metadata, error) { +func (m *MockRepository) FindList(ctx context.Context, collection string, filter http.QueryHeader) ([]*Metadata, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FindList", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "FindList", ctx, collection, filter) ret0, _ := ret[0].([]*Metadata) ret1, _ := ret[1].(error) return ret0, ret1 } // FindList indicates an expected call of FindList. -func (mr *MockRepositoryMockRecorder) FindList(arg0, arg1, arg2 any) *gomock.Call { +func (mr *MockRepositoryMockRecorder) FindList(ctx, collection, filter any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindList", reflect.TypeOf((*MockRepository)(nil).FindList), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindList", reflect.TypeOf((*MockRepository)(nil).FindList), ctx, collection, filter) } // Update mocks base method. -func (m *MockRepository) Update(arg0 context.Context, arg1, arg2 string, arg3 map[string]any) error { +func (m *MockRepository) Update(ctx context.Context, collection, id string, metadata map[string]any) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Update", arg0, arg1, arg2, arg3) + ret := m.ctrl.Call(m, "Update", ctx, collection, id, metadata) ret0, _ := ret[0].(error) return ret0 } // Update indicates an expected call of Update. -func (mr *MockRepositoryMockRecorder) Update(arg0, arg1, arg2, arg3 any) *gomock.Call { +func (mr *MockRepositoryMockRecorder) Update(ctx, collection, id, metadata any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockRepository)(nil).Update), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockRepository)(nil).Update), ctx, collection, id, metadata) } diff --git a/components/ledger/internal/adapters/mongodb/metadata.mongodb.go b/components/ledger/internal/adapters/mongodb/metadata.mongodb.go index 34779995..e361c5ae 100644 --- a/components/ledger/internal/adapters/mongodb/metadata.mongodb.go +++ b/components/ledger/internal/adapters/mongodb/metadata.mongodb.go @@ -3,11 +3,12 @@ package mongodb import ( "context" "errors" + "strings" + "time" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" - "strings" - "time" "github.com/LerianStudio/midaz/pkg" "github.com/LerianStudio/midaz/pkg/constant" diff --git a/components/ledger/internal/adapters/postgres/product/product.mock.go b/components/ledger/internal/adapters/postgres/product/product.mock.go index a556cd22..ac141df1 100644 --- a/components/ledger/internal/adapters/postgres/product/product.mock.go +++ b/components/ledger/internal/adapters/postgres/product/product.mock.go @@ -11,9 +11,10 @@ package product import ( context "context" - gomock "go.uber.org/mock/gomock" reflect "reflect" + gomock "go.uber.org/mock/gomock" + mmodel "github.com/LerianStudio/midaz/pkg/mmodel" uuid "github.com/google/uuid" diff --git a/components/ledger/internal/services/command/create-account_test.go b/components/ledger/internal/services/command/create-account_test.go index 0b06876f..5e79834e 100644 --- a/components/ledger/internal/services/command/create-account_test.go +++ b/components/ledger/internal/services/command/create-account_test.go @@ -3,11 +3,18 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "time" + + "go.uber.org/mock/gomock" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/asset" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" + "github.com/google/uuid" + + // "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" + "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/mpointers" @@ -15,74 +22,183 @@ import ( ) // TestCreateAccountSuccess is responsible to test CreateAccount with success -func TestCreateAccountSuccess(t *testing.T) { - a := &mmodel.Account{ - ID: pkg.GenerateUUIDv7().String(), - OrganizationID: pkg.GenerateUUIDv7().String(), - LedgerID: pkg.GenerateUUIDv7().String(), - PortfolioID: mpointers.String(pkg.GenerateUUIDv7().String()), +func TestCreateAccount(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + // Mocks + mockAssetRepo := asset.NewMockRepository(ctrl) + mockPortfolioRepo := portfolio.NewMockRepository(ctrl) + mockAccountRepo := account.NewMockRepository(ctrl) + + uc := &UseCase{ + AssetRepo: mockAssetRepo, + PortfolioRepo: mockPortfolioRepo, + AccountRepo: mockAccountRepo, } - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() + createAccountInput := &mmodel.CreateAccountInput{ + Name: "Test Account", + Type: "deposit", + AssetCode: "USD", + AllowReceiving: mpointers.Bool(true), + AllowSending: mpointers.Bool(true), } - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Create(gomock.Any(), a). - Return(a, nil). - Times(1) - res, err := uc.AccountRepo.Create(context.TODO(), a) + t.Run("success", func(t *testing.T) { + mockAssetRepo.EXPECT(). + FindByNameOrCode(gomock.Any(), organizationID, ledgerID, "", createAccountInput.AssetCode). + Return(true, nil). + Times(1) - assert.Equal(t, a, res) - assert.Nil(t, err) + mockAccountRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ + ID: uuid.New().String(), + AssetCode: createAccountInput.AssetCode, + Name: createAccountInput.Name, + Type: createAccountInput.Type, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }, nil). + Times(1) + + account, err := uc.CreateAccount(ctx, organizationID, ledgerID, createAccountInput) + assert.NoError(t, err) + assert.NotNil(t, account) + assert.Equal(t, createAccountInput.AssetCode, account.AssetCode) + }) } -// TestCreateWithoutPortfolioAccountSuccess is responsible to test CreateAccountWithoutPortfolio with success -func TestCreateWithoutPortfolioAccountSuccess(t *testing.T) { - a := &mmodel.Account{ - ID: pkg.GenerateUUIDv7().String(), - OrganizationID: pkg.GenerateUUIDv7().String(), - LedgerID: pkg.GenerateUUIDv7().String(), - } +func TestCreateAccount2(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), + mockAssetRepo := asset.NewMockRepository(ctrl) + mockPortfolioRepo := portfolio.NewMockRepository(ctrl) + mockAccountRepo := account.NewMockRepository(ctrl) + + uc := &UseCase{ + AssetRepo: mockAssetRepo, + PortfolioRepo: mockPortfolioRepo, + AccountRepo: mockAccountRepo, } - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Create(gomock.Any(), a). - Return(a, nil). - Times(1) - res, err := uc.AccountRepo.Create(context.TODO(), a) + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() - assert.Equal(t, a, res) - assert.Nil(t, err) -} + tests := []struct { + name string + input *mmodel.CreateAccountInput + mockSetup func() + expectedErr error + expectedName string + }{ + { + name: "success", + input: &mmodel.CreateAccountInput{ + Name: "Test Account", + Type: "deposit", + AssetCode: "USD", + AllowReceiving: mpointers.Bool(true), + AllowSending: mpointers.Bool(true), + }, + mockSetup: func() { + mockAssetRepo.EXPECT(). + FindByNameOrCode(gomock.Any(), organizationID, ledgerID, "", "USD"). + Return(true, nil). + Times(1) -// TestCreateAccountError is responsible to test CreateAccount with error -func TestCreateAccountError(t *testing.T) { - errMSG := "err to create account on database" - a := &mmodel.Account{ - ID: pkg.GenerateUUIDv7().String(), - OrganizationID: pkg.GenerateUUIDv7().String(), - LedgerID: pkg.GenerateUUIDv7().String(), - PortfolioID: mpointers.String(pkg.GenerateUUIDv7().String()), - } + mockAccountRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ + ID: uuid.New().String(), + AssetCode: "USD", + Name: "Test Account", + Type: "deposit", + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }, nil). + Times(1) + }, + expectedErr: nil, + expectedName: "Test Account", + }, + { + name: "asset not found", + input: &mmodel.CreateAccountInput{ + Name: "Test Account", + Type: "deposit", + AssetCode: "XYZ", + AllowReceiving: mpointers.Bool(true), + AllowSending: mpointers.Bool(true), + }, + mockSetup: func() { + mockAssetRepo.EXPECT(). + FindByNameOrCode(gomock.Any(), organizationID, ledgerID, "", "XYZ"). + Return(false, nil). + Times(1) + }, + expectedErr: errors.New("The provided asset code does not exist in our records. Please verify the asset code and try again."), + expectedName: "", + }, + { + name: "invalid account type", + input: &mmodel.CreateAccountInput{ + Name: "Invalid Account", + Type: "invalidType", + AssetCode: "USD", + AllowReceiving: mpointers.Bool(true), + AllowSending: mpointers.Bool(true), + }, + mockSetup: func() {}, + expectedErr: errors.New("0066 - The provided 'type' is not valid. Accepted types are: deposit, savings, loans, marketplace, creditCard or external. Please provide a valid type."), + expectedName: "", + }, + { + name: "error creating account", + input: &mmodel.CreateAccountInput{ + Name: "Error Account", + Type: "deposit", + AssetCode: "USD", + AllowReceiving: mpointers.Bool(true), + AllowSending: mpointers.Bool(true), + }, + mockSetup: func() { + mockAssetRepo.EXPECT(). + FindByNameOrCode(gomock.Any(), organizationID, ledgerID, "", "USD"). + Return(true, nil). + Times(1) - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), + mockAccountRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(nil, errors.New("failed to create account")). + Times(1) + }, + expectedErr: errors.New("failed to create account"), + expectedName: "", + }, } - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Create(gomock.Any(), a). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.AccountRepo.Create(context.TODO(), a) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + account, err := uc.CreateAccount(ctx, organizationID, ledgerID, tt.input) - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, account) + } else { + assert.NoError(t, err) + assert.NotNil(t, account) + assert.Equal(t, tt.expectedName, account.Name) + } + }) + } } diff --git a/components/ledger/internal/services/command/create-asset_test.go b/components/ledger/internal/services/command/create-asset_test.go index 18cb0bad..0a0bfb47 100644 --- a/components/ledger/internal/services/command/create-asset_test.go +++ b/components/ledger/internal/services/command/create-asset_test.go @@ -3,59 +3,145 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "time" + + "go.uber.org/mock/gomock" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/asset" - "github.com/LerianStudio/midaz/pkg" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/mpointers" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestCreateAssetSuccess is responsible to test CreateAsset with success -func TestCreateAssetSuccess(t *testing.T) { - a := &mmodel.Asset{ - ID: pkg.GenerateUUIDv7().String(), - LedgerID: pkg.GenerateUUIDv7().String(), - OrganizationID: pkg.GenerateUUIDv7().String(), - } +func TestCreateAsset(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockAssetRepo := asset.NewMockRepository(ctrl) + mockAccountRepo := account.NewMockRepository(ctrl) - uc := UseCase{ - AssetRepo: asset.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + AssetRepo: mockAssetRepo, + AccountRepo: mockAccountRepo, } - uc.AssetRepo.(*asset.MockRepository). - EXPECT(). - Create(gomock.Any(), a). - Return(a, nil). - Times(1) - res, err := uc.AssetRepo.Create(context.TODO(), a) + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() - assert.Equal(t, a, res) - assert.Nil(t, err) -} + tests := []struct { + name string + input *mmodel.CreateAssetInput + mockSetup func() + expectedErr error + expectedRes *mmodel.Asset + }{ + { + name: "success - asset created", + input: &mmodel.CreateAssetInput{ + Name: "USD Dollar", + Type: "currency", + Code: "USD", + Status: mmodel.Status{ + Code: "ACTIVE", + Description: mpointers.String("Active asset"), + }, + Metadata: nil, + }, + mockSetup: func() { + mockAssetRepo.EXPECT(). + FindByNameOrCode(gomock.Any(), organizationID, ledgerID, "USD Dollar", "USD"). + Return(false, nil). + Times(1) -// TestCreateAssetError is responsible to test CreateAsset with error -func TestCreateAssetError(t *testing.T) { - errMSG := "err to create asset on database" - a := &mmodel.Asset{ - ID: pkg.GenerateUUIDv7().String(), - LedgerID: pkg.GenerateUUIDv7().String(), - } + mockAssetRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Asset{ + ID: uuid.New().String(), + Name: "USD Dollar", + Type: "currency", + Code: "USD", + Status: mmodel.Status{Code: "ACTIVE"}, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }, nil). + Times(1) + + mockAccountRepo.EXPECT(). + ListAccountsByAlias(gomock.Any(), organizationID, ledgerID, gomock.Any()). + Return(nil, nil). + Times(1) + + mockAccountRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Account{}, nil). + Times(1) + }, + expectedErr: nil, + expectedRes: &mmodel.Asset{ + Name: "USD Dollar", + Type: "currency", + Code: "USD", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + }, + }, + { + name: "failure - invalid type", + input: &mmodel.CreateAssetInput{ + Name: "Invalid Asset", + Type: "invalidType", + Code: "INV", + }, + mockSetup: func() {}, + expectedErr: errors.New("0040 - The provided 'type' is not valid. Accepted types are currency, crypto, commodities, or others. Please provide a valid type."), + expectedRes: nil, + }, + { + name: "failure - error creating asset", + input: &mmodel.CreateAssetInput{ + Name: "USD Dollar", + Type: "currency", + Code: "USD", + }, + mockSetup: func() { + mockAssetRepo.EXPECT(). + FindByNameOrCode(gomock.Any(), organizationID, ledgerID, "USD Dollar", "USD"). + Return(false, nil). + Times(1) - uc := UseCase{ - AssetRepo: asset.NewMockRepository(gomock.NewController(t)), + mockAssetRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(nil, errors.New("failed to create asset")). + Times(1) + }, + expectedErr: errors.New("failed to create asset"), + expectedRes: nil, + }, } - uc.AssetRepo.(*asset.MockRepository). - EXPECT(). - Create(gomock.Any(), a). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.AssetRepo.Create(context.TODO(), a) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) + result, err := uc.CreateAsset(ctx, organizationID, ledgerID, tt.input) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.expectedRes.Name, result.Name) + assert.Equal(t, tt.expectedRes.Code, result.Code) + assert.Equal(t, tt.expectedRes.Type, result.Type) + } + }) + } } diff --git a/components/ledger/internal/services/command/create-ledger.go b/components/ledger/internal/services/command/create-ledger.go index c9950f50..6dc6e42b 100644 --- a/components/ledger/internal/services/command/create-ledger.go +++ b/components/ledger/internal/services/command/create-ledger.go @@ -59,7 +59,9 @@ func (uc *UseCase) CreateLedger(ctx context.Context, organizationID uuid.UUID, c return nil, err } - metadata, err := uc.CreateMetadata(ctx, reflect.TypeOf(mmodel.Ledger{}).Name(), led.ID, cli.Metadata) + takeName := reflect.TypeOf(mmodel.Ledger{}).Name() + + metadata, err := uc.CreateMetadata(ctx, takeName, led.ID, cli.Metadata) if err != nil { mopentelemetry.HandleSpanError(&span, "Failed to create ledger metadata", err) diff --git a/components/ledger/internal/services/command/create-ledger_test.go b/components/ledger/internal/services/command/create-ledger_test.go index f7f1f86b..bc6ee47d 100644 --- a/components/ledger/internal/services/command/create-ledger_test.go +++ b/components/ledger/internal/services/command/create-ledger_test.go @@ -3,59 +3,137 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "time" + + "go.uber.org/mock/gomock" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" - "github.com/LerianStudio/midaz/pkg" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/mpointers" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestCreateLedgerSuccess is responsible to test CreateLedger with success -func TestCreateLedgerSuccess(t *testing.T) { - l := &mmodel.Ledger{ - ID: pkg.GenerateUUIDv7().String(), - OrganizationID: pkg.GenerateUUIDv7().String(), - } +func TestCreateLedger(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - uc := UseCase{ - LedgerRepo: ledger.NewMockRepository(gomock.NewController(t)), + mockLedgerRepo := ledger.NewMockRepository(ctrl) + + uc := &UseCase{ + LedgerRepo: mockLedgerRepo, } - uc.LedgerRepo.(*ledger.MockRepository). - EXPECT(). - Create(gomock.Any(), l). - Return(l, nil). - Times(1) - res, err := uc.LedgerRepo.Create(context.TODO(), l) + ctx := context.Background() + organizationID := uuid.New() - assert.Equal(t, l, res) - assert.Nil(t, err) -} + tests := []struct { + name string + input *mmodel.CreateLedgerInput + mockSetup func() + expectedErr error + expectedRes *mmodel.Ledger + }{ -// TestCreateLedgerError is responsible to test CreateLedger with error -func TestCreateLedgerError(t *testing.T) { - errMSG := "err to create ledger on database" + { + name: "success - ledger created", + input: &mmodel.CreateLedgerInput{ + Name: "Finance Ledger", + Status: mmodel.Status{ + Code: "ACTIVE", + Description: mpointers.String("Ledger for financial transactions"), + }, + Metadata: nil, + }, + mockSetup: func() { + mockLedgerRepo.EXPECT(). + FindByName(gomock.Any(), organizationID, "Finance Ledger"). + Return(true, nil). + Times(1) - l := &mmodel.Ledger{ - ID: pkg.GenerateUUIDv7().String(), - OrganizationID: pkg.GenerateUUIDv7().String(), - } + mockLedgerRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Ledger{ + ID: uuid.New().String(), + OrganizationID: organizationID.String(), + Name: "Finance Ledger", + Status: mmodel.Status{ + Code: "ACTIVE", + Description: mpointers.String("Ledger for financial transactions"), + }, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }, nil). + Times(1) + }, + expectedErr: nil, + expectedRes: &mmodel.Ledger{ + Name: "Finance Ledger", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + }, + }, + { + name: "error - failed to find ledger by name", + input: &mmodel.CreateLedgerInput{ + Name: "Finance Ledger", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + Metadata: nil, + }, + mockSetup: func() { + mockLedgerRepo.EXPECT(). + FindByName(gomock.Any(), organizationID, "Finance Ledger"). + Return(false, errors.New("database error")). + Times(1) + }, + expectedErr: errors.New("database error"), + expectedRes: nil, + }, + { + name: "error - failed to create ledger", + input: &mmodel.CreateLedgerInput{ + Name: "Finance Ledger", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + Metadata: nil, + }, + mockSetup: func() { + mockLedgerRepo.EXPECT(). + FindByName(gomock.Any(), organizationID, "Finance Ledger"). + Return(false, nil). + Times(1) - uc := UseCase{ - LedgerRepo: ledger.NewMockRepository(gomock.NewController(t)), + mockLedgerRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(nil, errors.New("failed to insert ledger")). + Times(1) + }, + expectedErr: errors.New("failed to insert ledger"), + expectedRes: nil, + }, } - uc.LedgerRepo.(*ledger.MockRepository). - EXPECT(). - Create(gomock.Any(), l). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.LedgerRepo.Create(context.TODO(), l) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) + result, err := uc.CreateLedger(ctx, organizationID, tt.input) + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.expectedRes.Name, result.Name) + assert.Equal(t, tt.expectedRes.Status.Code, result.Status.Code) + } + }) + } } diff --git a/components/ledger/internal/services/command/create-metadata_test.go b/components/ledger/internal/services/command/create-metadata_test.go index f14681ea..a5772721 100644 --- a/components/ledger/internal/services/command/create-metadata_test.go +++ b/components/ledger/internal/services/command/create-metadata_test.go @@ -3,51 +3,112 @@ package command import ( "context" "errors" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.uber.org/mock/gomock" - "reflect" "testing" + "time" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" - "github.com/LerianStudio/midaz/pkg/mmodel" - "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) -// TestMetadataCreateSuccess is responsible to test MetadataCreate with success -func TestMetadataCreateSuccess(t *testing.T) { - metadata := mongodb.Metadata{ID: primitive.NewObjectID()} - collection := reflect.TypeOf(mmodel.Organization{}).Name() - uc := UseCase{ - MetadataRepo: mongodb.NewMockRepository(gomock.NewController(t)), - } +func TestCreateMetadata(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - uc.MetadataRepo.(*mongodb.MockRepository). - EXPECT(). - Create(gomock.Any(), collection, &metadata). - Return(nil). - Times(1) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - err := uc.MetadataRepo.Create(context.TODO(), collection, &metadata) - assert.Nil(t, err) -} + uc := &UseCase{ + MetadataRepo: mockMetadataRepo, + } + + ctx := context.Background() -// TestMetadataCreateError is responsible to test MetadataCreate with error -func TestMetadataCreateError(t *testing.T) { - errMSG := "err to create metadata on mongodb" - metadata := mongodb.Metadata{ID: primitive.NewObjectID()} - collection := reflect.TypeOf(mmodel.Organization{}).Name() - uc := UseCase{ - MetadataRepo: mongodb.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + entityName string + entityID string + metadata map[string]any + mockSetup func() + expectedErr error + expectedMeta map[string]any + }{ + { + name: "success - metadata created", + entityName: "TestEntity", + entityID: "12345", + metadata: map[string]any{ + "key1": "value1", + "key2": "value2", + }, + mockSetup: func() { + meta := mongodb.Metadata{ + EntityID: "12345", + EntityName: "TestEntity", + Data: map[string]any{ + "key1": "value1", + "key2": "value2", + }, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + } + mockMetadataRepo.EXPECT(). + Create(gomock.Any(), "TestEntity", gomock.Any()). + DoAndReturn(func(ctx context.Context, entityName string, metadata *mongodb.Metadata) error { + assert.Equal(t, meta.EntityID, metadata.EntityID) + assert.Equal(t, meta.EntityName, metadata.EntityName) + assert.Equal(t, meta.Data, metadata.Data) + return nil + }). + Times(1) + }, + expectedErr: nil, + expectedMeta: map[string]any{ + "key1": "value1", + "key2": "value2", + }, + }, + { + name: "failure - error creating metadata", + entityName: "TestEntity", + entityID: "12345", + metadata: map[string]any{ + "key1": "value1", + "key2": "value2", + }, + mockSetup: func() { + mockMetadataRepo.EXPECT(). + Create(gomock.Any(), "TestEntity", gomock.Any()). + Return(errors.New("failed to create metadata")). + Times(1) + }, + expectedErr: errors.New("failed to create metadata"), + expectedMeta: nil, + }, + { + name: "no metadata provided", + entityName: "TestEntity", + entityID: "12345", + metadata: nil, + mockSetup: func() {}, + expectedErr: nil, + expectedMeta: nil, + }, } - uc.MetadataRepo.(*mongodb.MockRepository). - EXPECT(). - Create(gomock.Any(), collection, &metadata). - Return(errors.New(errMSG)). - Times(1) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() - err := uc.MetadataRepo.Create(context.TODO(), collection, &metadata) - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) + result, err := uc.CreateMetadata(ctx, tt.entityName, tt.entityID, tt.metadata) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.Equal(t, tt.expectedMeta, result) + } + }) + } } diff --git a/components/ledger/internal/services/command/create-organization_test.go b/components/ledger/internal/services/command/create-organization_test.go index 3074a226..f28c2e86 100644 --- a/components/ledger/internal/services/command/create-organization_test.go +++ b/components/ledger/internal/services/command/create-organization_test.go @@ -2,53 +2,129 @@ package command import ( "context" - "errors" - "go.uber.org/mock/gomock" "testing" + "time" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/mdz/pkg/ptr" "github.com/LerianStudio/midaz/pkg/mmodel" - "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) -// TestCreateOrganizationSuccess is responsible to test CreateOrganization with success -func TestCreateOrganizationSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7().String() - o := &mmodel.Organization{ID: id} +func TestCreateOrganization(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockRepo := organization.NewMockRepository(ctrl) - uc := UseCase{ - OrganizationRepo: organization.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + OrganizationRepo: mockRepo, } - uc.OrganizationRepo.(*organization.MockRepository). - EXPECT(). - Create(gomock.Any(), o). - Return(o, nil). - Times(1) - res, err := uc.OrganizationRepo.Create(context.TODO(), o) + tests := []struct { + name string + input *mmodel.CreateOrganizationInput + mockSetup func() + expectErr bool + expectedOrg *mmodel.Organization + }{ + { + name: "Success with all fields provided", + input: &mmodel.CreateOrganizationInput{ + LegalName: "Test Org", + DoingBusinessAs: ptr.StringPtr("Test DBA"), + LegalDocument: "123456789", + Address: mmodel.Address{ + Country: "US", + }, + Status: mmodel.Status{ + Code: "ACTIVE", + }, + Metadata: nil, + }, + mockSetup: func() { + mockRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Organization{ + ID: "123", + LegalName: "Test Org", + DoingBusinessAs: ptr.StringPtr("Test DBA"), + LegalDocument: "123456789", + Address: mmodel.Address{Country: "US"}, + Status: mmodel.Status{Code: "ACTIVE"}, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + ParentOrganizationID: nil, + Metadata: nil, + }, nil) + }, + expectErr: false, + expectedOrg: &mmodel.Organization{ + LegalName: "Test Org", + DoingBusinessAs: ptr.StringPtr("Test DBA"), + LegalDocument: "123456789", + Address: mmodel.Address{Country: "US"}, + Status: mmodel.Status{Code: "ACTIVE"}, + }, + }, + { + name: "Success with default status", + input: &mmodel.CreateOrganizationInput{ + LegalName: "Default Status Org", + DoingBusinessAs: ptr.StringPtr("Default DBA"), + LegalDocument: "555555555", + Address: mmodel.Address{ + Country: "CA", + }, + Status: mmodel.Status{}, // Empty status + Metadata: nil, + }, + mockSetup: func() { + mockRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Organization{ + ID: "124", + LegalName: "Default Status Org", + DoingBusinessAs: ptr.StringPtr("Default DBA"), + LegalDocument: "555555555", + Address: mmodel.Address{Country: "CA"}, + Status: mmodel.Status{Code: "ACTIVE"}, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + ParentOrganizationID: nil, + Metadata: nil, + }, nil) + }, + expectErr: false, + expectedOrg: &mmodel.Organization{ + LegalName: "Default Status Org", + DoingBusinessAs: ptr.StringPtr("Default DBA"), + LegalDocument: "555555555", + Address: mmodel.Address{Country: "CA"}, + Status: mmodel.Status{Code: "ACTIVE"}, + }, + }, + } - assert.Equal(t, o, res) - assert.Nil(t, err) -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() -// TestCreateOrganizationError is responsible to test CreateOrganization with error -func TestCreateOrganizationError(t *testing.T) { - o := &mmodel.Organization{} - errMSG := "err to create organization on database" + ctx := context.Background() + result, err := uc.CreateOrganization(ctx, tt.input) - uc := UseCase{ - OrganizationRepo: organization.NewMockRepository(gomock.NewController(t)), + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.expectedOrg.LegalName, result.LegalName) + assert.Equal(t, tt.expectedOrg.DoingBusinessAs, result.DoingBusinessAs) + assert.Equal(t, tt.expectedOrg.LegalDocument, result.LegalDocument) + assert.Equal(t, tt.expectedOrg.Status.Code, result.Status.Code) + } + }) } - - uc.OrganizationRepo.(*organization.MockRepository). - EXPECT(). - Create(gomock.Any(), o). - Return(nil, errors.New(errMSG)) - res, err := uc.OrganizationRepo.Create(context.TODO(), o) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/command/create-portfolio_test.go b/components/ledger/internal/services/command/create-portfolio_test.go index 1f0cbfec..ae5ff8b4 100644 --- a/components/ledger/internal/services/command/create-portfolio_test.go +++ b/components/ledger/internal/services/command/create-portfolio_test.go @@ -3,16 +3,176 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" + "reflect" "testing" + "time" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/asset" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/rabbitmq" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/redis" "github.com/LerianStudio/midaz/pkg" "github.com/LerianStudio/midaz/pkg/mmodel" - + "github.com/LerianStudio/midaz/pkg/mpointers" + "github.com/google/uuid" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) +func TestCreatePortfolio(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + // Mocks + mockPortfolioRepo := portfolio.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + PortfolioRepo: mockPortfolioRepo, + MetadataRepo: mockMetadataRepo, + } + + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() + + tests := []struct { + name string + input *mmodel.CreatePortfolioInput + mockSetup func() + expectedErr error + expectedPortf *mmodel.Portfolio + }{ + { + name: "success - portfolio created", + input: &mmodel.CreatePortfolioInput{ + Name: "Test Portfolio", + EntityID: "entity-123", + Status: mmodel.Status{ + Code: "ACTIVE", + Description: mpointers.String("Active portfolio"), + }, + Metadata: map[string]any{ + "key1": "value1", + }, + }, + mockSetup: func() { + mockPortfolioRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Portfolio{ + ID: uuid.New().String(), + EntityID: "entity-123", + LedgerID: ledgerID.String(), + OrganizationID: organizationID.String(), + Name: "Test Portfolio", + Status: mmodel.Status{ + Code: "ACTIVE", + Description: mpointers.String("Active portfolio"), + }, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + Create(gomock.Any(), "Portfolio", gomock.Any()). + Return(nil). + Times(1) + }, + expectedErr: nil, + expectedPortf: &mmodel.Portfolio{ + Name: "Test Portfolio", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + }, + }, + { + name: "failure - repository error", + input: &mmodel.CreatePortfolioInput{ + Name: "Test Portfolio", + EntityID: "entity-123", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + Metadata: nil, + }, + mockSetup: func() { + mockPortfolioRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(nil, errors.New("failed to create portfolio")). + Times(1) + }, + expectedErr: errors.New("failed to create portfolio"), + expectedPortf: nil, + }, + { + name: "failure - metadata creation error", + input: &mmodel.CreatePortfolioInput{ + Name: "Test Portfolio", + EntityID: "entity-123", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + Metadata: map[string]any{ + "key1": "value1", + }, + }, + mockSetup: func() { + mockPortfolioRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Portfolio{ + ID: uuid.New().String(), + EntityID: "entity-123", + LedgerID: ledgerID.String(), + OrganizationID: organizationID.String(), + Name: "Test Portfolio", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + Create(gomock.Any(), "Portfolio", gomock.Any()). + Return(errors.New("failed to create metadata")). + Times(1) + }, + expectedErr: errors.New("failed to create metadata"), + expectedPortf: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Configura os mocks + tt.mockSetup() + + // Executa a função + result, err := uc.CreatePortfolio(ctx, organizationID, ledgerID, tt.input) + + // Validações + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.expectedPortf.Name, result.Name) + assert.Equal(t, tt.expectedPortf.Status.Code, result.Status.Code) + } + }) + } +} + // TestCreatePortfolioSuccess is responsible to test CreatePortfolio with success func TestCreatePortfolioSuccess(t *testing.T) { p := &mmodel.Portfolio{ @@ -62,3 +222,55 @@ func TestCreatePortfolioError(t *testing.T) { assert.Equal(t, err.Error(), errMSG) assert.Nil(t, res) } + +func TestUseCase_CreatePortfolio(t *testing.T) { + type fields struct { + OrganizationRepo organization.Repository + LedgerRepo ledger.Repository + ProductRepo product.Repository + PortfolioRepo portfolio.Repository + AccountRepo account.Repository + AssetRepo asset.Repository + MetadataRepo mongodb.Repository + RabbitMQRepo rabbitmq.ProducerRepository + RedisRepo redis.RedisRepository + } + type args struct { + ctx context.Context + organizationID uuid.UUID + ledgerID uuid.UUID + cpi *mmodel.CreatePortfolioInput + } + tests := []struct { + name string + fields fields + args args + want *mmodel.Portfolio + wantErr bool + }{ + // TODO: Add test cases. + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + uc := &UseCase{ + OrganizationRepo: tt.fields.OrganizationRepo, + LedgerRepo: tt.fields.LedgerRepo, + ProductRepo: tt.fields.ProductRepo, + PortfolioRepo: tt.fields.PortfolioRepo, + AccountRepo: tt.fields.AccountRepo, + AssetRepo: tt.fields.AssetRepo, + MetadataRepo: tt.fields.MetadataRepo, + RabbitMQRepo: tt.fields.RabbitMQRepo, + RedisRepo: tt.fields.RedisRepo, + } + got, err := uc.CreatePortfolio(tt.args.ctx, tt.args.organizationID, tt.args.ledgerID, tt.args.cpi) + if (err != nil) != tt.wantErr { + t.Errorf("UseCase.CreatePortfolio() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("UseCase.CreatePortfolio() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/components/ledger/internal/services/command/create-product_test.go b/components/ledger/internal/services/command/create-product_test.go index dcadeb78..42373893 100644 --- a/components/ledger/internal/services/command/create-product_test.go +++ b/components/ledger/internal/services/command/create-product_test.go @@ -2,61 +2,141 @@ package command import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "time" + + "go.uber.org/mock/gomock" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" - "github.com/LerianStudio/midaz/pkg" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestCreateProductSuccess is responsible to test CreateProduct with success -func TestCreateProductSuccess(t *testing.T) { - p := &mmodel.Product{ - ID: pkg.GenerateUUIDv7().String(), - OrganizationID: pkg.GenerateUUIDv7().String(), - LedgerID: pkg.GenerateUUIDv7().String(), - } - - uc := UseCase{ - ProductRepo: product.NewMockRepository(gomock.NewController(t)), - } - - uc.ProductRepo.(*product.MockRepository). - EXPECT(). - Create(gomock.Any(), p). - Return(p, nil). - Times(1) - res, err := uc.ProductRepo.Create(context.TODO(), p) +func TestCreateProduct(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - assert.Equal(t, p, res) - assert.Nil(t, err) -} + mockRepo := product.NewMockRepository(ctrl) -// TestCreateProductError is responsible to test CreateProduct with error -func TestCreateProductError(t *testing.T) { - errMSG := "err to create product on database" - p := &mmodel.Product{ - ID: pkg.GenerateUUIDv7().String(), - OrganizationID: pkg.GenerateUUIDv7().String(), - LedgerID: pkg.GenerateUUIDv7().String(), + uc := &UseCase{ + ProductRepo: mockRepo, } - uc := UseCase{ - ProductRepo: product.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + input *mmodel.CreateProductInput + mockSetup func() + expectErr bool + expectedProd *mmodel.Product + }{ + { + name: "Success with all fields", + organizationID: uuid.New(), + ledgerID: uuid.New(), + input: &mmodel.CreateProductInput{ + Name: "Test Product", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + Metadata: nil, + }, + mockSetup: func() { + mockRepo.EXPECT(). + FindByName(gomock.Any(), gomock.Any(), gomock.Any(), "Test Product"). + Return(true, nil) + mockRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Product{ + ID: "123", + OrganizationID: "org123", + LedgerID: "ledger123", + Name: "Test Product", + Status: mmodel.Status{Code: "ACTIVE"}, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + Metadata: nil, + }, nil) // Produto criado com sucesso + }, + expectErr: false, + expectedProd: &mmodel.Product{ + Name: "Test Product", + Status: mmodel.Status{Code: "ACTIVE"}, + }, + }, + { + name: "Error when FindByName fails", + organizationID: uuid.New(), + ledgerID: uuid.New(), + input: &mmodel.CreateProductInput{ + Name: "Failing Product", + Status: mmodel.Status{ + Code: "ACTIVE", + }, + Metadata: nil, + }, + mockSetup: func() { + mockRepo.EXPECT(). + FindByName(gomock.Any(), gomock.Any(), gomock.Any(), "Failing Product"). + Return(false, fmt.Errorf("repository error")) + }, + expectErr: true, + expectedProd: nil, + }, + { + name: "Success with default status", + organizationID: uuid.New(), + ledgerID: uuid.New(), + input: &mmodel.CreateProductInput{ + Name: "Default Status Product", + Status: mmodel.Status{}, // Empty status + Metadata: nil, + }, + mockSetup: func() { + mockRepo.EXPECT(). + FindByName(gomock.Any(), gomock.Any(), gomock.Any(), "Default Status Product"). + Return(true, nil) + mockRepo.EXPECT(). + Create(gomock.Any(), gomock.Any()). + Return(&mmodel.Product{ + ID: "124", + OrganizationID: "org124", + LedgerID: "ledger124", + Name: "Default Status Product", + Status: mmodel.Status{Code: "ACTIVE"}, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + Metadata: nil, + }, nil) + }, + expectErr: false, + expectedProd: &mmodel.Product{ + Name: "Default Status Product", + Status: mmodel.Status{Code: "ACTIVE"}, + }, + }, } - uc.ProductRepo.(*product.MockRepository). - EXPECT(). - Create(gomock.Any(), p). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.ProductRepo.Create(context.TODO(), p) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) + ctx := context.Background() + result, err := uc.CreateProduct(ctx, tt.organizationID, tt.ledgerID, tt.input) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.expectedProd.Name, result.Name) + assert.Equal(t, tt.expectedProd.Status.Code, result.Status.Code) + } + }) + } } diff --git a/components/ledger/internal/services/command/delete-account_test.go b/components/ledger/internal/services/command/delete-account_test.go index 65c61c21..49bc77be 100644 --- a/components/ledger/internal/services/command/delete-account_test.go +++ b/components/ledger/internal/services/command/delete-account_test.go @@ -3,15 +3,117 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "go.uber.org/mock/gomock" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) +func TestDeleteAccountByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + // Mocks + mockAccountRepo := account.NewMockRepository(ctrl) + + uc := &UseCase{ + AccountRepo: mockAccountRepo, + } + + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() + portfolioID := uuid.New() + accountID := uuid.New() + + tests := []struct { + name string + portfolioID *uuid.UUID + setupMocks func() + expectedErr error + }{ + { + name: "success - account deleted", + portfolioID: &portfolioID, + setupMocks: func() { + mockAccountRepo.EXPECT(). + Find(gomock.Any(), organizationID, ledgerID, nil, accountID). + Return(&mmodel.Account{ID: accountID.String()}, nil). + Times(1) + + mockAccountRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, &portfolioID, accountID). + Return(nil). + Times(1) + }, + expectedErr: nil, + }, + { + name: "failure - account not found", + portfolioID: nil, + setupMocks: func() { + mockAccountRepo.EXPECT(). + Find(gomock.Any(), organizationID, ledgerID, nil, accountID). + Return(nil, services.ErrDatabaseItemNotFound). + Times(1) + }, + expectedErr: errors.New("errDatabaseItemNotFound"), + }, + { + name: "failure - forbidden external account manipulation", + portfolioID: nil, + setupMocks: func() { + mockAccountRepo.EXPECT(). + Find(gomock.Any(), organizationID, ledgerID, nil, accountID). + Return(&mmodel.Account{ID: accountID.String(), Type: "external"}, nil). + Times(1) + }, + expectedErr: errors.New("0074 - Accounts of type 'external' cannot be deleted or modified as they are used for traceability with external systems. Please review your request and ensure operations are only performed on internal accounts."), + }, + { + name: "failure - delete operation error", + portfolioID: &portfolioID, + setupMocks: func() { + mockAccountRepo.EXPECT(). + Find(gomock.Any(), organizationID, ledgerID, nil, accountID). + Return(&mmodel.Account{ID: accountID.String()}, nil). + Times(1) + + mockAccountRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, &portfolioID, accountID). + Return(errors.New("delete error")). + Times(1) + }, + expectedErr: errors.New("delete error"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Configuração dos mocks + tt.setupMocks() + + // Executa a função + err := uc.DeleteAccountByID(ctx, organizationID, ledgerID, tt.portfolioID, accountID) + + // Validações + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + } else { + assert.NoError(t, err) + } + }) + } +} + // TestDeleteAccountByIDSuccess is responsible to test DeleteAccountByID with success func TestDeleteAccountByIDSuccess(t *testing.T) { organizationID := pkg.GenerateUUIDv7() diff --git a/components/ledger/internal/services/command/delete-asset_test.go b/components/ledger/internal/services/command/delete-asset_test.go index 8258e000..94e39017 100644 --- a/components/ledger/internal/services/command/delete-asset_test.go +++ b/components/ledger/internal/services/command/delete-asset_test.go @@ -3,15 +3,275 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/asset" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) +func TestDeleteAssetByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockAssetRepo := asset.NewMockRepository(ctrl) + mockAccountRepo := account.NewMockRepository(ctrl) + + uc := &UseCase{ + AssetRepo: mockAssetRepo, + AccountRepo: mockAccountRepo, + } + + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + assetID uuid.UUID + mockSetup func() + expectErr bool + }{ + { + name: "Success - Delete asset and external account", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + mockSetup: func() { + mockAssetRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Asset{ID: uuid.New().String(), Code: "asset123"}, nil) + mockAccountRepo.EXPECT(). + ListAccountsByAlias(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mmodel.Account{{ID: uuid.New().String()}}, nil) + mockAccountRepo.EXPECT(). + Delete(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil) + mockAssetRepo.EXPECT(). + Delete(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil) + }, + expectErr: false, + }, + { + name: "Error - Asset not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + mockSetup: func() { + mockAssetRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + }, + { + name: "Error - Failure to list external accounts", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + mockSetup: func() { + mockAssetRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Asset{ID: uuid.New().String(), Code: "asset123"}, nil) + mockAccountRepo.EXPECT(). + ListAccountsByAlias(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("error listing accounts")) + }, + expectErr: true, + }, + // { + // name: "Error - Failure to delete asset", + // organizationID: uuid.New(), + // ledgerID: uuid.New(), + // assetID: uuid.New(), + // mockSetup: func() { + // mockAssetRepo.EXPECT(). + // Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + // Return(&mmodel.Asset{ID: uuid.New().String(), Code: "asset123"}, nil) + // mockAccountRepo.EXPECT(). + // ListAccountsByAlias(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + // Return([]mmodel.Account{}, nil) + // mockAssetRepo.EXPECT(). + // Delete(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + // Return(fmt.Errorf("error deleting asset")) + // }, + // expectErr: true, + // }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + err := uc.DeleteAssetByID(ctx, tt.organizationID, tt.ledgerID, tt.assetID) + + if tt.expectErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +// func TestDeleteAssetByID(t *testing.T) { +// ctrl := gomock.NewController(t) +// defer ctrl.Finish() +// +// // Mocks +// mockAssetRepo := asset.NewMockRepository(ctrl) +// mockAccountRepo := account.NewMockRepository(ctrl) +// +// uc := &UseCase{ +// AssetRepo: mockAssetRepo, +// AccountRepo: mockAccountRepo, +// } +// +// ctx := context.Background() +// organizationID := uuid.New() +// ledgerID := uuid.New() +// assetID := uuid.New() +// +// tests := []struct { +// name string +// setupMocks func() +// expectedErr error +// }{ +// { +// name: "success - asset deleted with external account", +// setupMocks: func() { +// // Simula encontrar o asset +// mockAssetRepo.EXPECT(). +// Find(gomock.Any(), organizationID, ledgerID, assetID). +// Return(&mmodel.Asset{ID: assetID.String(), Code: "USD"}, nil). +// Times(1) +// +// // Simula encontrar conta externa associada +// mockAccountRepo.EXPECT(). +// ListAccountsByAlias(gomock.Any(), organizationID, ledgerID, []string{"EXT-USD"}). +// Return([]mmodel.Account{ +// {ID: uuid.New().String()}, +// }, nil). +// Times(1) +// +// // Simula exclusão da conta externa +// mockAccountRepo.EXPECT(). +// Delete(gomock.Any(), organizationID, ledgerID, nil, gomock.Any()). +// Return(nil). +// Times(1) +// +// // Simula exclusão do asset +// mockAssetRepo.EXPECT(). +// Delete(gomock.Any(), organizationID, ledgerID, assetID). +// Return(nil). +// Times(1) +// }, +// expectedErr: nil, +// }, +// { +// name: "success - asset deleted without external account", +// setupMocks: func() { +// // Simula encontrar o asset +// mockAssetRepo.EXPECT(). +// Find(gomock.Any(), organizationID, ledgerID, assetID). +// Return(&mmodel.Asset{ID: assetID.String(), Code: "USD"}, nil). +// Times(1) +// +// // Simula não encontrar contas externas +// mockAccountRepo.EXPECT(). +// ListAccountsByAlias(gomock.Any(), organizationID, ledgerID, []string{"EXT-USD"}). +// Return([]mmodel.Account{}, nil). +// Times(1) +// +// // Simula exclusão do asset +// mockAssetRepo.EXPECT(). +// Delete(gomock.Any(), organizationID, ledgerID, assetID). +// Return(nil). +// Times(1) +// }, +// expectedErr: nil, +// }, +// { +// name: "failure - asset not found", +// setupMocks: func() { +// mockAssetRepo.EXPECT(). +// Find(gomock.Any(), organizationID, ledgerID, assetID). +// Return(nil, services.ErrDatabaseItemNotFound). +// Times(1) +// }, +// expectedErr: constant.ErrAssetIDNotFound, +// }, +// { +// name: "failure - delete external account error", +// setupMocks: func() { +// mockAssetRepo.EXPECT(). +// Find(gomock.Any(), organizationID, ledgerID, assetID). +// Return(&mmodel.Asset{ID: assetID.String(), Code: "USD"}, nil). +// Times(1) +// +// mockAccountRepo.EXPECT(). +// ListAccountsByAlias(gomock.Any(), organizationID, ledgerID, []string{"EXT-USD"}). +// Return([]mmodel.Account{ +// {ID: uuid.New().String()}, +// }, nil). +// Times(1) +// +// mockAccountRepo.EXPECT(). +// Delete(gomock.Any(), organizationID, ledgerID, nil, gomock.Any()). +// Return(errors.New("failed to delete external account")). +// Times(1) +// }, +// expectedErr: errors.New("failed to delete external account"), +// }, +// { +// name: "failure - delete asset error", +// setupMocks: func() { +// mockAssetRepo.EXPECT(). +// Find(gomock.Any(), organizationID, ledgerID, assetID). +// Return(&mmodel.Asset{ID: assetID.String(), Code: "USD"}, nil). +// Times(1) +// +// mockAccountRepo.EXPECT(). +// ListAccountsByAlias(gomock.Any(), organizationID, ledgerID, []string{"EXT-USD"}). +// Return([]mmodel.Account{}, nil). +// Times(1) +// +// mockAssetRepo.EXPECT(). +// Delete(gomock.Any(), organizationID, ledgerID, assetID). +// Return(errors.New("failed to delete asset")). +// Times(1) +// }, +// expectedErr: errors.New("failed to delete asset"), +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Configura os mocks +// tt.setupMocks() +// +// // Executa a função +// err := uc.DeleteAssetByID(ctx, organizationID, ledgerID, assetID) +// +// // Validações +// if tt.expectedErr != nil { +// assert.Error(t, err) +// assert.Equal(t, tt.expectedErr.Error(), err.Error()) +// } else { +// assert.NoError(t, err) +// } +// }) +// } +// } + // TestDeleteAssetByIDSuccess is responsible to test DeleteAssetByID with success func TestDeleteAssetByIDSuccess(t *testing.T) { id := pkg.GenerateUUIDv7() diff --git a/components/ledger/internal/services/command/delete-ledger_test.go b/components/ledger/internal/services/command/delete-ledger_test.go index ffe49296..42863412 100644 --- a/components/ledger/internal/services/command/delete-ledger_test.go +++ b/components/ledger/internal/services/command/delete-ledger_test.go @@ -3,51 +3,80 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "go.uber.org/mock/gomock" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestDeleteLedgerByIDSuccess is responsible to test DeleteLedgerByID with success -func TestDeleteLedgerByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - - uc := UseCase{ - LedgerRepo: ledger.NewMockRepository(gomock.NewController(t)), - } +func TestDeleteLedgerByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - uc.LedgerRepo.(*ledger.MockRepository). - EXPECT(). - Delete(gomock.Any(), organizationID, id). - Return(nil). - Times(1) - err := uc.LedgerRepo.Delete(context.TODO(), organizationID, id) + mockLedgerRepo := ledger.NewMockRepository(ctrl) - assert.Nil(t, err) -} + uc := &UseCase{ + LedgerRepo: mockLedgerRepo, + } -// TestDeleteLedgerByIDError is responsible to test DeleteLedgerByID with error -func TestDeleteLedgerByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() - uc := UseCase{ - LedgerRepo: ledger.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + setupMocks func() + expectedErr error + }{ + { + name: "success - ledger deleted", + setupMocks: func() { + mockLedgerRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID). + Return(nil). + Times(1) + }, + expectedErr: nil, + }, + { + name: "failure - ledger not found", + setupMocks: func() { + mockLedgerRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID). + Return(services.ErrDatabaseItemNotFound). + Times(1) + }, + expectedErr: errors.New("The provided ledger ID does not exist in our records. Please verify the ledger ID and try again."), + }, + { + name: "failure - repository error", + setupMocks: func() { + mockLedgerRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID). + Return(errors.New("failed to delete ledger")). + Times(1) + }, + expectedErr: errors.New("failed to delete ledger"), + }, } - uc.LedgerRepo.(*ledger.MockRepository). - EXPECT(). - Delete(gomock.Any(), organizationID, id). - Return(errors.New(errMSG)). - Times(1) - err := uc.LedgerRepo.Delete(context.TODO(), organizationID, id) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) + err := uc.DeleteLedgerByID(ctx, organizationID, ledgerID) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + } else { + assert.NoError(t, err) + } + }) + } } diff --git a/components/ledger/internal/services/command/delete-metadata_test.go b/components/ledger/internal/services/command/delete-metadata_test.go deleted file mode 100644 index 3d1e2bd6..00000000 --- a/components/ledger/internal/services/command/delete-metadata_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package command - -import ( - "context" - "errors" - "go.uber.org/mock/gomock" - "reflect" - "testing" - - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" - "github.com/LerianStudio/midaz/pkg" - "github.com/LerianStudio/midaz/pkg/mmodel" - - "github.com/stretchr/testify/assert" -) - -// TestMetadataDeleteSuccess is responsible to test MetadataDelete with success -func TestMetadataDeleteSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7().String() - collection := reflect.TypeOf(mmodel.Organization{}).Name() - uc := UseCase{ - MetadataRepo: mongodb.NewMockRepository(gomock.NewController(t)), - } - - uc.MetadataRepo.(*mongodb.MockRepository). - EXPECT(). - Delete(gomock.Any(), collection, id). - Return(nil). - Times(1) - - err := uc.MetadataRepo.Delete(context.TODO(), collection, id) - assert.Nil(t, err) -} - -// TestMetadataDeleteError is responsible to test MetadataDelete with error -func TestMetadataDeleteError(t *testing.T) { - errMSG := "err to delete metadata on mongodb" - id := pkg.GenerateUUIDv7().String() - collection := reflect.TypeOf(mmodel.Organization{}).Name() - uc := UseCase{ - MetadataRepo: mongodb.NewMockRepository(gomock.NewController(t)), - } - - uc.MetadataRepo.(*mongodb.MockRepository). - EXPECT(). - Delete(gomock.Any(), collection, id). - Return(errors.New(errMSG)). - Times(1) - - err := uc.MetadataRepo.Delete(context.TODO(), collection, id) - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) -} diff --git a/components/ledger/internal/services/command/delete-organization_test.go b/components/ledger/internal/services/command/delete-organization_test.go index ef447641..82e069e5 100644 --- a/components/ledger/internal/services/command/delete-organization_test.go +++ b/components/ledger/internal/services/command/delete-organization_test.go @@ -3,49 +3,79 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "go.uber.org/mock/gomock" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestDeleteOrganizationByIDSuccess is responsible to test DeleteOrganizationByID with success -func TestDeleteOrganizationByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - - uc := UseCase{ - OrganizationRepo: organization.NewMockRepository(gomock.NewController(t)), - } +func TestDeleteOrganizationByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - uc.OrganizationRepo.(*organization.MockRepository). - EXPECT(). - Delete(gomock.Any(), id). - Return(nil). - Times(1) - err := uc.OrganizationRepo.Delete(context.TODO(), id) + mockOrganizationRepo := organization.NewMockRepository(ctrl) - assert.Nil(t, err) -} + uc := &UseCase{ + OrganizationRepo: mockOrganizationRepo, + } -// TestDeleteOrganizationByIDError is responsible to test DeleteOrganizationByID with error -func TestDeleteOrganizationByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" + ctx := context.Background() + organizationID := uuid.New() - uc := UseCase{ - OrganizationRepo: organization.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + setupMocks func() + expectedErr error + }{ + { + name: "success - organization deleted", + setupMocks: func() { + mockOrganizationRepo.EXPECT(). + Delete(gomock.Any(), organizationID). + Return(nil). + Times(1) + }, + expectedErr: nil, + }, + { + name: "failure - organization not found", + setupMocks: func() { + mockOrganizationRepo.EXPECT(). + Delete(gomock.Any(), organizationID). + Return(services.ErrDatabaseItemNotFound). + Times(1) + }, + expectedErr: errors.New("The provided organization ID does not exist in our records. Please verify the organization ID and try again."), + }, + { + name: "failure - repository error", + setupMocks: func() { + mockOrganizationRepo.EXPECT(). + Delete(gomock.Any(), organizationID). + Return(errors.New("failed to delete organization")). + Times(1) + }, + expectedErr: errors.New("failed to delete organization"), + }, } - uc.OrganizationRepo.(*organization.MockRepository). - EXPECT(). - Delete(gomock.Any(), id). - Return(errors.New(errMSG)). - Times(1) - err := uc.OrganizationRepo.Delete(context.TODO(), id) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) + err := uc.DeleteOrganizationByID(ctx, organizationID) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + } else { + assert.NoError(t, err) + } + }) + } } diff --git a/components/ledger/internal/services/command/delete-portfolio_test.go b/components/ledger/internal/services/command/delete-portfolio_test.go index 634f0622..6e0a74be 100644 --- a/components/ledger/internal/services/command/delete-portfolio_test.go +++ b/components/ledger/internal/services/command/delete-portfolio_test.go @@ -3,53 +3,81 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "go.uber.org/mock/gomock" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestDeletePortfolioByIDSuccess is responsible to test DeletePortfolioByID with success -func TestDeletePortfolioByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - - uc := UseCase{ - PortfolioRepo: portfolio.NewMockRepository(gomock.NewController(t)), - } +func TestDeletePortfolioByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - uc.PortfolioRepo.(*portfolio.MockRepository). - EXPECT(). - Delete(gomock.Any(), organizationID, ledgerID, id). - Return(nil). - Times(1) - err := uc.PortfolioRepo.Delete(context.TODO(), organizationID, ledgerID, id) + mockPortfolioRepo := portfolio.NewMockRepository(ctrl) - assert.Nil(t, err) -} + uc := &UseCase{ + PortfolioRepo: mockPortfolioRepo, + } -// TestDeletePortfolioByIDError is responsible to test DeletePortfolioByID with error -func TestDeletePortfolioByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() + portfolioID := uuid.New() - uc := UseCase{ - PortfolioRepo: portfolio.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + setupMocks func() + expectedErr error + }{ + { + name: "success - portfolio deleted", + setupMocks: func() { + mockPortfolioRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, portfolioID). + Return(nil). + Times(1) + }, + expectedErr: nil, + }, + { + name: "failure - portfolio not found", + setupMocks: func() { + mockPortfolioRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, portfolioID). + Return(services.ErrDatabaseItemNotFound). + Times(1) + }, + expectedErr: errors.New("The provided portfolio ID does not exist in our records. Please verify the portfolio ID and try again."), + }, + { + name: "failure - repository error", + setupMocks: func() { + mockPortfolioRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, portfolioID). + Return(errors.New("failed to delete portfolio")). + Times(1) + }, + expectedErr: errors.New("failed to delete portfolio"), + }, } - uc.PortfolioRepo.(*portfolio.MockRepository). - EXPECT(). - Delete(gomock.Any(), organizationID, ledgerID, id). - Return(errors.New(errMSG)). - Times(1) - err := uc.PortfolioRepo.Delete(context.TODO(), organizationID, ledgerID, id) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) + err := uc.DeletePortfolioByID(ctx, organizationID, ledgerID, portfolioID) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + } else { + assert.NoError(t, err) + } + }) + } } diff --git a/components/ledger/internal/services/command/delete-product_test.go b/components/ledger/internal/services/command/delete-product_test.go index 74339954..f9e3b0b0 100644 --- a/components/ledger/internal/services/command/delete-product_test.go +++ b/components/ledger/internal/services/command/delete-product_test.go @@ -3,53 +3,81 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "go.uber.org/mock/gomock" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestDeleteProductByIDSuccess is responsible to test DeleteProductByID with success -func TestDeleteProductByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - - uc := UseCase{ - ProductRepo: product.NewMockRepository(gomock.NewController(t)), - } +func TestDeleteProductByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - uc.ProductRepo.(*product.MockRepository). - EXPECT(). - Delete(gomock.Any(), organizationID, ledgerID, id). - Return(nil). - Times(1) - err := uc.ProductRepo.Delete(context.TODO(), organizationID, ledgerID, id) + mockProductRepo := product.NewMockRepository(ctrl) - assert.Nil(t, err) -} + uc := &UseCase{ + ProductRepo: mockProductRepo, + } -// TestDeleteProductByIDError is responsible to test DeleteProductByID with error -func TestDeleteProductByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() + productID := uuid.New() - uc := UseCase{ - ProductRepo: product.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + setupMocks func() + expectedErr error + }{ + { + name: "success - product deleted", + setupMocks: func() { + mockProductRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, productID). + Return(nil). + Times(1) + }, + expectedErr: nil, + }, + { + name: "failure - product not found", + setupMocks: func() { + mockProductRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, productID). + Return(services.ErrDatabaseItemNotFound). + Times(1) + }, + expectedErr: errors.New("The provided product ID does not exist in our records. Please verify the product ID and try again."), + }, + { + name: "failure - repository error", + setupMocks: func() { + mockProductRepo.EXPECT(). + Delete(gomock.Any(), organizationID, ledgerID, productID). + Return(errors.New("failed to delete product")). + Times(1) + }, + expectedErr: errors.New("failed to delete product"), + }, } - uc.ProductRepo.(*product.MockRepository). - EXPECT(). - Delete(gomock.Any(), organizationID, ledgerID, id). - Return(errors.New(errMSG)). - Times(1) - err := uc.ProductRepo.Delete(context.TODO(), organizationID, ledgerID, id) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) + err := uc.DeleteProductByID(ctx, organizationID, ledgerID, productID) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + } else { + assert.NoError(t, err) + } + }) + } } diff --git a/components/ledger/internal/services/command/update-account-id_test.go b/components/ledger/internal/services/command/update-account-id_test.go new file mode 100644 index 00000000..aa8246e0 --- /dev/null +++ b/components/ledger/internal/services/command/update-account-id_test.go @@ -0,0 +1,123 @@ +package command + +import ( + "context" + "errors" + "testing" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/LerianStudio/midaz/components/mdz/pkg/ptr" + "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" +) + +func TestUpdateAccountByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockAccountRepo := account.NewMockRepository(ctrl) + + uc := &UseCase{ + AccountRepo: mockAccountRepo, + } + + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() + accountID := uuid.New() + + tests := []struct { + name string + balance *mmodel.Balance + setupMocks func() + expectedErr error + expectedAcct *mmodel.Account + }{ + { + name: "success - account updated", + balance: &mmodel.Balance{ + Available: ptr.Float64Ptr(100.0), + OnHold: ptr.Float64Ptr(10.0), + Scale: ptr.Float64Ptr(0.01), + }, + setupMocks: func() { + updatedAccount := &mmodel.Account{ + ID: accountID.String(), + Balance: mmodel.Balance{ + Available: ptr.Float64Ptr(100.0), + OnHold: ptr.Float64Ptr(10.0), + Scale: ptr.Float64Ptr(0.01), + }, + } + + mockAccountRepo.EXPECT(). + UpdateAccountByID(gomock.Any(), organizationID, ledgerID, accountID, gomock.Any()). + Return(updatedAccount, nil). + Times(1) + }, + expectedErr: nil, + expectedAcct: &mmodel.Account{ + ID: accountID.String(), + Balance: mmodel.Balance{ + Available: ptr.Float64Ptr(100.0), + OnHold: ptr.Float64Ptr(10.0), + Scale: ptr.Float64Ptr(0.01), + }, + }, + }, + { + name: "failure - account not found", + balance: &mmodel.Balance{ + Available: ptr.Float64Ptr(50.0), + OnHold: ptr.Float64Ptr(5.0), + Scale: ptr.Float64Ptr(0.01), + }, + setupMocks: func() { + mockAccountRepo.EXPECT(). + UpdateAccountByID(gomock.Any(), organizationID, ledgerID, accountID, gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound). + Times(1) + }, + expectedErr: errors.New("The provided account ID does not exist in our records. Please verify the account ID and try again."), + expectedAcct: nil, + }, + { + name: "failure - repository error", + balance: &mmodel.Balance{ + Available: ptr.Float64Ptr(200.0), + OnHold: ptr.Float64Ptr(20.0), + Scale: ptr.Float64Ptr(0.01), + }, + setupMocks: func() { + mockAccountRepo.EXPECT(). + UpdateAccountByID(gomock.Any(), organizationID, ledgerID, accountID, gomock.Any()). + Return(nil, errors.New("failed to update account")). + Times(1) + }, + expectedErr: errors.New("failed to update account"), + expectedAcct: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() + + result, err := uc.UpdateAccountByID(ctx, organizationID, ledgerID, accountID, tt.balance) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.expectedAcct.ID, result.ID) + assert.Equal(t, tt.expectedAcct.Balance, result.Balance) + } + }) + } +} diff --git a/components/ledger/internal/services/command/update-account_test.go b/components/ledger/internal/services/command/update-account_test.go index eab2c9cf..744f223b 100644 --- a/components/ledger/internal/services/command/update-account_test.go +++ b/components/ledger/internal/services/command/update-account_test.go @@ -2,92 +2,142 @@ package command import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" - "time" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" - + "github.com/google/uuid" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) -// TestUpdateAccountByIDSuccess is responsible to test UpdateAccountByID with success -func TestUpdateAccountByIDSuccess(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - portfolioID := pkg.GenerateUUIDv7() - id := pkg.GenerateUUIDv7() - a := &mmodel.Account{ - ID: id.String(), - UpdatedAt: time.Now(), - } +func TestUpdateAccount(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), - } - - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, ledgerID, &portfolioID, id, a). - Return(a, nil). - Times(1) - res, err := uc.AccountRepo.Update(context.TODO(), organizationID, ledgerID, &portfolioID, id, a) + mockAccountRepo := account.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - assert.Equal(t, a, res) - assert.Nil(t, err) -} - -// TestUpdateAccountByIDWithoutPortfolioSuccess is responsible to test UpdateAccountByIDWithoutPortfolio with success -func TestUpdateAccountByIDWithoutPortfolioSuccess(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - id := pkg.GenerateUUIDv7() - a := &mmodel.Account{ - ID: id.String(), - UpdatedAt: time.Now(), + uc := &UseCase{ + AccountRepo: mockAccountRepo, + MetadataRepo: mockMetadataRepo, } - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + portfolioID *uuid.UUID + accountID uuid.UUID + input *mmodel.UpdateAccountInput + mockSetup func() + expectErr bool + }{ + { + name: "Success - Account updated with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + accountID: uuid.New(), + input: &mmodel.UpdateAccountInput{ + Name: "Updated Account", + Status: mmodel.Status{ + Code: "active", + }, + Alias: nil, + ProductID: nil, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockAccountRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ID: "123", Type: "internal"}, nil) + mockAccountRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ID: "123", Name: "Updated Account", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil) + }, + expectErr: false, + }, + { + name: "Error - Account not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + accountID: uuid.New(), + input: &mmodel.UpdateAccountInput{ + Name: "Nonexistent Account", + Status: mmodel.Status{ + Code: "active", + }, + Alias: nil, + ProductID: nil, + Metadata: nil, + }, + mockSetup: func() { + mockAccountRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + }, + { + name: "Error - Failed to update metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + accountID: uuid.New(), + input: &mmodel.UpdateAccountInput{ + Name: "Updated Account", + Status: mmodel.Status{ + Code: "active", + }, + Alias: nil, + ProductID: nil, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockAccountRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ID: "123", Type: "internal"}, nil) + mockAccountRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ID: "123", Name: "Updated Account", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(fmt.Errorf("metadata update error")) + }, + expectErr: true, + }, } - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, ledgerID, nil, id, a). - Return(a, nil). - Times(1) - res, err := uc.AccountRepo.Update(context.TODO(), organizationID, ledgerID, nil, id, a) - - assert.Equal(t, a, res) - assert.Nil(t, err) -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() -// TestUpdateAccountByIDError is responsible to test UpdateAccountByID with error -func TestUpdateAccountByIDError(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - portfolioID := pkg.GenerateUUIDv7() - id := pkg.GenerateUUIDv7() - a := &mmodel.Account{ - ID: id.String(), - UpdatedAt: time.Now(), - } + ctx := context.Background() + result, err := uc.UpdateAccount(ctx, tt.organizationID, tt.ledgerID, tt.portfolioID, tt.accountID, tt.input) - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.input.Name, result.Name) + assert.Equal(t, tt.input.Status, result.Status) + } + }) } - - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, ledgerID, &portfolioID, id, a). - Return(nil, errors.New(errMSG)) - res, err := uc.AccountRepo.Update(context.TODO(), organizationID, ledgerID, &portfolioID, id, a) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/command/update-asset_test.go b/components/ledger/internal/services/command/update-asset_test.go index 45070e45..51079579 100644 --- a/components/ledger/internal/services/command/update-asset_test.go +++ b/components/ledger/internal/services/command/update-asset_test.go @@ -2,69 +2,147 @@ package command import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" - "time" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/asset" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestUpdateAssetByIDSuccess is responsible to test UpdateAssetByID with success -func TestUpdateAssetByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - a := &mmodel.Asset{ - ID: id.String(), - LedgerID: ledgerID.String(), - OrganizationID: organizationID.String(), - UpdatedAt: time.Now(), - } - - uc := UseCase{ - AssetRepo: asset.NewMockRepository(gomock.NewController(t)), - } - - uc.AssetRepo.(*asset.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, ledgerID, id, a). - Return(a, nil). - Times(1) - res, err := uc.AssetRepo.Update(context.TODO(), organizationID, ledgerID, id, a) +func TestUpdateAssetByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - assert.Equal(t, a, res) - assert.Nil(t, err) -} + mockAssetRepo := asset.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) -// TestUpdateAssetByIDError is responsible to test UpdateAssetByID with error -func TestUpdateAssetByIDError(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - id := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - a := &mmodel.Asset{ - ID: id.String(), - LedgerID: ledgerID.String(), - OrganizationID: organizationID.String(), - UpdatedAt: time.Now(), + uc := &UseCase{ + AssetRepo: mockAssetRepo, + MetadataRepo: mockMetadataRepo, } - uc := UseCase{ - AssetRepo: asset.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + assetID uuid.UUID + input *mmodel.UpdateAssetInput + mockSetup func() + expectErr bool + }{ + { + name: "Success - Asset updated with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + input: &mmodel.UpdateAssetInput{ + Name: "Updated Asset", + Status: mmodel.Status{ + Code: "active", + }, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockAssetRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Asset{ID: "123", Name: "Updated Asset", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil) + }, + expectErr: false, + }, + { + name: "Error - Asset not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + input: &mmodel.UpdateAssetInput{ + Name: "Nonexistent Asset", + Status: mmodel.Status{ + Code: "inactive", + }, + Metadata: nil, + }, + mockSetup: func() { + mockAssetRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + }, + { + name: "Error - Failed to update metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + input: &mmodel.UpdateAssetInput{ + Name: "Asset with Metadata Error", + Status: mmodel.Status{ + Code: "active", + }, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockAssetRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Asset{ID: "123", Name: "Asset with Metadata Error", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(fmt.Errorf("metadata update error")) + }, + expectErr: true, + }, + { + name: "Error - Failure to update asset", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + input: &mmodel.UpdateAssetInput{ + Name: "Update Failure Asset", + Status: mmodel.Status{ + Code: "inactive", + }, + Metadata: nil, + }, + mockSetup: func() { + mockAssetRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("update error")) + }, + expectErr: true, + }, } - uc.AssetRepo.(*asset.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, ledgerID, id, a). - Return(nil, errors.New(errMSG)) - res, err := uc.AssetRepo.Update(context.TODO(), organizationID, ledgerID, id, a) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) + ctx := context.Background() + result, err := uc.UpdateAssetByID(ctx, tt.organizationID, tt.ledgerID, tt.assetID, tt.input) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.input.Name, result.Name) + assert.Equal(t, tt.input.Status, result.Status) + } + }) + } } diff --git a/components/ledger/internal/services/command/update-ledger_test.go b/components/ledger/internal/services/command/update-ledger_test.go index 83f1e674..db0f387f 100644 --- a/components/ledger/internal/services/command/update-ledger_test.go +++ b/components/ledger/internal/services/command/update-ledger_test.go @@ -2,68 +2,134 @@ package command import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" - "time" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestUpdateLedgerByIDSuccess is responsible to test UpdateLedgerByID with success -func TestUpdateLedgerByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() +func TestUpdateLedgerByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - l := &mmodel.Ledger{ - ID: id.String(), - OrganizationID: organizationID.String(), - UpdatedAt: time.Now(), - } + mockLedgerRepo := ledger.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - LedgerRepo: ledger.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + LedgerRepo: mockLedgerRepo, + MetadataRepo: mockMetadataRepo, } - uc.LedgerRepo.(*ledger.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, id, l). - Return(l, nil). - Times(1) - res, err := uc.LedgerRepo.Update(context.TODO(), organizationID, id, l) - - assert.Equal(t, l, res) - assert.Nil(t, err) -} - -// TestUpdateLedgerByIDError is responsible to test UpdateLedgerByID with error -func TestUpdateLedgerByIDError(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - - l := &mmodel.Ledger{ - ID: id.String(), - OrganizationID: organizationID.String(), - UpdatedAt: time.Now(), + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + input *mmodel.UpdateLedgerInput + mockSetup func() + expectErr bool + }{ + { + name: "Success - Ledger updated with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + input: &mmodel.UpdateLedgerInput{ + Name: "Updated Ledger", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockLedgerRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Ledger{ID: "123", Name: "Updated Ledger", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil) + }, + expectErr: false, + }, + { + name: "Error - Ledger not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + input: &mmodel.UpdateLedgerInput{ + Name: "Nonexistent Ledger", + Status: mmodel.Status{Code: "inactive"}, + Metadata: nil, + }, + mockSetup: func() { + mockLedgerRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + }, + { + name: "Error - Failed to update metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + input: &mmodel.UpdateLedgerInput{ + Name: "Ledger with Metadata Error", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockLedgerRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Ledger{ID: "123", Name: "Ledger with Metadata Error", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(fmt.Errorf("metadata update error")) + }, + expectErr: true, + }, + { + name: "Error - Failure to update ledger", + organizationID: uuid.New(), + ledgerID: uuid.New(), + input: &mmodel.UpdateLedgerInput{ + Name: "Update Failure Ledger", + Status: mmodel.Status{Code: "inactive"}, + Metadata: nil, + }, + mockSetup: func() { + mockLedgerRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("update error")) + }, + expectErr: true, + }, } - uc := UseCase{ - LedgerRepo: ledger.NewMockRepository(gomock.NewController(t)), - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() - uc.LedgerRepo.(*ledger.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, id, l). - Return(nil, errors.New(errMSG)) - res, err := uc.LedgerRepo.Update(context.TODO(), organizationID, id, l) + ctx := context.Background() + result, err := uc.UpdateLedgerByID(ctx, tt.organizationID, tt.ledgerID, tt.input) - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.input.Name, result.Name) + assert.Equal(t, tt.input.Status, result.Status) + } + }) + } } diff --git a/components/ledger/internal/services/command/update-metadata_test.go b/components/ledger/internal/services/command/update-metadata_test.go index f879c670..a97f267d 100644 --- a/components/ledger/internal/services/command/update-metadata_test.go +++ b/components/ledger/internal/services/command/update-metadata_test.go @@ -3,53 +3,144 @@ package command import ( "context" "errors" - "go.uber.org/mock/gomock" - "reflect" "testing" + "go.uber.org/mock/gomock" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" - "github.com/LerianStudio/midaz/pkg" - "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/stretchr/testify/assert" ) -// TestMetadataUpdateSuccess is responsible to test MetadataUpdate with success -func TestMetadataUpdateSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7().String() - metadata := map[string]any{} - collection := reflect.TypeOf(mmodel.Organization{}).Name() - uc := UseCase{ - MetadataRepo: mongodb.NewMockRepository(gomock.NewController(t)), +func TestUpdateMetadata(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + MetadataRepo: mockMetadataRepo, } - uc.MetadataRepo.(*mongodb.MockRepository). - EXPECT(). - Update(gomock.Any(), collection, id, metadata). - Return(nil). - Times(1) + ctx := context.Background() + entityName := "TestEntity" + entityID := "123456" - err := uc.MetadataRepo.Update(context.TODO(), collection, id, metadata) - assert.Nil(t, err) -} + tests := []struct { + name string + inputMetadata map[string]any + setupMocks func() + expectedErr error + expectedMetadata map[string]any + }{ + { + name: "success - metadata updated with new data", + inputMetadata: map[string]any{ + "key1": "value1", + "key2": "value2", + }, + setupMocks: func() { + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), entityName, entityID). + Return(nil, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), entityName, entityID, gomock.Any()). + Return(nil). + Times(1) + }, + expectedErr: nil, + expectedMetadata: map[string]any{ + "key1": "value1", + "key2": "value2", + }, + }, + { + name: "success - metadata updated with merged data", + inputMetadata: map[string]any{ + "key2": "new_value2", + "key3": "value3", + }, + setupMocks: func() { + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), entityName, entityID). + Return(&mongodb.Metadata{ + Data: map[string]any{ + "key1": "value1", + "key2": "value2", + }, + }, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), entityName, entityID, gomock.Any()). + DoAndReturn(func(_ context.Context, _, _ string, updatedMetadata map[string]any) error { + expectedMerged := map[string]any{ + "key1": "value1", + "key2": "new_value2", + "key3": "value3", + } + assert.Equal(t, expectedMerged, updatedMetadata) + return nil + }). + Times(1) + }, + expectedErr: nil, + expectedMetadata: map[string]any{ + "key1": "value1", + "key2": "new_value2", + "key3": "value3", + }, + }, + { + name: "failure - error retrieving existing metadata", + inputMetadata: map[string]any{"key1": "value1"}, + setupMocks: func() { + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), entityName, entityID). + Return(nil, errors.New("failed to retrieve metadata")). + Times(1) + }, + expectedErr: errors.New("failed to retrieve metadata"), + expectedMetadata: nil, + }, + { + name: "failure - error updating metadata", + inputMetadata: map[string]any{ + "key1": "value1", + }, + setupMocks: func() { + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), entityName, entityID). + Return(nil, nil). + Times(1) -// TestMetadataUpdateError is responsible to test MetadataUpdate with error -func TestMetadataUpdateError(t *testing.T) { - errMSG := "err to update metadata on mongodb" - id := pkg.GenerateUUIDv7().String() - metadata := map[string]any{} - collection := reflect.TypeOf(mmodel.Organization{}).Name() - uc := UseCase{ - MetadataRepo: mongodb.NewMockRepository(gomock.NewController(t)), + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), entityName, entityID, gomock.Any()). + Return(errors.New("failed to update metadata")). + Times(1) + }, + expectedErr: errors.New("failed to update metadata"), + expectedMetadata: nil, + }, } - uc.MetadataRepo.(*mongodb.MockRepository). - EXPECT(). - Update(gomock.Any(), collection, id, metadata). - Return(errors.New(errMSG)). - Times(1) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() - err := uc.MetadataRepo.Update(context.TODO(), collection, id, metadata) - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) + result, err := uc.UpdateMetadata(ctx, entityName, entityID, tt.inputMetadata) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.expectedMetadata, result) + } + }) + } } diff --git a/components/ledger/internal/services/command/update-organization_test.go b/components/ledger/internal/services/command/update-organization_test.go index e31fe07b..a809c3f2 100644 --- a/components/ledger/internal/services/command/update-organization_test.go +++ b/components/ledger/internal/services/command/update-organization_test.go @@ -2,55 +2,134 @@ package command import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" - "time" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/LerianStudio/midaz/components/mdz/pkg/ptr" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestUpdateOrganizationByIDSuccess is responsible to test UpdateOrganizationByID with success -func TestUpdateOrganizationByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - o := &mmodel.Organization{ID: id.String(), UpdatedAt: time.Now()} +func TestUpdateOrganizationByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockOrganizationRepo := organization.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - OrganizationRepo: organization.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + OrganizationRepo: mockOrganizationRepo, + MetadataRepo: mockMetadataRepo, } - uc.OrganizationRepo.(*organization.MockRepository). - EXPECT(). - Update(gomock.Any(), id, o). - Return(o, nil). - Times(1) - res, err := uc.OrganizationRepo.Update(context.TODO(), id, o) + tests := []struct { + name string + orgID uuid.UUID + input *mmodel.UpdateOrganizationInput + mockSetup func() + expectErr bool + }{ + { + name: "Success - Organization updated with metadata", + orgID: uuid.New(), + input: &mmodel.UpdateOrganizationInput{ + ParentOrganizationID: nil, + LegalName: "Updated Organization", + DoingBusinessAs: ptr.StringPtr("Updated DBA"), + Address: mmodel.Address{Country: "US"}, + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockOrganizationRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Organization{ + ID: "123", + LegalName: "Updated Organization", + DoingBusinessAs: ptr.StringPtr("Updated DBA"), + Address: mmodel.Address{Country: "US"}, + Status: mmodel.Status{Code: "active"}, + ParentOrganizationID: nil, + }, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil) + }, + expectErr: false, + }, + { + name: "Error - Invalid address", + orgID: uuid.New(), + input: &mmodel.UpdateOrganizationInput{ + Address: mmodel.Address{Country: "INVALID"}, + }, + mockSetup: func() {}, + expectErr: true, + }, + { + name: "Error - Organization not found", + orgID: uuid.New(), + input: &mmodel.UpdateOrganizationInput{ + LegalName: "Nonexistent Organization", + Address: mmodel.Address{Country: "US"}, + }, + mockSetup: func() { + mockOrganizationRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + }, + { + name: "Error - Failed to update metadata", + orgID: uuid.New(), + input: &mmodel.UpdateOrganizationInput{ + LegalName: "Organization with Metadata Error", + Address: mmodel.Address{Country: "US"}, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockOrganizationRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Organization{ID: "123"}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(fmt.Errorf("metadata update error")) + }, + expectErr: true, + }, + } - assert.Equal(t, o, res) - assert.Nil(t, err) -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() -// TestUpdateOrganizationByIDError is responsible to test UpdateOrganizationByID with error -func TestUpdateOrganizationByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" - o := &mmodel.Organization{ID: id.String(), UpdatedAt: time.Now()} + ctx := context.Background() + result, err := uc.UpdateOrganizationByID(ctx, tt.orgID, tt.input) - uc := UseCase{ - OrganizationRepo: organization.NewMockRepository(gomock.NewController(t)), + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.input.LegalName, result.LegalName) + assert.Equal(t, tt.input.Address, result.Address) + assert.Equal(t, tt.input.Status, result.Status) + } + }) } - - uc.OrganizationRepo.(*organization.MockRepository). - EXPECT(). - Update(gomock.Any(), id, o). - Return(nil, errors.New(errMSG)) - res, err := uc.OrganizationRepo.Update(context.TODO(), id, o) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/command/update-portfolio_test.go b/components/ledger/internal/services/command/update-portfolio_test.go index 45a38c48..47cb7c08 100644 --- a/components/ledger/internal/services/command/update-portfolio_test.go +++ b/components/ledger/internal/services/command/update-portfolio_test.go @@ -2,71 +2,137 @@ package command import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" - "time" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" - + "github.com/google/uuid" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) -// TestUpdatePortfolioByIDSuccess is responsible to test UpdatePortfolioByID with success -func TestUpdatePortfolioByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - p := &mmodel.Portfolio{ - ID: id.String(), - EntityID: pkg.GenerateUUIDv7().String(), - OrganizationID: organizationID.String(), - LedgerID: ledgerID.String(), - UpdatedAt: time.Now(), - } - - uc := UseCase{ - PortfolioRepo: portfolio.NewMockRepository(gomock.NewController(t)), - } - - uc.PortfolioRepo.(*portfolio.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, ledgerID, id, p). - Return(p, nil). - Times(1) - res, err := uc.PortfolioRepo.Update(context.TODO(), organizationID, ledgerID, id, p) +func TestUpdatePortfolioByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - assert.Equal(t, p, res) - assert.Nil(t, err) -} + mockPortfolioRepo := portfolio.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) -// TestUpdatePortfolioByIDError is responsible to test UpdatePortfolioByID with error -func TestUpdatePortfolioByIDError(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - p := &mmodel.Portfolio{ - ID: id.String(), - OrganizationID: pkg.GenerateUUIDv7().String(), - EntityID: pkg.GenerateUUIDv7().String(), - LedgerID: ledgerID.String(), - UpdatedAt: time.Now(), + uc := &UseCase{ + PortfolioRepo: mockPortfolioRepo, + MetadataRepo: mockMetadataRepo, } - uc := UseCase{ - PortfolioRepo: portfolio.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + portfolioID uuid.UUID + input *mmodel.UpdatePortfolioInput + mockSetup func() + expectErr bool + }{ + { + name: "Success - Portfolio updated with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: uuid.New(), + input: &mmodel.UpdatePortfolioInput{ + Name: "Updated Portfolio", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockPortfolioRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Portfolio{ID: "123", Name: "Updated Portfolio", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil) + }, + expectErr: false, + }, + { + name: "Error - Portfolio not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: uuid.New(), + input: &mmodel.UpdatePortfolioInput{ + Name: "Nonexistent Portfolio", + Status: mmodel.Status{Code: "inactive"}, + Metadata: nil, + }, + mockSetup: func() { + mockPortfolioRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + }, + { + name: "Error - Failed to update metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: uuid.New(), + input: &mmodel.UpdatePortfolioInput{ + Name: "Portfolio with Metadata Error", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockPortfolioRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Portfolio{ID: "123", Name: "Portfolio with Metadata Error", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(fmt.Errorf("metadata update error")) + }, + expectErr: true, + }, + { + name: "Error - Failure to update portfolio", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: uuid.New(), + input: &mmodel.UpdatePortfolioInput{ + Name: "Update Failure Portfolio", + Status: mmodel.Status{Code: "inactive"}, + Metadata: nil, + }, + mockSetup: func() { + mockPortfolioRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("update error")) + }, + expectErr: true, + }, } - uc.PortfolioRepo.(*portfolio.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, ledgerID, id, p). - Return(nil, errors.New(errMSG)) - res, err := uc.PortfolioRepo.Update(context.TODO(), organizationID, ledgerID, id, p) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) + ctx := context.Background() + result, err := uc.UpdatePortfolioByID(ctx, tt.organizationID, tt.ledgerID, tt.portfolioID, tt.input) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.input.Name, result.Name) + assert.Equal(t, tt.input.Status, result.Status) + } + }) + } } diff --git a/components/ledger/internal/services/command/update-product_test.go b/components/ledger/internal/services/command/update-product_test.go index 95b2ac4c..4fea7e14 100644 --- a/components/ledger/internal/services/command/update-product_test.go +++ b/components/ledger/internal/services/command/update-product_test.go @@ -2,69 +2,139 @@ package command import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" - "time" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestUpdateProductByIDSuccess is responsible to test UpdateProductByID with success -func TestUpdateProductByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - p := &mmodel.Product{ - ID: id.String(), - OrganizationID: organizationID.String(), - LedgerID: ledgerID.String(), - UpdatedAt: time.Now(), - } - - uc := UseCase{ - ProductRepo: product.NewMockRepository(gomock.NewController(t)), - } - - uc.ProductRepo.(*product.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, ledgerID, id, p). - Return(p, nil). - Times(1) - res, err := uc.ProductRepo.Update(context.TODO(), organizationID, ledgerID, id, p) +func TestUpdateProductByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - assert.Equal(t, p, res) - assert.Nil(t, err) -} + mockProductRepo := product.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) -// TestUpdateProductByIDError is responsible to test UpdateProductByID with error -func TestUpdateProductByIDError(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - p := &mmodel.Product{ - ID: id.String(), - OrganizationID: organizationID.String(), - LedgerID: ledgerID.String(), - UpdatedAt: time.Now(), + uc := &UseCase{ + ProductRepo: mockProductRepo, + MetadataRepo: mockMetadataRepo, } - uc := UseCase{ - ProductRepo: product.NewMockRepository(gomock.NewController(t)), + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + productID uuid.UUID + input *mmodel.UpdateProductInput + mockSetup func() + expectErr bool + }{ + { + name: "Success - Product updated with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + productID: uuid.New(), + input: &mmodel.UpdateProductInput{ + Name: "Updated Product", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockProductRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Product{ID: "123", Name: "Updated Product", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil) + }, + expectErr: false, + }, + { + name: "Error - Product not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + productID: uuid.New(), + input: &mmodel.UpdateProductInput{ + Name: "Nonexistent Product", + Status: mmodel.Status{Code: "inactive"}, + Metadata: nil, + }, + mockSetup: func() { + mockProductRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + }, + { + name: "Error - Failed to update metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + productID: uuid.New(), + input: &mmodel.UpdateProductInput{ + Name: "Product with Metadata Error", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + mockSetup: func() { + mockProductRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Product{ID: "123", Name: "Product with Metadata Error", Status: mmodel.Status{Code: "active"}, Metadata: nil}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"existing_key": "existing_value"}}, nil) + mockMetadataRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(fmt.Errorf("metadata update error")) + }, + expectErr: true, + }, + { + name: "Error - Failure to update product", + organizationID: uuid.New(), + ledgerID: uuid.New(), + productID: uuid.New(), + input: &mmodel.UpdateProductInput{ + Name: "Update Failure Product", + Status: mmodel.Status{Code: "inactive"}, + Metadata: nil, + }, + mockSetup: func() { + mockProductRepo.EXPECT(). + Update(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("update error")) + }, + expectErr: true, + }, } - uc.ProductRepo.(*product.MockRepository). - EXPECT(). - Update(gomock.Any(), organizationID, ledgerID, id, p). - Return(nil, errors.New(errMSG)) - res, err := uc.ProductRepo.Update(context.TODO(), organizationID, ledgerID, id, p) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) + ctx := context.Background() + result, err := uc.UpdateProductByID(ctx, tt.organizationID, tt.ledgerID, tt.productID, tt.input) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.input.Name, result.Name) + assert.Equal(t, tt.input.Status, result.Status) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-alias-accounts_test.go b/components/ledger/internal/services/query/get-alias-accounts_test.go new file mode 100644 index 00000000..dbe04334 --- /dev/null +++ b/components/ledger/internal/services/query/get-alias-accounts_test.go @@ -0,0 +1,99 @@ +package query + +import ( + "context" + "errors" + "testing" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/mpointers" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" +) + +func TestListAccountsByAlias(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockAccountRepo := account.NewMockRepository(ctrl) + + uc := &UseCase{ + AccountRepo: mockAccountRepo, + } + + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() + aliases := []string{"alias1", "alias2"} + + tests := []struct { + name string + setupMocks func() + expectedErr error + expectedAccounts []*mmodel.Account + }{ + { + name: "success - accounts retrieved", + setupMocks: func() { + mockAccountRepo.EXPECT(). + ListAccountsByAlias(gomock.Any(), organizationID, ledgerID, aliases). + Return([]*mmodel.Account{ + {ID: uuid.New().String(), Alias: mpointers.String("alias1")}, + {ID: uuid.New().String(), Alias: mpointers.String("alias2")}, + }, nil). + Times(1) + }, + expectedErr: nil, + expectedAccounts: []*mmodel.Account{ + {ID: uuid.New().String(), Alias: mpointers.String("alias1")}, + {ID: uuid.New().String(), Alias: mpointers.String("alias2")}, + }, + }, + { + name: "failure - accounts not found", + setupMocks: func() { + mockAccountRepo.EXPECT(). + ListAccountsByAlias(gomock.Any(), organizationID, ledgerID, aliases). + Return(nil, services.ErrDatabaseItemNotFound). + Times(1) + }, + expectedErr: errors.New("The accounts could not be retrieved using the specified aliases. Please verify the aliases for accuracy and try again."), + expectedAccounts: nil, + }, + { + name: "failure - repository error", + setupMocks: func() { + mockAccountRepo.EXPECT(). + ListAccountsByAlias(gomock.Any(), organizationID, ledgerID, aliases). + Return(nil, errors.New("failed to retrieve accounts")). + Times(1) + }, + expectedErr: errors.New("failed to retrieve accounts"), + expectedAccounts: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() + + result, err := uc.ListAccountsByAlias(ctx, organizationID, ledgerID, aliases) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, len(tt.expectedAccounts), len(result)) + for i, account := range result { + assert.Equal(t, tt.expectedAccounts[i].Alias, account.Alias) + } + } + }) + } +} diff --git a/components/ledger/internal/services/query/get-all-accounts_test.go b/components/ledger/internal/services/query/get-all-accounts_test.go index 6ba91dd9..e8efea09 100644 --- a/components/ledger/internal/services/query/get-all-accounts_test.go +++ b/components/ledger/internal/services/query/get-all-accounts_test.go @@ -3,99 +3,135 @@ package query import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/net/http" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAllAccounts is responsible to test GetAllAccounts with success and error -func TestGetAllAccounts(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - portfolioID := pkg.GenerateUUIDv7() - limit := 10 - page := 1 - - t.Parallel() +func TestGetAllAccount(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockAccountRepo := account.NewMockRepository(ctrl) - - uc := UseCase{ - AccountRepo: mockAccountRepo, - } - - t.Run("Success", func(t *testing.T) { - accounts := []*mmodel.Account{{}} - mockAccountRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, ledgerID, &portfolioID, limit, page). - Return(accounts, nil). - Times(1) - res, err := uc.AccountRepo.FindAll(context.TODO(), organizationID, ledgerID, &portfolioID, limit, page) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - t.Run("Error", func(t *testing.T) { - errMsg := "errDatabaseItemNotFound" - mockAccountRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, ledgerID, &portfolioID, limit, page). - Return(nil, errors.New(errMsg)). - Times(1) - res, err := uc.AccountRepo.FindAll(context.TODO(), organizationID, ledgerID, &portfolioID, limit, page) - - assert.EqualError(t, err, errMsg) - assert.Nil(t, res) - }) -} - -// TestGetAllAccountsWithoutPortfolio is responsible to test GetAllAccounts without portfolio with success and error -func TestGetAllAccountsWithoutPortfolio(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - limit := 10 - page := 1 - - t.Parallel() - ctrl := gomock.NewController(t) - defer ctrl.Finish() mockAccountRepo := account.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - AccountRepo: mockAccountRepo, + uc := &UseCase{ + AccountRepo: mockAccountRepo, + MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - accounts := []*mmodel.Account{{}} - mockAccountRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, ledgerID, nil, limit, page). - Return(accounts, nil). - Times(1) - res, err := uc.AccountRepo.FindAll(context.TODO(), organizationID, ledgerID, nil, limit, page) + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() + portfolioID := uuid.New() - assert.NoError(t, err) - assert.Len(t, res, 1) - }) + filter := http.QueryHeader{ + Limit: 10, + Page: 1, + } - t.Run("Error", func(t *testing.T) { - errMsg := "errDatabaseItemNotFound" - mockAccountRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, ledgerID, nil, limit, page). - Return(nil, errors.New(errMsg)). - Times(1) - res, err := uc.AccountRepo.FindAll(context.TODO(), organizationID, ledgerID, nil, limit, page) + tests := []struct { + name string + setupMocks func() + expectedErr error + expectedAccounts []*mmodel.Account + }{ + { + name: "success - accounts retrieved with metadata", + setupMocks: func() { + mockAccountRepo.EXPECT(). + FindAll(gomock.Any(), organizationID, ledgerID, &portfolioID, filter.Limit, filter.Page). + Return([]*mmodel.Account{ + {ID: "acc1"}, + {ID: "acc2"}, + }, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), "Account", filter). + Return([]*mongodb.Metadata{ + {EntityID: "acc1", Data: map[string]any{"key1": "value1"}}, + {EntityID: "acc2", Data: map[string]any{"key2": "value2"}}, + }, nil). + Times(1) + }, + expectedErr: nil, + expectedAccounts: []*mmodel.Account{ + {ID: "acc1", Metadata: map[string]any{"key1": "value1"}}, + {ID: "acc2", Metadata: map[string]any{"key2": "value2"}}, + }, + }, + { + name: "failure - accounts not found", + setupMocks: func() { + mockAccountRepo.EXPECT(). + FindAll(gomock.Any(), organizationID, ledgerID, &portfolioID, filter.Limit, filter.Page). + Return(nil, services.ErrDatabaseItemNotFound). + Times(1) + }, + expectedErr: errors.New("No accounts were found in the search. Please review the search criteria and try again."), + expectedAccounts: nil, + }, + { + name: "failure - error retrieving accounts", + setupMocks: func() { + mockAccountRepo.EXPECT(). + FindAll(gomock.Any(), organizationID, ledgerID, &portfolioID, filter.Limit, filter.Page). + Return(nil, errors.New("failed to retrieve accounts")). + Times(1) + }, + expectedErr: errors.New("failed to retrieve accounts"), + expectedAccounts: nil, + }, + { + name: "failure - metadata retrieval error", + setupMocks: func() { + mockAccountRepo.EXPECT(). + FindAll(gomock.Any(), organizationID, ledgerID, &portfolioID, filter.Limit, filter.Page). + Return([]*mmodel.Account{ + {ID: "acc1"}, + {ID: "acc2"}, + }, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), "Account", filter). + Return(nil, errors.New("failed to retrieve metadata")). + Times(1) + }, + expectedErr: errors.New("No accounts were found in the search. Please review the search criteria and try again."), + expectedAccounts: nil, + }, + } - assert.EqualError(t, err, errMsg) - assert.Nil(t, res) - }) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() + + result, err := uc.GetAllAccount(ctx, organizationID, ledgerID, &portfolioID, filter) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, len(tt.expectedAccounts), len(result)) + for i, account := range result { + assert.Equal(t, tt.expectedAccounts[i].ID, account.ID) + assert.Equal(t, tt.expectedAccounts[i].Metadata, account.Metadata) + } + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-asset_test.go b/components/ledger/internal/services/query/get-all-asset_test.go index 053eaa07..7f7e0442 100644 --- a/components/ledger/internal/services/query/get-all-asset_test.go +++ b/components/ledger/internal/services/query/get-all-asset_test.go @@ -3,55 +3,134 @@ package query import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/asset" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/net/http" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAllAssetsError is responsible to test GetAllAssets with success and error func TestGetAllAssets(t *testing.T) { - ledgerID := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - limit := 10 - page := 1 - - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() + mockAssetRepo := asset.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + AssetRepo: mockAssetRepo, + MetadataRepo: mockMetadataRepo, + } + + ctx := context.Background() + organizationID := uuid.New() + ledgerID := uuid.New() - uc := UseCase{ - AssetRepo: mockAssetRepo, + filter := http.QueryHeader{ + Limit: 10, + Page: 1, } - t.Run("Success", func(t *testing.T) { - assets := []*mmodel.Asset{{}} - mockAssetRepo. - EXPECT(). - FindAllWithDeleted(gomock.Any(), organizationID, ledgerID, page, limit). - Return(assets, nil). - Times(1) - res, err := uc.AssetRepo.FindAllWithDeleted(context.TODO(), organizationID, ledgerID, page, limit) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMsg := "errDatabaseItemNotFound" - mockAssetRepo. - EXPECT(). - FindAllWithDeleted(gomock.Any(), organizationID, ledgerID, page, limit). - Return(nil, errors.New(errMsg)). - Times(1) - res, err := uc.AssetRepo.FindAllWithDeleted(context.TODO(), organizationID, ledgerID, page, limit) - - assert.EqualError(t, err, errMsg) - assert.Nil(t, res) - }) + tests := []struct { + name string + setupMocks func() + expectedErr error + expectedAssets []*mmodel.Asset + }{ + { + name: "success - assets retrieved with metadata", + setupMocks: func() { + mockAssetRepo.EXPECT(). + FindAllWithDeleted(gomock.Any(), organizationID, ledgerID, filter.Limit, filter.Page). + Return([]*mmodel.Asset{ + {ID: "asset1"}, + {ID: "asset2"}, + }, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), "Asset", filter). + Return([]*mongodb.Metadata{ + {EntityID: "asset1", Data: map[string]any{"key1": "value1"}}, + {EntityID: "asset2", Data: map[string]any{"key2": "value2"}}, + }, nil). + Times(1) + }, + expectedErr: nil, + expectedAssets: []*mmodel.Asset{ + {ID: "asset1", Metadata: map[string]any{"key1": "value1"}}, + {ID: "asset2", Metadata: map[string]any{"key2": "value2"}}, + }, + }, + { + name: "failure - assets not found", + setupMocks: func() { + mockAssetRepo.EXPECT(). + FindAllWithDeleted(gomock.Any(), organizationID, ledgerID, filter.Limit, filter.Page). + Return(nil, services.ErrDatabaseItemNotFound). + Times(1) + }, + expectedErr: errors.New("No assets were found in the search. Please review the search criteria and try again."), + expectedAssets: nil, + }, + { + name: "failure - repository error retrieving assets", + setupMocks: func() { + mockAssetRepo.EXPECT(). + FindAllWithDeleted(gomock.Any(), organizationID, ledgerID, filter.Limit, filter.Page). + Return(nil, errors.New("failed to retrieve assets")). + Times(1) + }, + expectedErr: errors.New("failed to retrieve assets"), + expectedAssets: nil, + }, + { + name: "failure - metadata retrieval error", + setupMocks: func() { + mockAssetRepo.EXPECT(). + FindAllWithDeleted(gomock.Any(), organizationID, ledgerID, filter.Limit, filter.Page). + Return([]*mmodel.Asset{ + {ID: "asset1"}, + {ID: "asset2"}, + }, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), "Asset", filter). + Return(nil, errors.New("failed to retrieve metadata")). + Times(1) + }, + expectedErr: errors.New("No assets were found in the search. Please review the search criteria and try again."), + expectedAssets: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() + + result, err := uc.GetAllAssets(ctx, organizationID, ledgerID, filter) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, len(tt.expectedAssets), len(result)) + for i, asset := range result { + assert.Equal(t, tt.expectedAssets[i].ID, asset.ID) + assert.Equal(t, tt.expectedAssets[i].Metadata, asset.Metadata) + } + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-ledgers_test.go b/components/ledger/internal/services/query/get-all-ledgers_test.go index ae8e8479..351d1c60 100644 --- a/components/ledger/internal/services/query/get-all-ledgers_test.go +++ b/components/ledger/internal/services/query/get-all-ledgers_test.go @@ -3,53 +3,132 @@ package query import ( "context" "errors" - "go.uber.org/mock/gomock" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" - "github.com/LerianStudio/midaz/pkg" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/net/http" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAllLedgersError is responsible to test GetAllLedgers with success and error func TestGetAllLedgers(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() + mockLedgerRepo := ledger.NewMockRepository(ctrl) - organizationID := pkg.GenerateUUIDv7() - limit := 10 - page := 1 + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + LedgerRepo: mockLedgerRepo, + MetadataRepo: mockMetadataRepo, + } + + ctx := context.Background() + organizationID := uuid.New() - uc := UseCase{ - LedgerRepo: mockLedgerRepo, + filter := http.QueryHeader{ + Limit: 10, + Page: 1, } - t.Run("Success", func(t *testing.T) { - ledgers := []*mmodel.Ledger{{}} - mockLedgerRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, page, limit). - Return(ledgers, nil). - Times(1) - res, err := uc.LedgerRepo.FindAll(context.TODO(), organizationID, page, limit) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMsg := "errDatabaseItemNotFound" - mockLedgerRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, page, limit). - Return(nil, errors.New(errMsg)). - Times(1) - res, err := uc.LedgerRepo.FindAll(context.TODO(), organizationID, page, limit) - - assert.EqualError(t, err, errMsg) - assert.Nil(t, res) - }) + tests := []struct { + name string + setupMocks func() + expectedErr error + expectedLedgers []*mmodel.Ledger + }{ + { + name: "success - ledgers retrieved with metadata", + setupMocks: func() { + mockLedgerRepo.EXPECT(). + FindAll(gomock.Any(), organizationID, filter.Limit, filter.Page). + Return([]*mmodel.Ledger{ + {ID: "ledger1"}, + {ID: "ledger2"}, + }, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), "Ledger", filter). + Return([]*mongodb.Metadata{ + {EntityID: "ledger1", Data: map[string]any{"key1": "value1"}}, + {EntityID: "ledger2", Data: map[string]any{"key2": "value2"}}, + }, nil). + Times(1) + }, + expectedErr: nil, + expectedLedgers: []*mmodel.Ledger{ + {ID: "ledger1", Metadata: map[string]any{"key1": "value1"}}, + {ID: "ledger2", Metadata: map[string]any{"key2": "value2"}}, + }, + }, + { + name: "failure - ledgers not found", + setupMocks: func() { + mockLedgerRepo.EXPECT(). + FindAll(gomock.Any(), organizationID, filter.Limit, filter.Page). + Return(nil, errors.New("No ledgers were found in the search. Please review the search criteria and try again.")). + Times(1) + }, + expectedErr: errors.New("No ledgers were found in the search. Please review the search criteria and try again."), + expectedLedgers: nil, + }, + { + name: "failure - repository error retrieving ledgers", + setupMocks: func() { + mockLedgerRepo.EXPECT(). + FindAll(gomock.Any(), organizationID, filter.Limit, filter.Page). + Return(nil, errors.New("failed to retrieve ledgers")). + Times(1) + }, + expectedErr: errors.New("failed to retrieve ledgers"), + expectedLedgers: nil, + }, + { + name: "failure - metadata retrieval error", + setupMocks: func() { + mockLedgerRepo.EXPECT(). + FindAll(gomock.Any(), organizationID, filter.Limit, filter.Page). + Return([]*mmodel.Ledger{ + {ID: "ledger1"}, + {ID: "ledger2"}, + }, nil). + Times(1) + + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), "Ledger", filter). + Return(nil, errors.New("failed to retrieve metadata")). + Times(1) + }, + expectedErr: errors.New("No ledgers were found in the search. Please review the search criteria and try again."), + expectedLedgers: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setupMocks() + + result, err := uc.GetAllLedgers(ctx, organizationID, filter) + + if tt.expectedErr != nil { + assert.Error(t, err) + assert.Equal(t, tt.expectedErr.Error(), err.Error()) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, len(tt.expectedLedgers), len(result)) + for i, ledger := range result { + assert.Equal(t, tt.expectedLedgers[i].ID, ledger.ID) + assert.Equal(t, tt.expectedLedgers[i].Metadata, ledger.Metadata) + } + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-metadata-accounts_test.go b/components/ledger/internal/services/query/get-all-metadata-accounts_test.go index f8fe8918..458fc6d7 100644 --- a/components/ledger/internal/services/query/get-all-metadata-accounts_test.go +++ b/components/ledger/internal/services/query/get-all-metadata-accounts_test.go @@ -2,60 +2,78 @@ package query import ( "context" - "errors" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.uber.org/mock/gomock" - "reflect" "testing" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/net/http" - + "github.com/google/uuid" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) -// TestGetAllMetadataAccounts is responsible to test TestGetAllMetadataAccounts with success and error func TestGetAllMetadataAccounts(t *testing.T) { - collection := reflect.TypeOf(mmodel.Account{}).Name() - filter := http.QueryHeader{ - Metadata: &bson.M{"metadata": 1}, - Limit: 10, - Page: 1, - } - - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() - mockMetadataRepo := mongodb.NewMockRepository(gomock.NewController(t)) - uc := UseCase{ + mockAccountRepo := account.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + AccountRepo: mockAccountRepo, MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return([]*mongodb.Metadata{{ID: primitive.NewObjectID()}}, nil). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.EqualError(t, err, errMSG) - assert.Nil(t, res) - }) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + portfolioID *uuid.UUID + filter http.QueryHeader + mockSetup func() + expectErr bool + expectedResult []*mmodel.Account + }{ + { + name: "Success - Retrieve accounts with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockAccountRepo.EXPECT(). + ListByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return([]*mmodel.Account{ + {ID: validUUID.String(), Name: "Test Account", Status: mmodel.Status{Code: "active"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Account{ + {ID: "valid-uuid", Name: "Test Account", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAllMetadataAccounts(ctx, tt.organizationID, tt.ledgerID, tt.portfolioID, tt.filter) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-metadata-asset_test.go b/components/ledger/internal/services/query/get-all-metadata-asset_test.go index 10a91f53..4078d730 100644 --- a/components/ledger/internal/services/query/get-all-metadata-asset_test.go +++ b/components/ledger/internal/services/query/get-all-metadata-asset_test.go @@ -2,60 +2,95 @@ package query import ( "context" - "errors" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.uber.org/mock/gomock" - "reflect" + "fmt" "testing" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/asset" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/net/http" - + "github.com/google/uuid" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) -// TestGetAllMetadataAssets is responsible to test TestGetAllMetadataAssets with success and error func TestGetAllMetadataAssets(t *testing.T) { - collection := reflect.TypeOf(mmodel.Asset{}).Name() - filter := http.QueryHeader{ - Metadata: &bson.M{"metadata": 1}, - Limit: 10, - Page: 1, - } - - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() - mockMetadataRepo := mongodb.NewMockRepository(gomock.NewController(t)) - uc := UseCase{ + mockAssetRepo := asset.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + AssetRepo: mockAssetRepo, MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return([]*mongodb.Metadata{{ID: primitive.NewObjectID()}}, nil). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.EqualError(t, err, errMSG) - assert.Nil(t, res) - }) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + filter http.QueryHeader + mockSetup func() + expectErr bool + expectedResult []*mmodel.Asset + }{ + { + name: "Success - Retrieve assets with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockAssetRepo.EXPECT(). + ListByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return([]*mmodel.Asset{ + {ID: validUUID.String(), Name: "Test Asset", Status: mmodel.Status{Code: "active"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Asset{ + {ID: "valid-uuid", Name: "Test Asset", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + }, + }, + { + name: "Error - Failed to retrieve assets", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockAssetRepo.EXPECT(). + ListByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return(nil, fmt.Errorf("database error")) + }, + expectErr: true, + expectedResult: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAllMetadataAssets(ctx, tt.organizationID, tt.ledgerID, tt.filter) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-metadata-ledgers_test.go b/components/ledger/internal/services/query/get-all-metadata-ledgers_test.go index aad77647..a7aeb806 100644 --- a/components/ledger/internal/services/query/get-all-metadata-ledgers_test.go +++ b/components/ledger/internal/services/query/get-all-metadata-ledgers_test.go @@ -2,60 +2,92 @@ package query import ( "context" - "errors" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.uber.org/mock/gomock" - "reflect" + "fmt" "testing" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/net/http" - + "github.com/google/uuid" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) -// TestGetAllMetadataLedgers is responsible to test TestGetAllMetadataLedgers with success and error func TestGetAllMetadataLedgers(t *testing.T) { - collection := reflect.TypeOf(mmodel.Ledger{}).Name() - filter := http.QueryHeader{ - Metadata: &bson.M{"metadata": 1}, - Limit: 10, - Page: 1, - } - - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() - mockMetadataRepo := mongodb.NewMockRepository(gomock.NewController(t)) - uc := UseCase{ + mockLedgerRepo := ledger.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + LedgerRepo: mockLedgerRepo, MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return([]*mongodb.Metadata{{ID: primitive.NewObjectID()}}, nil). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.EqualError(t, err, errMSG) - assert.Nil(t, res) - }) + tests := []struct { + name string + organizationID uuid.UUID + filter http.QueryHeader + mockSetup func() + expectErr bool + expectedResult []*mmodel.Ledger + }{ + { + name: "Success - Retrieve ledgers with metadata", + organizationID: uuid.New(), + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockLedgerRepo.EXPECT(). + ListByIDs(gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return([]*mmodel.Ledger{ + {ID: validUUID.String(), Name: "Test Ledger", Status: mmodel.Status{Code: "active"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Ledger{ + {ID: "valid-uuid", Name: "Test Ledger", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + }, + }, + { + name: "Error - Failed to retrieve ledgers", + organizationID: uuid.New(), + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockLedgerRepo.EXPECT(). + ListByIDs(gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return(nil, fmt.Errorf("database error")) + }, + expectErr: true, + expectedResult: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAllMetadataLedgers(ctx, tt.organizationID, tt.filter) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-metadata-organizations_test.go b/components/ledger/internal/services/query/get-all-metadata-organizations_test.go index 7402cb59..45776891 100644 --- a/components/ledger/internal/services/query/get-all-metadata-organizations_test.go +++ b/components/ledger/internal/services/query/get-all-metadata-organizations_test.go @@ -2,60 +2,89 @@ package query import ( "context" - "errors" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.uber.org/mock/gomock" - "reflect" + "fmt" "testing" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/net/http" - + "github.com/google/uuid" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) -// TestGetAllMetadataOrganizations is responsible to test TestGetAllMetadataOrganizations with success and error func TestGetAllMetadataOrganizations(t *testing.T) { - collection := reflect.TypeOf(mmodel.Organization{}).Name() - filter := http.QueryHeader{ - Metadata: &bson.M{"metadata": 1}, - Limit: 10, - Page: 1, - } - - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() - mockMetadataRepo := mongodb.NewMockRepository(gomock.NewController(t)) - uc := UseCase{ - MetadataRepo: mockMetadataRepo, + mockOrganizationRepo := organization.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + OrganizationRepo: mockOrganizationRepo, + MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return([]*mongodb.Metadata{{ID: primitive.NewObjectID()}}, nil). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.EqualError(t, err, errMSG) - assert.Nil(t, res) - }) + tests := []struct { + name string + filter http.QueryHeader + mockSetup func() + expectErr bool + expectedResult []*mmodel.Organization + }{ + { + name: "Success - Retrieve organizations with metadata", + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockOrganizationRepo.EXPECT(). + ListByIDs(gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return([]*mmodel.Organization{ + {ID: validUUID.String(), LegalName: "Test Organization", Status: mmodel.Status{Code: "active"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Organization{ + {ID: "valid-uuid", LegalName: "Test Organization", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + }, + }, + { + name: "Error - Failed to retrieve organizations", + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockOrganizationRepo.EXPECT(). + ListByIDs(gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return(nil, fmt.Errorf("database error")) + }, + expectErr: true, + expectedResult: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAllMetadataOrganizations(ctx, tt.filter) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-metadata-portfolios_test.go b/components/ledger/internal/services/query/get-all-metadata-portfolios_test.go index c0018511..565d9349 100644 --- a/components/ledger/internal/services/query/get-all-metadata-portfolios_test.go +++ b/components/ledger/internal/services/query/get-all-metadata-portfolios_test.go @@ -3,59 +3,109 @@ package query import ( "context" "errors" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.uber.org/mock/gomock" - "reflect" + "fmt" "testing" + "go.uber.org/mock/gomock" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/net/http" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAllMetadataPortfolios is responsible to test TestGetAllMetadataPortfolios with success and error func TestGetAllMetadataPortfolios(t *testing.T) { - collection := reflect.TypeOf(mmodel.Portfolio{}).Name() - filter := http.QueryHeader{ - Metadata: &bson.M{"metadata": 1}, - Limit: 10, - Page: 1, - } - - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() - mockMetadataRepo := mongodb.NewMockRepository(gomock.NewController(t)) - uc := UseCase{ - MetadataRepo: mockMetadataRepo, + mockPortfolioRepo := portfolio.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + PortfolioRepo: mockPortfolioRepo, + MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return([]*mongodb.Metadata{{ID: primitive.NewObjectID()}}, nil). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.EqualError(t, err, errMSG) - assert.Nil(t, res) - }) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + filter http.QueryHeader + mockSetup func() + expectErr bool + expectedResult []*mmodel.Portfolio + }{ + { + name: "Success - Retrieve portfolios with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockPortfolioRepo.EXPECT(). + ListByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return([]*mmodel.Portfolio{ + {ID: validUUID.String(), Name: "Test Portfolio", Status: mmodel.Status{Code: "active"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Portfolio{ + {ID: "valid-uuid", Name: "Test Portfolio", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + }, + }, + { + name: "Error - No metadata found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, errors.New("error no metadata found")) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve portfolios", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockPortfolioRepo.EXPECT(). + ListByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return(nil, fmt.Errorf("database error")) + }, + expectErr: true, + expectedResult: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAllMetadataPortfolios(ctx, tt.organizationID, tt.ledgerID, tt.filter) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-metadata-products_test.go b/components/ledger/internal/services/query/get-all-metadata-products_test.go index ad0f7283..2a01707a 100644 --- a/components/ledger/internal/services/query/get-all-metadata-products_test.go +++ b/components/ledger/internal/services/query/get-all-metadata-products_test.go @@ -3,59 +3,109 @@ package query import ( "context" "errors" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.uber.org/mock/gomock" - "reflect" + "fmt" "testing" + "go.uber.org/mock/gomock" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" "github.com/LerianStudio/midaz/pkg/mmodel" "github.com/LerianStudio/midaz/pkg/net/http" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAllMetadataProducts is responsible to test TestGetAllMetadataProducts with success and error func TestGetAllMetadataProducts(t *testing.T) { - collection := reflect.TypeOf(mmodel.Product{}).Name() - filter := http.QueryHeader{ - Metadata: &bson.M{"metadata": 1}, - Limit: 10, - Page: 1, - } - - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() - mockMetadataRepo := mongodb.NewMockRepository(gomock.NewController(t)) - uc := UseCase{ + mockProductRepo := product.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) + + uc := &UseCase{ + ProductRepo: mockProductRepo, MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return([]*mongodb.Metadata{{ID: primitive.NewObjectID()}}, nil). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMSG := "errDatabaseItemNotFound" - mockMetadataRepo. - EXPECT(). - FindList(gomock.Any(), collection, filter). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.MetadataRepo.FindList(context.TODO(), collection, filter) - - assert.EqualError(t, err, errMSG) - assert.Nil(t, res) - }) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + filter http.QueryHeader + mockSetup func() + expectErr bool + expectedResult []*mmodel.Product + }{ + { + name: "Success - Retrieve products with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockProductRepo.EXPECT(). + FindByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return([]*mmodel.Product{ + {ID: validUUID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Product{ + {ID: "valid-uuid", Name: "Test Product", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + }, + }, + { + name: "Error - No metadata found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, errors.New("error metadata no found")) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve products", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + validUUID := uuid.New() + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + mockProductRepo.EXPECT(). + FindByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq([]uuid.UUID{validUUID})). + Return(nil, fmt.Errorf("database error")) + }, + expectErr: true, + expectedResult: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAllMetadataProducts(ctx, tt.organizationID, tt.ledgerID, tt.filter) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-organizations_test.go b/components/ledger/internal/services/query/get-all-organizations_test.go index bc24d30e..4882b8df 100644 --- a/components/ledger/internal/services/query/get-all-organizations_test.go +++ b/components/ledger/internal/services/query/get-all-organizations_test.go @@ -2,52 +2,114 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/net/http" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAllOrganizationsError is responsible to test GetAllOrganizations with success and error func TestGetAllOrganizations(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() + mockOrganizationRepo := organization.NewMockRepository(ctrl) - limit := 10 - page := 1 + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ + uc := &UseCase{ OrganizationRepo: mockOrganizationRepo, + MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - organizations := []*mmodel.Organization{{}} - mockOrganizationRepo. - EXPECT(). - FindAll(gomock.Any(), limit, page). - Return(organizations, nil). - Times(1) - res, err := uc.OrganizationRepo.FindAll(context.TODO(), limit, page) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMsg := "errDatabaseItemNotFound" - mockOrganizationRepo. - EXPECT(). - FindAll(gomock.Any(), limit, page). - Return(nil, errors.New(errMsg)). - Times(1) - res, err := uc.OrganizationRepo.FindAll(context.TODO(), limit, page) - - assert.EqualError(t, err, errMsg) - assert.Nil(t, res) - }) + tests := []struct { + name string + filter http.QueryHeader + mockSetup func() + expectErr bool + expectedResult []*mmodel.Organization + }{ + { + name: "Success - Retrieve organizations with metadata", + filter: http.QueryHeader{ + Limit: 10, + Page: 1, + }, + mockSetup: func() { + validUUID := uuid.New() + mockOrganizationRepo.EXPECT(). + FindAll(gomock.Any(), 10, 1). + Return([]*mmodel.Organization{ + {ID: validUUID.String(), LegalName: "Test Organization", Status: mmodel.Status{Code: "active"}}, + }, nil) + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Organization{ + {ID: "valid-uuid", LegalName: "Test Organization", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + }, + }, + { + name: "Error - No organizations found", + filter: http.QueryHeader{ + Limit: 10, + Page: 1, + }, + mockSetup: func() { + mockOrganizationRepo.EXPECT(). + FindAll(gomock.Any(), 10, 1). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + filter: http.QueryHeader{ + Limit: 10, + Page: 1, + }, + mockSetup: func() { + validUUID := uuid.New() + mockOrganizationRepo.EXPECT(). + FindAll(gomock.Any(), 10, 1). + Return([]*mmodel.Organization{ + {ID: validUUID.String(), LegalName: "Test Organization", Status: mmodel.Status{Code: "active"}}, + }, nil) + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAllOrganizations(ctx, tt.filter) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-portfolios_test.go b/components/ledger/internal/services/query/get-all-portfolios_test.go index 273c2c29..c3a75154 100644 --- a/components/ledger/internal/services/query/get-all-portfolios_test.go +++ b/components/ledger/internal/services/query/get-all-portfolios_test.go @@ -2,56 +2,113 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/net/http" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAllPortfoliosError is responsible to test GetAllPortfolios with success and error -func TestGetAllPortfolios(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - limit := 10 - page := 1 - - t.Parallel() +func TestGetAllPortfolio(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() + mockPortfolioRepo := portfolio.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ + uc := &UseCase{ PortfolioRepo: mockPortfolioRepo, + MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - portfolios := []*mmodel.Portfolio{{}} - mockPortfolioRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, ledgerID, limit, page). - Return(portfolios, nil). - Times(1) - res, err := uc.PortfolioRepo.FindAll(context.TODO(), organizationID, ledgerID, limit, page) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMsg := "errDatabaseItemNotFound" - mockPortfolioRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, ledgerID, limit, page). - Return(nil, errors.New(errMsg)). - Times(1) - res, err := uc.PortfolioRepo.FindAll(context.TODO(), organizationID, ledgerID, limit, page) - - assert.EqualError(t, err, errMsg) - assert.Nil(t, res) - }) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + filter http.QueryHeader + mockSetup func() + expectErr bool + expectedResult []*mmodel.Portfolio + }{ + { + name: "Success - Retrieve portfolios with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + filter: http.QueryHeader{Limit: 10, Page: 1}, + mockSetup: func() { + validUUID := uuid.New() + mockPortfolioRepo.EXPECT(). + FindAll(gomock.Any(), gomock.Any(), gomock.Any(), 10, 1). + Return([]*mmodel.Portfolio{ + {ID: validUUID.String(), Name: "Test Portfolio", Status: mmodel.Status{Code: "active"}}, + }, nil) + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Portfolio{ + {ID: "valid-uuid", Name: "Test Portfolio", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + }, + }, + { + name: "Error - No portfolios found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + filter: http.QueryHeader{Limit: 10, Page: 1}, + mockSetup: func() { + mockPortfolioRepo.EXPECT(). + FindAll(gomock.Any(), gomock.Any(), gomock.Any(), 10, 1). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + filter: http.QueryHeader{Limit: 10, Page: 1}, + mockSetup: func() { + validUUID := uuid.New() + mockPortfolioRepo.EXPECT(). + FindAll(gomock.Any(), gomock.Any(), gomock.Any(), 10, 1). + Return([]*mmodel.Portfolio{ + {ID: validUUID.String(), Name: "Test Portfolio", Status: mmodel.Status{Code: "active"}}, + }, nil) + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAllPortfolio(ctx, tt.organizationID, tt.ledgerID, tt.filter) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-all-products_test.go b/components/ledger/internal/services/query/get-all-products_test.go index 6a6628a9..e7081d62 100644 --- a/components/ledger/internal/services/query/get-all-products_test.go +++ b/components/ledger/internal/services/query/get-all-products_test.go @@ -2,56 +2,113 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/LerianStudio/midaz/pkg/net/http" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAllProductsError is responsible to test GetAllProducts with success and error func TestGetAllProducts(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - limit := 10 - page := 1 - - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() + mockProductRepo := product.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - ProductRepo: mockProductRepo, + uc := &UseCase{ + ProductRepo: mockProductRepo, + MetadataRepo: mockMetadataRepo, } - t.Run("Success", func(t *testing.T) { - products := []*mmodel.Product{{}} - mockProductRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, ledgerID, limit, page). - Return(products, nil). - Times(1) - res, err := uc.ProductRepo.FindAll(context.TODO(), organizationID, ledgerID, limit, page) - - assert.NoError(t, err) - assert.Len(t, res, 1) - }) - - t.Run("Error", func(t *testing.T) { - errMsg := "errDatabaseItemNotFound" - mockProductRepo. - EXPECT(). - FindAll(gomock.Any(), organizationID, ledgerID, limit, page). - Return(nil, errors.New(errMsg)). - Times(1) - res, err := uc.ProductRepo.FindAll(context.TODO(), organizationID, ledgerID, limit, page) - - assert.EqualError(t, err, errMsg) - assert.Nil(t, res) - }) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + filter http.QueryHeader + mockSetup func() + expectErr bool + expectedResult []*mmodel.Product + }{ + { + name: "Success - Retrieve products with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + filter: http.QueryHeader{Limit: 10, Page: 1}, + mockSetup: func() { + validUUID := uuid.New() + mockProductRepo.EXPECT(). + FindAll(gomock.Any(), gomock.Any(), gomock.Any(), 10, 1). + Return([]*mmodel.Product{ + {ID: validUUID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, + }, nil) + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mongodb.Metadata{ + {EntityID: validUUID.String(), Data: map[string]any{"key": "value"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Product{ + {ID: "valid-uuid", Name: "Test Product", Status: mmodel.Status{Code: "active"}, Metadata: map[string]any{"key": "value"}}, + }, + }, + { + name: "Error - No products found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + filter: http.QueryHeader{Limit: 10, Page: 1}, + mockSetup: func() { + mockProductRepo.EXPECT(). + FindAll(gomock.Any(), gomock.Any(), gomock.Any(), 10, 1). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + filter: http.QueryHeader{Limit: 10, Page: 1}, + mockSetup: func() { + validUUID := uuid.New() + mockProductRepo.EXPECT(). + FindAll(gomock.Any(), gomock.Any(), gomock.Any(), 10, 1). + Return([]*mmodel.Product{ + {ID: validUUID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, + }, nil) + mockMetadataRepo.EXPECT(). + FindList(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAllProducts(ctx, tt.organizationID, tt.ledgerID, tt.filter) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) + } } diff --git a/components/ledger/internal/services/query/get-id-account-with-deleted_test.go b/components/ledger/internal/services/query/get-id-account-with-deleted_test.go index 35320225..02e847db 100644 --- a/components/ledger/internal/services/query/get-id-account-with-deleted_test.go +++ b/components/ledger/internal/services/query/get-id-account-with-deleted_test.go @@ -2,99 +2,113 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" - "time" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" - "github.com/LerianStudio/midaz/pkg/mpointers" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAccountByIDWithDeletedSuccess is responsible to test GetAccountByIDWithDeleted with success -func TestGetAccountByIDWithDeletedSuccess(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - portfolioID := pkg.GenerateUUIDv7() - id := pkg.GenerateUUIDv7() +func TestGetAccountByIDWithDeleted(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - a := &mmodel.Account{ - ID: id.String(), - OrganizationID: organizationID.String(), - LedgerID: ledgerID.String(), - PortfolioID: mpointers.String(portfolioID.String()), - DeletedAt: mpointers.Time(time.Now()), - } + mockAccountRepo := account.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + AccountRepo: mockAccountRepo, + MetadataRepo: mockMetadataRepo, } - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, &portfolioID, id). - Return(a, nil). - Times(1) - res, err := uc.AccountRepo.Find(context.TODO(), organizationID, ledgerID, &portfolioID, id) - - assert.Equal(t, res, a) - assert.Nil(t, err) -} - -// TestGetAccountByIDWithDeletedWithoutPortfolioSuccess is responsible to test GetAccountByIDWithDeleted without portfolio with success -func TestGetAccountByIDWithDeletedWithoutPortfolioSuccess(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - id := pkg.GenerateUUIDv7() - - a := &mmodel.Account{ - ID: id.String(), - OrganizationID: organizationID.String(), - LedgerID: ledgerID.String(), - PortfolioID: nil, - DeletedAt: mpointers.Time(time.Now()), + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + portfolioID *uuid.UUID + accountID uuid.UUID + mockSetup func() + expectErr bool + expectedResult *mmodel.Account + }{ + { + name: "Success - Retrieve account with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + accountID: uuid.New(), + mockSetup: func() { + accountID := uuid.New() + mockAccountRepo.EXPECT(). + FindWithDeleted(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ID: accountID.String(), Name: "Test Account", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"key": "value"}}, nil) + }, + expectErr: false, + expectedResult: &mmodel.Account{ + ID: "valid-uuid", + Name: "Test Account", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + }, + { + name: "Error - Account not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + accountID: uuid.New(), + mockSetup: func() { + mockAccountRepo.EXPECT(). + FindWithDeleted(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + accountID: uuid.New(), + mockSetup: func() { + accountID := uuid.New() + mockAccountRepo.EXPECT(). + FindWithDeleted(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ID: accountID.String(), Name: "Test Account", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, } - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAccountByIDWithDeleted(ctx, tt.organizationID, tt.ledgerID, tt.portfolioID, tt.accountID) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) } - - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, nil, id). - Return(a, nil). - Times(1) - res, err := uc.AccountRepo.Find(context.TODO(), organizationID, ledgerID, nil, id) - - assert.Equal(t, res, a) - assert.Nil(t, err) -} - -// TestGetAccountByIDWithDeletedError is responsible to test GetAccountByIDWithDeleted with error -func TestGetAccountByIDWithDeletedError(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - portfolioID := pkg.GenerateUUIDv7() - id := pkg.GenerateUUIDv7() - - errMSG := "errDatabaseItemNotFound" - - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), - } - - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, &portfolioID, id). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.AccountRepo.Find(context.TODO(), organizationID, ledgerID, &portfolioID, id) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/query/get-id-account_test.go b/components/ledger/internal/services/query/get-id-account_test.go index d777227b..ba593a69 100644 --- a/components/ledger/internal/services/query/get-id-account_test.go +++ b/components/ledger/internal/services/query/get-id-account_test.go @@ -2,96 +2,113 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" - "github.com/LerianStudio/midaz/pkg/mpointers" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAccountByIDSuccess is responsible to test GetAccountByID with success -func TestGetAccountByIDSuccess(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - portfolioID := pkg.GenerateUUIDv7() - id := pkg.GenerateUUIDv7() +func TestGetAccountByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - a := &mmodel.Account{ - ID: id.String(), - OrganizationID: organizationID.String(), - LedgerID: ledgerID.String(), - PortfolioID: mpointers.String(portfolioID.String()), - } + mockAccountRepo := account.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + AccountRepo: mockAccountRepo, + MetadataRepo: mockMetadataRepo, } - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, &portfolioID, id). - Return(a, nil). - Times(1) - res, err := uc.AccountRepo.Find(context.TODO(), organizationID, ledgerID, &portfolioID, id) - - assert.Equal(t, res, a) - assert.Nil(t, err) -} - -// TestGetAccountByIDWithoutPortfolioSuccess is responsible to test GetAccountByID without portfolio with success -func TestGetAccountByIDWithoutPortfolioSuccess(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - id := pkg.GenerateUUIDv7() - - a := &mmodel.Account{ - ID: id.String(), - OrganizationID: organizationID.String(), - LedgerID: ledgerID.String(), - PortfolioID: nil, + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + portfolioID *uuid.UUID + accountID uuid.UUID + mockSetup func() + expectErr bool + expectedResult *mmodel.Account + }{ + { + name: "Success - Retrieve account with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + accountID: uuid.New(), + mockSetup: func() { + accountID := uuid.New() + mockAccountRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ID: accountID.String(), Name: "Test Account", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"key": "value"}}, nil) + }, + expectErr: false, + expectedResult: &mmodel.Account{ + ID: "valid-uuid", + Name: "Test Account", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + }, + { + name: "Error - Account not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + accountID: uuid.New(), + mockSetup: func() { + mockAccountRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: nil, + accountID: uuid.New(), + mockSetup: func() { + accountID := uuid.New() + mockAccountRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Account{ID: accountID.String(), Name: "Test Account", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, } - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.GetAccountByID(ctx, tt.organizationID, tt.ledgerID, tt.portfolioID, tt.accountID) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) } - - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, nil, id). - Return(a, nil). - Times(1) - res, err := uc.AccountRepo.Find(context.TODO(), organizationID, ledgerID, nil, id) - - assert.Equal(t, res, a) - assert.Nil(t, err) -} - -// TestGetAccountByIDError is responsible to test GetAccountByID with error -func TestGetAccountByIDError(t *testing.T) { - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - portfolioID := pkg.GenerateUUIDv7() - id := pkg.GenerateUUIDv7() - - errMSG := "errDatabaseItemNotFound" - - uc := UseCase{ - AccountRepo: account.NewMockRepository(gomock.NewController(t)), - } - - uc.AccountRepo.(*account.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, &portfolioID, id). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.AccountRepo.Find(context.TODO(), organizationID, ledgerID, &portfolioID, id) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/query/get-id-asset_test.go b/components/ledger/internal/services/query/get-id-asset_test.go index c5427fb7..21ee5da2 100644 --- a/components/ledger/internal/services/query/get-id-asset_test.go +++ b/components/ledger/internal/services/query/get-id-asset_test.go @@ -2,62 +2,109 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/asset" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetAssetByIDSuccess is responsible to test GetAssetByID with success -func TestGetAssetByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - a := &mmodel.Asset{ - ID: id.String(), - LedgerID: ledgerID.String(), - OrganizationID: organizationID.String(), - } +func TestGetAssetByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockAssetRepo := asset.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - AssetRepo: asset.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + AssetRepo: mockAssetRepo, + MetadataRepo: mockMetadataRepo, } - uc.AssetRepo.(*asset.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, id). - Return(a, nil). - Times(1) - res, err := uc.AssetRepo.Find(context.TODO(), organizationID, ledgerID, id) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + assetID uuid.UUID + mockSetup func() + expectErr bool + expectedResult *mmodel.Asset + }{ + { + name: "Success - Retrieve asset with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + mockSetup: func() { + assetID := uuid.New() + mockAssetRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Asset{ID: assetID.String(), Name: "Test Asset", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"key": "value"}}, nil) + }, + expectErr: false, + expectedResult: &mmodel.Asset{ + ID: "valid-uuid", + Name: "Test Asset", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + }, + { + name: "Error - Asset not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + mockSetup: func() { + mockAssetRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + assetID: uuid.New(), + mockSetup: func() { + assetID := uuid.New() + mockAssetRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Asset{ID: assetID.String(), Name: "Test Asset", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, + } - assert.Equal(t, res, a) - assert.Nil(t, err) -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() -// TestGetAssetByIDError is responsible to test GetAssetByID with error -func TestGetAssetByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" + ctx := context.Background() + result, err := uc.GetAssetByID(ctx, tt.organizationID, tt.ledgerID, tt.assetID) - uc := UseCase{ - AssetRepo: asset.NewMockRepository(gomock.NewController(t)), + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) } - - uc.AssetRepo.(*asset.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, id). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.AssetRepo.Find(context.TODO(), organizationID, ledgerID, id) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/query/get-id-ledger_test.go b/components/ledger/internal/services/query/get-id-ledger_test.go index d06eacef..47890820 100644 --- a/components/ledger/internal/services/query/get-id-ledger_test.go +++ b/components/ledger/internal/services/query/get-id-ledger_test.go @@ -2,56 +2,105 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/ledger" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetLedgerByIDSuccess is responsible to test GetLedgerByID with success -func TestGetLedgerByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - l := &mmodel.Ledger{ID: id.String()} +func TestGetLedgerByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockLedgerRepo := ledger.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - LedgerRepo: ledger.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + LedgerRepo: mockLedgerRepo, + MetadataRepo: mockMetadataRepo, } - uc.LedgerRepo.(*ledger.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, id). - Return(l, nil). - Times(1) - res, err := uc.LedgerRepo.Find(context.TODO(), organizationID, id) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + mockSetup func() + expectErr bool + expectedResult *mmodel.Ledger + }{ + { + name: "Success - Retrieve ledger with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + ledgerID := uuid.New() + mockLedgerRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Ledger{ID: ledgerID.String(), Name: "Test Ledger", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"key": "value"}}, nil) + }, + expectErr: false, + expectedResult: &mmodel.Ledger{ + ID: "valid-uuid", + Name: "Test Ledger", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + }, + { + name: "Error - Ledger not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + mockLedgerRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + mockSetup: func() { + ledgerID := uuid.New() + mockLedgerRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Ledger{ID: ledgerID.String(), Name: "Test Ledger", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, + } - assert.Equal(t, res, l) - assert.Nil(t, err) -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() -// TestGetLedgerByIDError is responsible to test GetLedgerByID with error -func TestGetLedgerByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" + ctx := context.Background() + result, err := uc.GetLedgerByID(ctx, tt.organizationID, tt.ledgerID) - uc := UseCase{ - LedgerRepo: ledger.NewMockRepository(gomock.NewController(t)), + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) } - - uc.LedgerRepo.(*ledger.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, id). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.LedgerRepo.Find(context.TODO(), organizationID, id) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/query/get-id-metadata_test.go b/components/ledger/internal/services/query/get-id-metadata_test.go deleted file mode 100644 index 5d6ef6a2..00000000 --- a/components/ledger/internal/services/query/get-id-metadata_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package query - -import ( - "context" - "errors" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.uber.org/mock/gomock" - "reflect" - "testing" - - "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" - "github.com/LerianStudio/midaz/pkg" - "github.com/LerianStudio/midaz/pkg/mmodel" - - "github.com/stretchr/testify/assert" -) - -// TestMetadataFindByEntitySuccess is responsible to test MetadataFindByEntity with success -func TestMetadataFindByEntitySuccess(t *testing.T) { - id := pkg.GenerateUUIDv7().String() - collection := reflect.TypeOf(mmodel.Organization{}).Name() - metadata := &mongodb.Metadata{ID: primitive.NewObjectID()} - uc := UseCase{ - MetadataRepo: mongodb.NewMockRepository(gomock.NewController(t)), - } - - uc.MetadataRepo.(*mongodb.MockRepository). - EXPECT(). - FindByEntity(gomock.Any(), collection, id). - Return(metadata, nil). - Times(1) - - res, err := uc.MetadataRepo.FindByEntity(context.TODO(), collection, id) - - assert.Equal(t, res, metadata) - assert.Nil(t, err) -} - -// TestMetadataFindByEntityError is responsible to test MetadataFindByEntity with error -func TestMetadataFindByEntityError(t *testing.T) { - errMSG := "err to findByEntity metadata on mongodb" - id := pkg.GenerateUUIDv7().String() - collection := reflect.TypeOf(mmodel.Organization{}).Name() - uc := UseCase{ - MetadataRepo: mongodb.NewMockRepository(gomock.NewController(t)), - } - - uc.MetadataRepo.(*mongodb.MockRepository). - EXPECT(). - FindByEntity(gomock.Any(), collection, id). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.MetadataRepo.FindByEntity(context.TODO(), collection, id) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) -} diff --git a/components/ledger/internal/services/query/get-id-organization_test.go b/components/ledger/internal/services/query/get-id-organization_test.go index 802bacb2..a764d831 100644 --- a/components/ledger/internal/services/query/get-id-organization_test.go +++ b/components/ledger/internal/services/query/get-id-organization_test.go @@ -2,54 +2,101 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/organization" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetOrganizationByIDSuccess is responsible to test GetOrganizationByID with success -func TestGetOrganizationByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - o := &mmodel.Organization{ID: id.String()} +func TestGetOrganizationByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockOrganizationRepo := organization.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - OrganizationRepo: organization.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + OrganizationRepo: mockOrganizationRepo, + MetadataRepo: mockMetadataRepo, } - uc.OrganizationRepo.(*organization.MockRepository). - EXPECT(). - Find(gomock.Any(), id). - Return(o, nil). - Times(1) - res, err := uc.OrganizationRepo.Find(context.TODO(), id) + tests := []struct { + name string + organizationID uuid.UUID + mockSetup func() + expectErr bool + expectedResult *mmodel.Organization + }{ + { + name: "Success - Retrieve organization with metadata", + organizationID: uuid.New(), + mockSetup: func() { + orgID := uuid.New() + mockOrganizationRepo.EXPECT(). + Find(gomock.Any(), gomock.Any()). + Return(&mmodel.Organization{ID: orgID.String(), LegalName: "Test Organization", Status: mmodel.Status{Code: "ACTIVE"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"key": "value"}}, nil) + }, + expectErr: false, + expectedResult: &mmodel.Organization{ + ID: "valid-uuid", + LegalName: "Test Organization", + Status: mmodel.Status{Code: "ACTIVE"}, + Metadata: map[string]any{"key": "value"}, + }, + }, + { + name: "Error - Organization not found", + organizationID: uuid.New(), + mockSetup: func() { + mockOrganizationRepo.EXPECT(). + Find(gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + organizationID: uuid.New(), + mockSetup: func() { + orgID := uuid.New() + mockOrganizationRepo.EXPECT(). + Find(gomock.Any(), gomock.Any()). + Return(&mmodel.Organization{ID: orgID.String(), LegalName: "Test Organization", Status: mmodel.Status{Code: "ACTIVE"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, + } - assert.Equal(t, res, o) - assert.Nil(t, err) -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() -// TestGetOrganizationByIDError is responsible to test GetOrganizationByID with error -func TestGetOrganizationByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" + ctx := context.Background() + result, err := uc.GetOrganizationByID(ctx, tt.organizationID) - uc := UseCase{ - OrganizationRepo: organization.NewMockRepository(gomock.NewController(t)), + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) } - - uc.OrganizationRepo.(*organization.MockRepository). - EXPECT(). - Find(gomock.Any(), id). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.OrganizationRepo.Find(context.TODO(), id) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/query/get-id-portfolio_test.go b/components/ledger/internal/services/query/get-id-portfolio_test.go index 52515726..109a6ec8 100644 --- a/components/ledger/internal/services/query/get-id-portfolio_test.go +++ b/components/ledger/internal/services/query/get-id-portfolio_test.go @@ -2,62 +2,109 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/portfolio" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetPortfolioByIDSuccess is responsible to test GetPortfolioByID with success -func TestGetPortfolioByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - p := &mmodel.Portfolio{ - ID: id.String(), - LedgerID: ledgerID.String(), - OrganizationID: organizationID.String(), - } +func TestGetPortfolioByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockPortfolioRepo := portfolio.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - PortfolioRepo: portfolio.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + PortfolioRepo: mockPortfolioRepo, + MetadataRepo: mockMetadataRepo, } - uc.PortfolioRepo.(*portfolio.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, id). - Return(p, nil). - Times(1) - res, err := uc.PortfolioRepo.Find(context.TODO(), organizationID, ledgerID, id) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + portfolioID uuid.UUID + mockSetup func() + expectErr bool + expectedResult *mmodel.Portfolio + }{ + { + name: "Success - Retrieve portfolio with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: uuid.New(), + mockSetup: func() { + portfolioID := uuid.New() + mockPortfolioRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Portfolio{ID: portfolioID.String(), Name: "Test Portfolio", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"key": "value"}}, nil) + }, + expectErr: false, + expectedResult: &mmodel.Portfolio{ + ID: "valid-uuid", + Name: "Test Portfolio", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + }, + { + name: "Error - Portfolio not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: uuid.New(), + mockSetup: func() { + mockPortfolioRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + portfolioID: uuid.New(), + mockSetup: func() { + portfolioID := uuid.New() + mockPortfolioRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Portfolio{ID: portfolioID.String(), Name: "Test Portfolio", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, + } - assert.Equal(t, res, p) - assert.Nil(t, err) -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() -// TestGetPortfolioByIDError is responsible to test GetPortfolioByID with error -func TestGetPortfolioByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" + ctx := context.Background() + result, err := uc.GetPortfolioByID(ctx, tt.organizationID, tt.ledgerID, tt.portfolioID) - uc := UseCase{ - PortfolioRepo: portfolio.NewMockRepository(gomock.NewController(t)), + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) } - - uc.PortfolioRepo.(*portfolio.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, id). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.PortfolioRepo.Find(context.TODO(), organizationID, ledgerID, id) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/query/get-id-product_test.go b/components/ledger/internal/services/query/get-id-product_test.go index fc2c5d15..9d2685b9 100644 --- a/components/ledger/internal/services/query/get-id-product_test.go +++ b/components/ledger/internal/services/query/get-id-product_test.go @@ -2,62 +2,109 @@ package query import ( "context" - "errors" - "go.uber.org/mock/gomock" + "fmt" "testing" + "go.uber.org/mock/gomock" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/mongodb" "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/product" - "github.com/LerianStudio/midaz/pkg" + "github.com/LerianStudio/midaz/components/ledger/internal/services" "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" "github.com/stretchr/testify/assert" ) -// TestGetProductByIDSuccess is responsible to test GetProductByID with success -func TestGetProductByIDSuccess(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - p := &mmodel.Product{ - ID: id.String(), - LedgerID: ledgerID.String(), - OrganizationID: organizationID.String(), - } +func TestGetProductByID(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockProductRepo := product.NewMockRepository(ctrl) + mockMetadataRepo := mongodb.NewMockRepository(ctrl) - uc := UseCase{ - ProductRepo: product.NewMockRepository(gomock.NewController(t)), + uc := &UseCase{ + ProductRepo: mockProductRepo, + MetadataRepo: mockMetadataRepo, } - uc.ProductRepo.(*product.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, id). - Return(p, nil). - Times(1) - res, err := uc.ProductRepo.Find(context.TODO(), organizationID, ledgerID, id) + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + productID uuid.UUID + mockSetup func() + expectErr bool + expectedResult *mmodel.Product + }{ + { + name: "Success - Retrieve product with metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + productID: uuid.New(), + mockSetup: func() { + productID := uuid.New() + mockProductRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Product{ID: productID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mongodb.Metadata{Data: map[string]any{"key": "value"}}, nil) + }, + expectErr: false, + expectedResult: &mmodel.Product{ + ID: "valid-uuid", + Name: "Test Product", + Status: mmodel.Status{Code: "active"}, + Metadata: map[string]any{"key": "value"}, + }, + }, + { + name: "Error - Product not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + productID: uuid.New(), + mockSetup: func() { + mockProductRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Failed to retrieve metadata", + organizationID: uuid.New(), + ledgerID: uuid.New(), + productID: uuid.New(), + mockSetup: func() { + productID := uuid.New() + mockProductRepo.EXPECT(). + Find(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&mmodel.Product{ID: productID.String(), Name: "Test Product", Status: mmodel.Status{Code: "active"}}, nil) + mockMetadataRepo.EXPECT(). + FindByEntity(gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("metadata retrieval error")) + }, + expectErr: true, + expectedResult: nil, + }, + } - assert.Equal(t, res, p) - assert.Nil(t, err) -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() -// TestGetProductByIDError is responsible to test GetProductByID with error -func TestGetProductByIDError(t *testing.T) { - id := pkg.GenerateUUIDv7() - organizationID := pkg.GenerateUUIDv7() - ledgerID := pkg.GenerateUUIDv7() - errMSG := "errDatabaseItemNotFound" + ctx := context.Background() + result, err := uc.GetProductByID(ctx, tt.organizationID, tt.ledgerID, tt.productID) - uc := UseCase{ - ProductRepo: product.NewMockRepository(gomock.NewController(t)), + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + } + }) } - - uc.ProductRepo.(*product.MockRepository). - EXPECT(). - Find(gomock.Any(), organizationID, ledgerID, id). - Return(nil, errors.New(errMSG)). - Times(1) - res, err := uc.ProductRepo.Find(context.TODO(), organizationID, ledgerID, id) - - assert.NotEmpty(t, err) - assert.Equal(t, err.Error(), errMSG) - assert.Nil(t, res) } diff --git a/components/ledger/internal/services/query/get-ids-accounts_test.go b/components/ledger/internal/services/query/get-ids-accounts_test.go new file mode 100644 index 00000000..a014556a --- /dev/null +++ b/components/ledger/internal/services/query/get-ids-accounts_test.go @@ -0,0 +1,99 @@ +package query + +import ( + "context" + "fmt" + "testing" + + "github.com/LerianStudio/midaz/components/ledger/internal/adapters/postgres/account" + "github.com/LerianStudio/midaz/components/ledger/internal/services" + "github.com/LerianStudio/midaz/pkg/mmodel" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" +) + +func TestListAccountsByIDs(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockAccountRepo := account.NewMockRepository(ctrl) + + uc := &UseCase{ + AccountRepo: mockAccountRepo, + } + + tests := []struct { + name string + organizationID uuid.UUID + ledgerID uuid.UUID + accountIDs []uuid.UUID + mockSetup func() + expectErr bool + expectedResult []*mmodel.Account + }{ + { + name: "Success - Retrieve accounts by IDs", + organizationID: uuid.New(), + ledgerID: uuid.New(), + accountIDs: []uuid.UUID{uuid.New(), uuid.New()}, + mockSetup: func() { + mockAccountRepo.EXPECT(). + ListAccountsByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*mmodel.Account{ + {ID: "account-1", Name: "Account 1", Status: mmodel.Status{Code: "active"}}, + {ID: "account-2", Name: "Account 2", Status: mmodel.Status{Code: "inactive"}}, + }, nil) + }, + expectErr: false, + expectedResult: []*mmodel.Account{ + {ID: "account-1", Name: "Account 1", Status: mmodel.Status{Code: "active"}}, + {ID: "account-2", Name: "Account 2", Status: mmodel.Status{Code: "inactive"}}, + }, + }, + { + name: "Error - Accounts not found", + organizationID: uuid.New(), + ledgerID: uuid.New(), + accountIDs: []uuid.UUID{uuid.New(), uuid.New()}, + mockSetup: func() { + mockAccountRepo.EXPECT(). + ListAccountsByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, services.ErrDatabaseItemNotFound) + }, + expectErr: true, + expectedResult: nil, + }, + { + name: "Error - Database error", + organizationID: uuid.New(), + ledgerID: uuid.New(), + accountIDs: []uuid.UUID{uuid.New(), uuid.New()}, + mockSetup: func() { + mockAccountRepo.EXPECT(). + ListAccountsByIDs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("database error")) + }, + expectErr: true, + expectedResult: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.mockSetup() + + ctx := context.Background() + result, err := uc.ListAccountsByIDs(ctx, tt.organizationID, tt.ledgerID, tt.accountIDs) + + if tt.expectErr { + assert.Error(t, err) + assert.Nil(t, result) + } else { + assert.NoError(t, err) + assert.NotNil(t, result) + assert.Equal(t, tt.expectedResult, result) + } + }) + } +} diff --git a/scripts/coverage.sh b/scripts/coverage.sh new file mode 100644 index 00000000..3f038a79 --- /dev/null +++ b/scripts/coverage.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +IGNORED=$(cat ./scripts/coverage_ignore.txt | xargs -I{} echo '-not -path ./{}/*' | xargs) +PACKAGES=$(go list ./pkg/... | grep -v -f ./scripts/coverage_ignore.txt) + +go test -cover $PACKAGES -coverprofile=coverage.out diff --git a/scripts/coverage_ignore.txt b/scripts/coverage_ignore.txt new file mode 100644 index 00000000..3ce6b6b5 --- /dev/null +++ b/scripts/coverage_ignore.txt @@ -0,0 +1,12 @@ +github.com/LerianStudio/midaz/pkg/constant +github.com/LerianStudio/midaz/pkg/gold +github.com/LerianStudio/midaz/pkg/mredis +github.com/LerianStudio/midaz/pkg/mmongo +github.com/LerianStudio/midaz/pkg/mmongo +github.com/LerianStudio/midaz/pkg/mgrpc/account +github.com/LerianStudio/midaz/pkg/mopentelemetry +github.com/LerianStudio/midaz/pkg/mpostgres +github.com/LerianStudio/midaz/pkg/mrabbitmq +github.com/LerianStudio/midaz/pkg/mredis +github.com/LerianStudio/midaz/pkg/net/http +github.com/LerianStudio/midaz/pkg/mlog