From 5ff06e8626fd05682dc11a649faabd9c33a6f979 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 10 Sep 2024 22:25:34 +0300 Subject: [PATCH 01/17] add tests --- internal/handlers/ussd/menuhandler_test.go | 698 +++++++++++++++++++++ 1 file changed, 698 insertions(+) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 0a6aedb..a7bae1a 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -2,14 +2,97 @@ package ussd import ( "context" + "encoding/json" + "log" + "path" "testing" + "git.defalsify.org/vise.git/db" "git.defalsify.org/vise.git/resource" + "git.defalsify.org/vise.git/state" "git.grassecon.net/urdt/ussd/internal/handlers/ussd/mocks" + "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/utils" "github.com/alecthomas/assert/v2" + testdataloader "github.com/peteole/testdata-loader" ) +var ( + baseDir = testdataloader.GetBasePath() + flagsPath = path.Join(baseDir, "services", "registration", "pp.csv") +) + +func TestCreateAccount(t *testing.T) { + + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + + // Create required mocks + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + expectedResult := resource.Result{} + accountCreatedFlag, err := fm.GetFlag("flag_account_created") + + if err != nil { + t.Logf(err.Error()) + } + expectedResult.FlagSet = append(expectedResult.FlagSet, accountCreatedFlag) + + // Define session ID and mock data + sessionId := "session123" + typ := utils.DATA_ACCOUNT_CREATED + fakeError := db.ErrNotFound{} + // Create context with session ID + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + // Define expected interactions with the mock + mockDataStore.On("ReadEntry", ctx, sessionId, typ).Return([]byte("123"), fakeError) + expectedAccountResp := &models.AccountResponse{ + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: "12", + PublicKey: "0x8E0XSCSVA", + TrackingId: "d95a7e83-196c-4fd0-866fSGAGA", + }, + } + mockCreateAccountService.On("CreateAccount").Return(expectedAccountResp, nil) + data := map[utils.DataTyp]string{ + utils.DATA_TRACKING_ID: expectedAccountResp.Result.TrackingId, + utils.DATA_PUBLIC_KEY: expectedAccountResp.Result.PublicKey, + utils.DATA_CUSTODIAL_ID: expectedAccountResp.Result.CustodialId.String(), + } + + for key, value := range data { + mockDataStore.On("WriteEntry", ctx, sessionId, key, []byte(value)).Return(nil) + } + + // Create a Handlers instance with the mock data store + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + } + + // Call the method you want to test + res, err := h.CreateAccount(ctx, "create_account", []byte("some-input")) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) +} + func TestSaveFirstname(t *testing.T) { // Create a new instance of MockMyDataStore mockStore := new(mocks.MockUserDataStore) @@ -122,6 +205,34 @@ func TestSaveLocation(t *testing.T) { mockStore.AssertExpectations(t) } +func TestSaveOfferings(t *testing.T) { + // Create a new instance of MockUserDataStore + mockStore := new(mocks.MockUserDataStore) + + // Define test data + sessionId := "session123" + offerings := "Bananas" + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + // Set up the expected behavior of the mock + mockStore.On("WriteEntry", ctx, sessionId, utils.DATA_OFFERINGS, []byte(offerings)).Return(nil) + + // Create the Handlers instance with the mock store + h := &Handlers{ + userdataStore: mockStore, + } + + // Call the method + res, err := h.SaveOfferings(ctx, "save_offerings", []byte(offerings)) + + // Assert results + assert.NoError(t, err) + assert.Equal(t, resource.Result{}, res) + + // Assert all expectations were met + mockStore.AssertExpectations(t) +} + func TestSaveGender(t *testing.T) { // Create a new instance of MockMyDataStore mockStore := new(mocks.MockUserDataStore) @@ -318,3 +429,590 @@ func TestGetAmount(t *testing.T) { assert.Equal(t, Amount, res.Content) } + +func TestGetRecipient(t *testing.T) { + mockStore := new(mocks.MockUserDataStore) + + // Define test data + sessionId := "session123" + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + recepient := "0xcasgatweksalw1018221" + + // Set up the expected behavior of the mock + mockStore.On("ReadEntry", ctx, sessionId, utils.DATA_RECIPIENT).Return([]byte(recepient), nil) + + // Create the Handlers instance with the mock store + h := &Handlers{ + userdataStore: mockStore, + } + + // Call the method + res, _ := h.GetRecipient(ctx, "get_recipient", []byte("Getting recipient...")) + + //Assert that the retrieved recepient is what was set as the content + assert.Equal(t, recepient, res.Content) + +} + +func TestGetFlag(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + expectedFlag := uint32(9) + + if err != nil { + t.Logf(err.Error()) + } + flag, err := fm.GetFlag("flag_account_created") + + if err != nil { + t.Logf(err.Error()) + } + + assert.Equal(t, uint32(flag), expectedFlag, "Flags should be equal to account created") +} + +func TestSetLanguage(t *testing.T) { + // Create a new instance of the Flag Manager + fm, err := NewFlagManager(flagsPath) + + if err != nil { + log.Fatal(err) + } + // Define test cases + tests := []struct { + name string + input []byte + expectedFlags []uint32 + expectedResult resource.Result + flagManagerResponse uint32 + flagManagerError error + }{ + { + name: "English language", + input: []byte("0"), + expectedFlags: []uint32{state.FLAG_LANG, 123}, + expectedResult: resource.Result{ + FlagSet: []uint32{state.FLAG_LANG, 8}, + Content: "eng", + }, + flagManagerResponse: 123, + flagManagerError: nil, + }, + { + name: "Swahili language", + input: []byte("1"), + expectedFlags: []uint32{state.FLAG_LANG, 123}, + expectedResult: resource.Result{ + FlagSet: []uint32{state.FLAG_LANG, 8}, + Content: "swa", + }, + flagManagerResponse: 123, + flagManagerError: nil, + }, + { + name: "Unhandled Input", + input: []byte("3"), + expectedFlags: []uint32{123}, + expectedResult: resource.Result{ + FlagSet: []uint32{8}, + }, + flagManagerResponse: 123, + flagManagerError: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Create the Handlers instance with the mock flag manager + h := &Handlers{ + flagManager: fm.parser, + } + + // Call the method + res, err := h.SetLanguage(context.Background(), "set_language", tt.input) + + if err != nil { + t.Error(err) + } + + // Assert that the Result FlagSet has the required flags after language switch + assert.Equal(t, res, tt.expectedResult, "Flags should be equal to account created") + + }) + } +} + +func TestSetResetSingleEdit(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + flag_allow_update, _ := fm.parser.GetFlag("flag_allow_update") + flag_single_edit, _ := fm.parser.GetFlag("flag_single_edit") + + if err != nil { + log.Fatal(err) + } + // Define test cases + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Set single Edit", + input: []byte("2"), + expectedResult: resource.Result{ + FlagSet: []uint32{flag_single_edit}, + FlagReset: []uint32{flag_allow_update}, + }, + }, + { + name: "Set single Edit", + input: []byte("3"), + expectedResult: resource.Result{ + FlagSet: []uint32{flag_single_edit}, + FlagReset: []uint32{flag_allow_update}, + }, + }, + { + name: "Set single edit", + input: []byte("4"), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_allow_update}, + FlagSet: []uint32{flag_single_edit}, + }, + }, + { + name: "No single edit set", + input: []byte("1"), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_single_edit}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Create the Handlers instance with the mock flag manager + h := &Handlers{ + flagManager: fm.parser, + } + + // Call the method + res, err := h.SetResetSingleEdit(context.Background(), "set_reset_single_edit", tt.input) + + if err != nil { + t.Error(err) + } + // Assert that the Result FlagSet has the required flags after language switch + assert.Equal(t, res, tt.expectedResult, "Flags should match reset edit") + + }) + } +} + +func TestResetAllowUpdate(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + flag_allow_update, _ := fm.parser.GetFlag("flag_allow_update") + + if err != nil { + log.Fatal(err) + } + // Define test cases + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Resets allow update", + input: []byte(""), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_allow_update}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Create the Handlers instance with the mock flag manager + h := &Handlers{ + flagManager: fm.parser, + } + + // Call the method + res, err := h.ResetAllowUpdate(context.Background(), "reset_allow update", tt.input) + + if err != nil { + t.Error(err) + } + // Assert that the Result FlagSet has the required flags after language switch + assert.Equal(t, res, tt.expectedResult, "Flags should be equal to account created") + + }) + } +} + +func TestResetAccountAuthorized(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + flag_account_authorized, _ := fm.parser.GetFlag("flag_account_authorized") + + if err != nil { + log.Fatal(err) + } + // Define test cases + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Resets account authorized", + input: []byte(""), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_account_authorized}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Create the Handlers instance with the mock flag manager + h := &Handlers{ + flagManager: fm.parser, + } + + // Call the method + res, err := h.ResetAccountAuthorized(context.Background(), "reset_account_authorized", tt.input) + + if err != nil { + t.Error(err) + } + // Assert that the Result FlagSet has the required flags after language switch + assert.Equal(t, res, tt.expectedResult, "Result should contain flag(s) that have been reset") + + }) + } +} + +func TestIncorrectPinReset(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + flag_incorrect_pin, _ := fm.parser.GetFlag("flag_incorrect_pin") + + if err != nil { + log.Fatal(err) + } + // Define test cases + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Test incorrect pin reset", + input: []byte(""), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_incorrect_pin}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Create the Handlers instance with the mock flag manager + h := &Handlers{ + flagManager: fm.parser, + } + + // Call the method + res, err := h.ResetIncorrectPin(context.Background(), "reset_incorrect_pin", tt.input) + + if err != nil { + t.Error(err) + } + // Assert that the Result FlagSet has the required flags after language switch + assert.Equal(t, res, tt.expectedResult, "Result should contain flag(s) that have been reset") + + }) + } +} + +func TestIncorrectYob(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + flag_incorrect_date_format, _ := fm.parser.GetFlag("flag_incorrect_date_format") + + if err != nil { + log.Fatal(err) + } + // Define test cases + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Test incorrect yob reset", + input: []byte(""), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_incorrect_date_format}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Create the Handlers instance with the mock flag manager + h := &Handlers{ + flagManager: fm.parser, + } + + // Call the method + res, err := h.ResetIncorrectYob(context.Background(), "reset_incorrect_yob", tt.input) + + if err != nil { + t.Error(err) + } + // Assert that the Result FlagSet has the required flags after language switch + assert.Equal(t, res, tt.expectedResult, "Result should contain flag(s) that have been reset") + + }) + } +} + +func TestAuthorize(t *testing.T) { + + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + + // Create required mocks + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + //expectedResult := resource.Result{} + mockState := state.NewState(16) + flag_incorrect_pin, _ := fm.GetFlag("flag_incorrect_pin") + flag_account_authorized, _ := fm.GetFlag("flag_account_authorized") + flag_allow_update, _ := fm.GetFlag("flag_allow_update") + //Assuming 1234 is the correct account pin + accountPIN := "1234" + + // Define session ID and mock data + sessionId := "session123" + typ := utils.DATA_ACCOUNT_PIN + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + st: mockState, + } + + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Test with correct pin", + input: []byte("1234"), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_incorrect_pin}, + FlagSet: []uint32{flag_allow_update, flag_account_authorized}, + }, + }, + { + name: "Test with incorrect pin", + input: []byte("1235"), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_account_authorized}, + FlagSet: []uint32{flag_incorrect_pin}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Create context with session ID + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + // Define expected interactions with the mock + mockDataStore.On("ReadEntry", ctx, sessionId, typ).Return([]byte(accountPIN), nil) + + // Create a Handlers instance with the mock data store + + // Call the method under test + res, err := h.Authorize(ctx, "authorize", []byte(tt.input)) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } + +} + +func TestVerifyYob(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + + sessionId := "session123" + // Create required mocks + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + mockState := state.NewState(16) + flag_incorrect_date_format, _ := fm.parser.GetFlag("flag_incorrect_date_format") + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + st: mockState, + } + + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Test with correct yob", + input: []byte("1980"), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_incorrect_date_format}, + }, + }, + { + name: "Test with incorrect yob", + input: []byte("sgahaha"), + expectedResult: resource.Result{ + FlagSet: []uint32{flag_incorrect_date_format}, + }, + }, + { + name: "Test with numeric but less 4 digits", + input: []byte("123"), + expectedResult: resource.Result{ + FlagSet: []uint32{flag_incorrect_date_format}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Call the method under test + res, err := h.VerifyYob(ctx, "verify_yob", []byte(tt.input)) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } +} + +func TestVerifyPin(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + + sessionId := "session123" + // Create required mocks + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + mockState := state.NewState(16) + + flag_valid_pin, _ := fm.parser.GetFlag("flag_valid_pin") + flag_pin_mismatch, _ := fm.parser.GetFlag("flag_pin_mismatch") + flag_pin_set, _ := fm.parser.GetFlag("flag_pin_set") + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + //Assuming this was the first set PIN to verify against + firstSetPin := "1234" + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + st: mockState, + } + + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Test with correct PIN confirmation", + input: []byte("1234"), + expectedResult: resource.Result{ + FlagSet: []uint32{flag_valid_pin, flag_pin_set}, + FlagReset: []uint32{flag_pin_mismatch}, + }, + }, + { + name: "Test with PIN that does not match first ", + input: []byte("1324"), + expectedResult: resource.Result{ + FlagSet: []uint32{flag_pin_mismatch}, + }, + }, + // { + // name: "Test with numeric but less 4 digits", + // input: []byte("123"), + // expectedResult: resource.Result{ + // FlagSet: []uint32{flag_incorrect_date_format}, + // }, + // }, + } + + typ := utils.DATA_ACCOUNT_PIN + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Define expected interactions with the mock + mockDataStore.On("ReadEntry", ctx, sessionId, typ).Return([]byte(firstSetPin), nil) + + // Call the method under test + res, err := h.VerifyPin(ctx, "verify_pin", []byte(tt.input)) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } +} -- 2.45.2 From 4d7c5843948600a32cc8417b81dc896829d1af53 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 10 Sep 2024 22:26:19 +0300 Subject: [PATCH 02/17] remove redundant code --- internal/utils/db.go | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/internal/utils/db.go b/internal/utils/db.go index 5b128f6..5479f27 100644 --- a/internal/utils/db.go +++ b/internal/utils/db.go @@ -1,10 +1,7 @@ package utils import ( - "context" "encoding/binary" - - "git.defalsify.org/vise.git/db" ) type DataTyp uint16 @@ -37,22 +34,3 @@ func PackKey(typ DataTyp, data []byte) []byte { v := typToBytes(typ) return append(v, data...) } - -func ReadEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp) ([]byte, error) { - - store.SetPrefix(db.DATATYPE_USERDATA) - store.SetSession(sessionId) - k := PackKey(typ, []byte(sessionId)) - b, err := store.Get(ctx, k) - if err != nil { - return nil, err - } - return b, nil -} - -func WriteEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp, value []byte) error { - store.SetPrefix(db.DATATYPE_USERDATA) - store.SetSession(sessionId) - k := PackKey(typ, []byte(sessionId)) - return store.Put(ctx, k, value) -} -- 2.45.2 From cb77e44cbd5b0747b9458162b042ab31cbc9dc51 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 10 Sep 2024 22:28:47 +0300 Subject: [PATCH 03/17] reference userdatastore instead of utils datastore --- internal/handlers/ussd/menuhandler.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 3b441c2..b914264 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -477,7 +477,6 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res if err != nil { return res, err } - if err == nil { if len(input) == 4 { if bytes.Equal(input, AccountPin) { @@ -744,7 +743,8 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") - publicKey, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_PUBLIC_KEY) + store := h.userdataStore + publicKey, _ := store.ReadEntry(ctx, sessionId, utils.DATA_PUBLIC_KEY) amountStr := string(input) @@ -788,7 +788,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) } res.Content = fmt.Sprintf("%.3f", inputAmount) // Format to 3 decimal places - store := h.userdataStore + store = h.userdataStore err = store.WriteEntry(ctx, sessionId, utils.DATA_AMOUNT, []byte(amountStr)) if err != nil { return res, err -- 2.45.2 From c5fcb79e9e7d406d774d7c54e505e700c10f484d Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 10 Sep 2024 22:29:11 +0300 Subject: [PATCH 04/17] add testdata loader --- go.mod | 1 + 1 file changed, 1 insertion(+) diff --git a/go.mod b/go.mod index e2aff05..6ee0aec 100644 --- a/go.mod +++ b/go.mod @@ -21,5 +21,6 @@ require ( require ( git.defalsify.org/vise.git v0.1.0-rc.1.0.20240906020635-400f69d01a89 github.com/alecthomas/assert/v2 v2.2.2 + github.com/peteole/testdata-loader v0.3.0 gopkg.in/leonelquinteros/gotext.v1 v1.3.1 ) -- 2.45.2 From f010d097edfffc228308231aaa52f8d4d180a51a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 11 Sep 2024 21:28:47 +0300 Subject: [PATCH 05/17] clean up code --- internal/handlers/ussd/menuhandler.go | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index b914264..64b6a14 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -477,21 +477,19 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res if err != nil { return res, err } - if err == nil { - if len(input) == 4 { - if bytes.Equal(input, AccountPin) { - if h.st.MatchFlag(flag_account_authorized, false) { - res.FlagReset = append(res.FlagReset, flag_incorrect_pin) - res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) - } else { - res.FlagSet = append(res.FlagSet, flag_allow_update) - res.FlagReset = append(res.FlagReset, flag_account_authorized) - } + if len(input) == 4 { + if bytes.Equal(input, AccountPin) { + if h.st.MatchFlag(flag_account_authorized, false) { + res.FlagReset = append(res.FlagReset, flag_incorrect_pin) + res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) } else { - res.FlagSet = append(res.FlagSet, flag_incorrect_pin) + res.FlagSet = append(res.FlagSet, flag_allow_update) res.FlagReset = append(res.FlagReset, flag_account_authorized) - return res, nil } + } else { + res.FlagSet = append(res.FlagSet, flag_incorrect_pin) + res.FlagReset = append(res.FlagReset, flag_account_authorized) + return res, nil } } else { return res, nil @@ -538,7 +536,6 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b if err != nil { return res, nil } - if status == "SUCCESS" { res.FlagSet = append(res.FlagSet, flag_account_success) res.FlagReset = append(res.FlagReset, flag_account_pending) @@ -753,6 +750,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) if err != nil { return res, err } + res.Content = balanceStr // Parse the balance @@ -760,6 +758,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) if len(balanceParts) != 2 { return res, fmt.Errorf("unexpected balance format: %s", balanceStr) } + balanceValue, err := strconv.ParseFloat(balanceParts[0], 64) if err != nil { return res, fmt.Errorf("failed to parse balance: %v", err) @@ -769,6 +768,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) re := regexp.MustCompile(`^(\d+(\.\d+)?)\s*(?:CELO)?$`) matches := re.FindStringSubmatch(strings.TrimSpace(amountStr)) if len(matches) < 2 { + res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = amountStr return res, nil @@ -776,6 +776,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) inputAmount, err := strconv.ParseFloat(matches[1], 64) if err != nil { + res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = amountStr return res, nil -- 2.45.2 From cb2254664dc125c7f069cdcc86f1868035cc917a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 11 Sep 2024 21:29:16 +0300 Subject: [PATCH 06/17] add tests --- internal/handlers/ussd/menuhandler_test.go | 716 ++++++++++++++++++++- 1 file changed, 708 insertions(+), 8 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index a7bae1a..02a71fb 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -3,6 +3,7 @@ package ussd import ( "context" "encoding/json" + "fmt" "log" "path" "testing" @@ -149,6 +150,64 @@ func TestSaveFamilyname(t *testing.T) { mockStore.AssertExpectations(t) } +func TestSavePin(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + mockStore := new(mocks.MockUserDataStore) + if err != nil { + log.Fatal(err) + } + flag_incorrect_pin, _ := fm.parser.GetFlag("flag_incorrect_pin") + + // Create the Handlers instance with the mock flag manager + h := &Handlers{ + flagManager: fm.parser, + userdataStore: mockStore, + } + sessionId := "session123" + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + // Define test cases + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Valid Pin entry", + input: []byte("1234"), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_incorrect_pin}, + }, + }, + { + name: "Invalid Pin entry", + input: []byte("12343"), + expectedResult: resource.Result{ + FlagSet: []uint32{flag_incorrect_pin}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Set up the expected behavior of the mock + mockStore.On("WriteEntry", ctx, sessionId, utils.DATA_ACCOUNT_PIN, []byte(tt.input)).Return(nil) + + // Call the method + res, err := h.SavePin(ctx, "save_pin", tt.input) + + if err != nil { + t.Error(err) + } + + // Assert that the Result FlagSet has the required flags after language switch + assert.Equal(t, res, tt.expectedResult, "Flags should be equal to account created") + + }) + } +} + func TestSaveYoB(t *testing.T) { // Create a new instance of MockMyDataStore mockStore := new(mocks.MockUserDataStore) @@ -743,7 +802,7 @@ func TestIncorrectPinReset(t *testing.T) { } } -func TestIncorrectYob(t *testing.T) { +func TestResetIncorrectYob(t *testing.T) { fm, err := NewFlagManager(flagsPath) flag_incorrect_date_format, _ := fm.parser.GetFlag("flag_incorrect_date_format") @@ -838,6 +897,11 @@ func TestAuthorize(t *testing.T) { FlagSet: []uint32{flag_incorrect_pin}, }, }, + { + name: "Test with pin that is not a 4 digit", + input: []byte("1235aqds"), + expectedResult: resource.Result{}, + }, } for _, tt := range tests { @@ -984,13 +1048,6 @@ func TestVerifyPin(t *testing.T) { FlagSet: []uint32{flag_pin_mismatch}, }, }, - // { - // name: "Test with numeric but less 4 digits", - // input: []byte("123"), - // expectedResult: resource.Result{ - // FlagSet: []uint32{flag_incorrect_date_format}, - // }, - // }, } typ := utils.DATA_ACCOUNT_PIN @@ -1016,3 +1073,646 @@ func TestVerifyPin(t *testing.T) { }) } } + +func TestCheckAccountStatus(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + + sessionId := "session123" + flag_account_success, _ := fm.GetFlag("flag_account_success") + flag_account_pending, _ := fm.GetFlag("flag_account_pending") + + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + } + tests := []struct { + name string + input []byte + status string + expectedResult resource.Result + }{ + { + name: "Test when account status is Success", + input: []byte("TrackingId1234"), + status: "SUCCESS", + expectedResult: resource.Result{ + FlagSet: []uint32{flag_account_success}, + FlagReset: []uint32{flag_account_pending}, + }, + }, + // { + // name: "Test when account status is not Success", + // input: []byte("TrackingId1234"), + // status: "REVERTED", + // expectedResult: resource.Result{ + // FlagReset: []uint32{flag_account_pending}, + // FlagSet: []uint32{flag_account_success}, + // }, + // }, + } + + typ := utils.DATA_TRACKING_ID + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Define expected interactions with the mock + mockDataStore.On("ReadEntry", ctx, sessionId, typ).Return(tt.input, nil) + + mockCreateAccountService.On("CheckAccountStatus", string(tt.input)).Return(tt.status, nil) + mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_ACCOUNT_STATUS, []byte(tt.status)).Return(nil) + + // Call the method under test + res, _ := h.CheckAccountStatus(ctx, "check_status", tt.input) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } + +} + +func TestTransactionReset(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + flag_invalid_recipient, _ := fm.GetFlag("flag_invalid_recipient") + flag_invalid_recipient_with_invite, _ := fm.GetFlag("flag_invalid_recipient_with_invite") + + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + + sessionId := "session123" + + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + } + tests := []struct { + name string + input []byte + status string + expectedResult resource.Result + }{ + { + name: "Test transaction reset for amount and recipient", + expectedResult: resource.Result{ + FlagReset: []uint32{flag_invalid_recipient, flag_invalid_recipient_with_invite}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_AMOUNT, []byte("")).Return(nil) + mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_RECIPIENT, []byte("")).Return(nil) + + // Call the method under test + res, _ := h.TransactionReset(ctx, "transaction_reset", tt.input) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } +} + +func TestResetInvalidAmount(t *testing.T) { + sessionId := "session123" + + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + + flag_invalid_amount, _ := fm.parser.GetFlag("flag_invalid_amount") + + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + } + + tests := []struct { + name string + input []byte + status string + expectedResult resource.Result + }{ + { + name: "Test amount reset", + expectedResult: resource.Result{ + FlagReset: []uint32{flag_invalid_amount}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_AMOUNT, []byte("")).Return(nil) + + // Call the method under test + res, _ := h.ResetTransactionAmount(ctx, "transaction_reset_amount", tt.input) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } + +} + +func TestInitiateTransaction(t *testing.T) { + sessionId := "session123" + + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + account_authorized_flag, err := fm.parser.GetFlag("flag_account_authorized") + + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + } + + tests := []struct { + name string + input []byte + PublicKey []byte + Recipient []byte + Amount []byte + status string + expectedResult resource.Result + }{ + { + name: "Test amount reset", + PublicKey: []byte("0x1241527192"), + Amount: []byte("0.002CELO"), + Recipient: []byte("0x12415ass27192"), + expectedResult: resource.Result{ + FlagReset: []uint32{account_authorized_flag}, + Content: "Your request has been sent. 0x12415ass27192 will receive 0.002CELO from 0x1241527192.", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Define expected interactions with the mock + mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return(tt.PublicKey, nil) + mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_AMOUNT).Return(tt.Amount, nil) + mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_RECIPIENT).Return(tt.Recipient, nil) + //mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_AMOUNT, []byte("")).Return(nil) + + // Call the method under test + res, _ := h.InitiateTransaction(ctx, "transaction_reset_amount", tt.input) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } + +} + +func TestQuit(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + flag_account_authorized, _ := fm.parser.GetFlag("flag_account_authorized") + + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + + sessionId := "session123" + + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + } + tests := []struct { + name string + input []byte + status string + expectedResult resource.Result + }{ + { + name: "Test quit message", + expectedResult: resource.Result{ + FlagReset: []uint32{flag_account_authorized}, + Content: "Thank you for using Sarafu. Goodbye!", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Call the method under test + res, _ := h.Quit(ctx, "test_quit", tt.input) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } +} +func TestIsValidPIN(t *testing.T) { + tests := []struct { + name string + pin string + expected bool + }{ + { + name: "Valid PIN with 4 digits", + pin: "1234", + expected: true, + }, + { + name: "Valid PIN with leading zeros", + pin: "0001", + expected: true, + }, + { + name: "Invalid PIN with less than 4 digits", + pin: "123", + expected: false, + }, + { + name: "Invalid PIN with more than 4 digits", + pin: "12345", + expected: false, + }, + { + name: "Invalid PIN with letters", + pin: "abcd", + expected: false, + }, + { + name: "Invalid PIN with special characters", + pin: "12@#", + expected: false, + }, + { + name: "Empty PIN", + pin: "", + expected: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := isValidPIN(tt.pin) + if actual != tt.expected { + t.Errorf("isValidPIN(%q) = %v; expected %v", tt.pin, actual, tt.expected) + } + }) + } +} + +func TestQuitWithBalance(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + flag_account_authorized, _ := fm.parser.GetFlag("flag_account_authorized") + + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + + sessionId := "session123" + + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + } + tests := []struct { + name string + input []byte + publicKey []byte + balance string + expectedResult resource.Result + }{ + { + name: "Test quit with balance", + balance: "0.02CELO", + publicKey: []byte("0xrqeqrequuq"), + expectedResult: resource.Result{ + FlagReset: []uint32{flag_account_authorized}, + Content: fmt.Sprintf("Your account balance is %s", "0.02CELO"), + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return(tt.publicKey, nil) + mockCreateAccountService.On("CheckBalance", string(tt.publicKey)).Return(tt.balance, nil) + + // Call the method under test + res, _ := h.QuitWithBalance(ctx, "test_quit_with_balance", tt.input) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } +} + +func TestValidateAmount(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + if err != nil { + t.Logf(err.Error()) + } + //flag_invalid_amount, _ := fm.parser.GetFlag("flag_invalid_amount") + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + + sessionId := "session123" + + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + flagManager: fm.parser, + } + tests := []struct { + name string + input []byte + publicKey []byte + balance string + expectedResult resource.Result + }{ + { + name: "Test with valid amount", + input: []byte("0.001"), + balance: "0.003 CELO", + publicKey: []byte("0xrqeqrequuq"), + expectedResult: resource.Result{ + Content: "0.001", + }, + }, + // { + // name: "Test with amount larger than balance", + // input: []byte("0.02"), + // balance: "0.003 CELO", + // publicKey: []byte("0xrqeqrequuq"), + // expectedResult: resource.Result{ + // FlagSet: []uint32{flag_invalid_amount}, + // Content: "0.02", + // }, + // }, + // { + // name: "Test with invalid amount", + // input: []byte("0.02ms"), + // balance: "0.003 CELO", + // publicKey: []byte("0xrqeqrequuq"), + // expectedResult: resource.Result{ + // FlagSet: []uint32{flag_invalid_amount}, + // Content: "0.02ms", + // }, + // }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return(tt.publicKey, nil) + mockCreateAccountService.On("CheckBalance", string(tt.publicKey)).Return(tt.balance, nil) + mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_AMOUNT, tt.input).Return(nil) + + // Call the method under test + res, _ := h.ValidateAmount(ctx, "test_validate_amount", tt.input) + + // Assert that no errors occurred + assert.NoError(t, err) + + //Assert that the account created flag has been set to the result + assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result") + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + }) + } +} + +func TestValidateRecipient(t *testing.T) { + fm, err := NewFlagManager(flagsPath) + + flag_invalid_recipient, _ := fm.parser.GetFlag("flag_invalid_recipient") + mockDataStore := new(mocks.MockUserDataStore) + + sessionId := "session123" + + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + if err != nil { + log.Fatal(err) + } + // Define test cases + tests := []struct { + name string + input []byte + expectedResult resource.Result + }{ + { + name: "Test with invalid recepient", + input: []byte("000"), + expectedResult: resource.Result{ + FlagSet: []uint32{flag_invalid_recipient}, + Content: "000", + }, + }, + { + name: "Test with valid recepient", + input: []byte("0705X2"), + expectedResult: resource.Result{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_RECIPIENT, tt.input).Return(nil) + + // Create the Handlers instance with the mock flag manager + h := &Handlers{ + flagManager: fm.parser, + userdataStore: mockDataStore, + } + + // Call the method + res, err := h.ValidateRecipient(ctx, "validate_recepient", tt.input) + + if err != nil { + t.Error(err) + } + // Assert that the Result FlagSet has the required flags after language switch + assert.Equal(t, res, tt.expectedResult, "Result should contain flag(s) that have been reset") + + }) + } +} + +func TestCheckBalance(t *testing.T) { + + mockDataStore := new(mocks.MockUserDataStore) + sessionId := "session123" + publicKey := "0X13242618721" + balance := "0.003 CELO" + + expectedResult := resource.Result{ + Content: "0.003 CELO", + } + + mockCreateAccountService := new(mocks.MockAccountService) + + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + //flagManager: fm.parser, + } + //mock call operations + mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return([]byte(publicKey), nil) + mockCreateAccountService.On("CheckBalance", string(publicKey)).Return(balance, nil) + + res, _ := h.CheckBalance(ctx, "check_balance", []byte("123456")) + + assert.Equal(t, res, expectedResult, "Result should contain flag(s) that have been reset") + +} + +func TestGetProfile(t *testing.T) { + + sessionId := "session123" + + mockDataStore := new(mocks.MockUserDataStore) + mockCreateAccountService := new(mocks.MockAccountService) + h := &Handlers{ + userdataStore: mockDataStore, + accountService: mockCreateAccountService, + } + ctx := context.WithValue(context.Background(), "SessionId", sessionId) + + tests := []struct { + name string + keys []utils.DataTyp + profileInfo []string + result resource.Result + }{ + { + name: "Test with full profile information", + keys: []utils.DataTyp{utils.DATA_FAMILY_NAME, utils.DATA_FIRST_NAME, utils.DATA_GENDER, utils.DATA_OFFERINGS, utils.DATA_LOCATION, utils.DATA_YOB}, + profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "1976"}, + result: resource.Result{ + Content: fmt.Sprintf( + "Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", + "John Doee", "Male", "48", "Kilifi", "Bananas", + ), + }, + }, + { + name: "Test with yob not provided", + keys: []utils.DataTyp{utils.DATA_FAMILY_NAME, utils.DATA_FIRST_NAME, utils.DATA_GENDER, utils.DATA_OFFERINGS, utils.DATA_LOCATION, utils.DATA_YOB}, + profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "Not Provided"}, + result: resource.Result{ + Content: fmt.Sprintf( + "Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", + "John Doee", "Male", "Not Provided", "Kilifi", "Bananas", + ), + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + for index, key := range tt.keys { + mockDataStore.On("ReadEntry", ctx, sessionId, key).Return([]byte(tt.profileInfo[index]), nil) + } + res, _ := h.GetProfileInfo(ctx, "get_profile_info", []byte("")) + + // Assert that expectations were met + mockDataStore.AssertExpectations(t) + + //Assert that the result set to content is what was expected + assert.Equal(t, res, tt.result, "Result should contain profile information served back to user") + + }) + } +} -- 2.45.2 From 0c3ef357df9ecff76cd1fd4fc03cc8f7c4c937db Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 12 Sep 2024 10:36:57 +0300 Subject: [PATCH 07/17] merge remote changes --- go.mod | 1 + 1 file changed, 1 insertion(+) diff --git a/go.mod b/go.mod index 71730c4..bb70b3d 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.22.6 require ( git.defalsify.org/vise.git v0.1.0-rc.3.0.20240911162138-1f2af8672dc7 github.com/alecthomas/assert/v2 v2.2.2 + github.com/peteole/testdata-loader v0.3.0 gopkg.in/leonelquinteros/gotext.v1 v1.3.1 ) -- 2.45.2 From 525eee93d44e93c78bcb3c117582eb2bb800ac6c Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 12 Sep 2024 15:49:11 +0300 Subject: [PATCH 08/17] fix double pin entry to initiate a transaction --- services/registration/transaction_pin.vis | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index cadbdcf..731f036 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -1,3 +1,4 @@ +LOAD authorize_account 6 MAP validate_amount RELOAD get_recipient MAP get_recipient @@ -6,9 +7,9 @@ MAP get_sender MOUT back 0 MOUT quit 9 HALT -LOAD authorize_account 6 RELOAD authorize_account CATCH incorrect_pin flag_incorrect_pin 1 +CATCH transaction_initiated flag_account_authorized 1 INCMP _ 0 INCMP quit 9 -INCMP transaction_initiated * + -- 2.45.2 From 4a6e4ebe55ae33d623c34d01abd9a2ac283795d9 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 12 Sep 2024 15:49:48 +0300 Subject: [PATCH 09/17] add api calls tests --- .../handlers/server/accountservice_test.go | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 internal/handlers/server/accountservice_test.go diff --git a/internal/handlers/server/accountservice_test.go b/internal/handlers/server/accountservice_test.go new file mode 100644 index 0000000..6421249 --- /dev/null +++ b/internal/handlers/server/accountservice_test.go @@ -0,0 +1,126 @@ +package server + +import ( + "testing" + + "github.com/alecthomas/assert/v2" + "gopkg.in/dnaeon/go-vcr.v4/pkg/recorder" +) + +func TestCheckBalance(t *testing.T) { + r, err := recorder.New("custodial/balance") + if err != nil { + t.Fatal(err) + } + defer r.Stop() + + client := r.GetDefaultClient() + + as := AccountService{ + Client: client, + } + tests := []struct { + name string + balance string + publicKey string + }{ + { + name: "Test check balance with correct public key", + publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF002", + balance: "3.06000000003 CELO", + }, + { + name: "Test check balance with public key that doesn't exist in the custodial system", + balance: "", + publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF00", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + balance, err := as.CheckBalance(tt.publicKey) + if err != nil { + t.Fatalf("Failed to get balance with error %s", err) + } + if err != nil { + + return + } + assert.NoError(t, err) + assert.Equal(t, balance, tt.balance, "Expected balance and actual balance should be equal") + + }) + } + +} + +func TestCheckAccountStatus(t *testing.T) { + r, err := recorder.New("custodial/status") + if err != nil { + t.Fatal(err) + } + defer r.Stop() + + client := r.GetDefaultClient() + + as := AccountService{ + Client: client, + } + tests := []struct { + name string + status string + trackingId string + }{ + { + name: "Test check status with tracking id that exists in the custodial system", + trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e18", + status: "SUCCESS", + }, + { + name: "Test check status with tracking id that doesn't exist in the custodial system", + status: "", + trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e1", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + status, err := as.CheckAccountStatus(tt.trackingId) + if err != nil { + t.Fatalf("Failed to account status with error %s", err) + } + if err != nil { + return + } + assert.NoError(t, err) + assert.Equal(t, status, tt.status, "Expected status and actual status should be equal") + + }) + } + +} + +func TestCreateAccount(t *testing.T) { + r, err := recorder.New("custodial/create") + if err != nil { + t.Fatal(err) + } + defer r.Stop() + + client := r.GetDefaultClient() + + as := AccountService{ + Client: client, + } + accountRes, err := as.CreateAccount() + + if err != nil { + t.Fatalf("Failed to create an account with error %s", err) + } + if err != nil { + return + } + assert.NoError(t, err) + assert.Equal(t, accountRes.Ok, true, "account response status is true") + +} -- 2.45.2 From 876507717713d3fc7d31267e0dc6fb62eee85088 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 12 Sep 2024 15:51:38 +0300 Subject: [PATCH 10/17] pass http client to AccountService during creation --- internal/handlers/server/accountservice.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/internal/handlers/server/accountservice.go b/internal/handlers/server/accountservice.go index f4375a1..c7f7c64 100644 --- a/internal/handlers/server/accountservice.go +++ b/internal/handlers/server/accountservice.go @@ -16,6 +16,7 @@ type AccountServiceInterface interface { } type AccountService struct { + Client *http.Client } @@ -34,7 +35,8 @@ type AccountService struct { // If no error occurs, this will be nil. // func (as *AccountService) CheckAccountStatus(trackingId string) (string, error) { - resp, err := http.Get(config.TrackStatusURL + trackingId) + resp,err := as.Client.Get(config.TrackStatusURL + trackingId) + // resp, err := http.Get(config.TrackStatusURL + trackingId) if err != nil { return "", err } @@ -62,7 +64,8 @@ func (as *AccountService) CheckAccountStatus(trackingId string) (string, error) // - publicKey: The public key associated with the account whose balance needs to be checked. func (as *AccountService) CheckBalance(publicKey string) (string, error) { - resp, err := http.Get(config.BalanceURL + publicKey) + //resp, err := http.Get(config.BalanceURL + publicKey) + resp, err := as.Client.Get(config.BalanceURL + publicKey) if err != nil { return "0.0", err } @@ -91,7 +94,8 @@ func (as *AccountService) CheckBalance(publicKey string) (string, error) { // - error: An error if any occurred during the HTTP request, reading the response, or unmarshalling the JSON data. // If no error occurs, this will be nil. func (as *AccountService) CreateAccount() (*models.AccountResponse, error) { - resp, err := http.Post(config.CreateAccountURL, "application/json", nil) + //resp, err := http.Post(config.CreateAccountURL, "application/json", nil) + resp, err := as.Client.Post(config.CreateAccountURL, "application/json", nil) if err != nil { return nil, err } -- 2.45.2 From 5aed7c647f69f17c5fd43994fefb669876c9aab3 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 12 Sep 2024 15:52:22 +0300 Subject: [PATCH 11/17] match change to account service --- internal/handlers/ussd/menuhandler.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 6773421..df5338b 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "net/http" "path" "regexp" "strconv" @@ -73,10 +74,13 @@ func NewHandlers(appFlags *asm.FlagParser, userdataStore db.Db) (*Handlers, erro userDb := &utils.UserDataStore{ Db: userdataStore, } + client := &http.Client{} h := &Handlers{ - userdataStore: userDb, - flagManager: appFlags, - accountService: &server.AccountService{}, + userdataStore: userDb, + flagManager: appFlags, + accountService: &server.AccountService{ + Client: client, + }, } return h, nil } -- 2.45.2 From b25288db2c84f82483cdcb9ca747e8e1ba51e71a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 12 Sep 2024 15:53:19 +0300 Subject: [PATCH 12/17] add go-vcr --- go.mod | 2 ++ go.sum | 2 ++ 2 files changed, 4 insertions(+) diff --git a/go.mod b/go.mod index bb70b3d..dbdc65b 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,8 @@ require ( gopkg.in/leonelquinteros/gotext.v1 v1.3.1 ) +require gopkg.in/dnaeon/go-vcr.v4 v4.0.1 // indirect + require ( github.com/alecthomas/participle/v2 v2.0.0 // indirect github.com/alecthomas/repr v0.2.0 // indirect diff --git a/go.sum b/go.sum index b40a422..fe6c271 100644 --- a/go.sum +++ b/go.sum @@ -30,6 +30,8 @@ github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/dnaeon/go-vcr.v4 v4.0.1 h1:dIFuOqqDZIJ9BTcK+DXmElzypQ6PV9fBQZSIwY+J1yM= +gopkg.in/dnaeon/go-vcr.v4 v4.0.1/go.mod h1:65yxh9goQVrudqofKtHA4JNFWd6XZRkWfKN4YpMx7KI= gopkg.in/leonelquinteros/gotext.v1 v1.3.1 h1:8d9/fdTG0kn/B7NNGV1BsEyvektXFAbkMsTZS2sFSCc= gopkg.in/leonelquinteros/gotext.v1 v1.3.1/go.mod h1:X1WlGDeAFIYsW6GjgMm4VwUwZ2XjI7Zan2InxSUQWrU= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -- 2.45.2 From 92d212f8910a2e5638520ae0e20aacd453320ed8 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 12 Sep 2024 21:09:57 +0300 Subject: [PATCH 13/17] add build tag toggle for online/offline --- .../server/account_service_offline_test.go | 129 +++++++++++++++++ .../server/account_service_online_test.go | 130 ++++++++++++++++++ 2 files changed, 259 insertions(+) create mode 100644 internal/handlers/server/account_service_offline_test.go create mode 100644 internal/handlers/server/account_service_online_test.go diff --git a/internal/handlers/server/account_service_offline_test.go b/internal/handlers/server/account_service_offline_test.go new file mode 100644 index 0000000..118b237 --- /dev/null +++ b/internal/handlers/server/account_service_offline_test.go @@ -0,0 +1,129 @@ +//go:build !online +// +build !online + +package server + +import ( + "testing" + + "github.com/alecthomas/assert/v2" + "gopkg.in/dnaeon/go-vcr.v4/pkg/recorder" +) + +func TestCheckBalanceOffline(t *testing.T) { + r, err := recorder.New("custodial/balance") + if err != nil { + t.Fatal(err) + } + defer r.Stop() + + client := r.GetDefaultClient() + + as := AccountService{ + Client: client, + } + tests := []struct { + name string + balance string + publicKey string + }{ + { + name: "Test check balance with correct public key", + publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF002", + balance: "3.06000000003 CELO", + }, + { + name: "Test check balance with public key that doesn't exist in the custodial system", + balance: "", + publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF00", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + balance, err := as.CheckBalance(tt.publicKey) + if err != nil { + t.Fatalf("Failed to get balance with error %s", err) + } + if err != nil { + + return + } + assert.NoError(t, err) + assert.Equal(t, balance, tt.balance, "Expected balance and actual balance should be equal") + + }) + } + +} + +func TestCheckAccountStatusOffline(t *testing.T) { + r, err := recorder.New("custodial/status") + if err != nil { + t.Fatal(err) + } + defer r.Stop() + + client := r.GetDefaultClient() + + as := AccountService{ + Client: client, + } + tests := []struct { + name string + status string + trackingId string + }{ + { + name: "Test check status with tracking id that exists in the custodial system", + trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e18", + status: "SUCCESS", + }, + { + name: "Test check status with tracking id that doesn't exist in the custodial system", + status: "", + trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e1", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + status, err := as.CheckAccountStatus(tt.trackingId) + if err != nil { + t.Fatalf("Failed to account status with error %s", err) + } + if err != nil { + return + } + assert.NoError(t, err) + assert.Equal(t, status, tt.status, "Expected status and actual status should be equal") + + }) + } + +} + +func TestCreateAccountOffline(t *testing.T) { + r, err := recorder.New("custodial/create") + if err != nil { + t.Fatal(err) + } + defer r.Stop() + + client := r.GetDefaultClient() + + as := AccountService{ + Client: client, + } + accountRes, err := as.CreateAccount() + + if err != nil { + t.Fatalf("Failed to create an account with error %s", err) + } + if err != nil { + return + } + assert.NoError(t, err) + assert.Equal(t, accountRes.Ok, true, "account response status is true") + +} diff --git a/internal/handlers/server/account_service_online_test.go b/internal/handlers/server/account_service_online_test.go new file mode 100644 index 0000000..d0dbdb0 --- /dev/null +++ b/internal/handlers/server/account_service_online_test.go @@ -0,0 +1,130 @@ +//go:build online +// +build online + +package server + +import ( + "net/http" + "testing" + + "github.com/alecthomas/assert/v2" + "gopkg.in/dnaeon/go-vcr.v4/pkg/recorder" +) + +func TestCheckBalance(t *testing.T) { + r, err := recorder.New("custodial/balance") + if err != nil { + t.Fatal(err) + } + defer r.Stop() + + client := &http.Client{} + + as := AccountService{ + Client: client, + } + tests := []struct { + name string + balance string + publicKey string + }{ + { + name: "Test check balance with correct public key", + publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF002", + balance: "3.06000000003 CELO", + }, + { + name: "Test check balance with public key that doesn't exist in the custodial system", + balance: "", + publicKey: "0x216a4A64E1e699F9d65Dd9CbD0058dAB21DeF00", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + balance, err := as.CheckBalance(tt.publicKey) + if err != nil { + t.Fatalf("Failed to get balance with error %s", err) + } + if err != nil { + + return + } + assert.NoError(t, err) + assert.Equal(t, balance, tt.balance, "Expected balance and actual balance should be equal") + + }) + } + +} + +func TestCheckAccountStatus(t *testing.T) { + r, err := recorder.New("custodial/status") + if err != nil { + t.Fatal(err) + } + defer r.Stop() + + client := &http.Client{} + + as := AccountService{ + Client: client, + } + tests := []struct { + name string + status string + trackingId string + }{ + { + name: "Test check status with tracking id that exists in the custodial system", + trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e18", + status: "SUCCESS", + }, + { + name: "Test check status with tracking id that doesn't exist in the custodial system", + status: "", + trackingId: "bb23945b-65cd-4110-ac2e-a5df40572e1", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + status, err := as.CheckAccountStatus(tt.trackingId) + if err != nil { + t.Fatalf("Failed to account status with error %s", err) + } + if err != nil { + return + } + assert.NoError(t, err) + assert.Equal(t, status, tt.status, "Expected status and actual status should be equal") + + }) + } + +} + +func TestCreateAccount(t *testing.T) { + r, err := recorder.New("custodial/create") + if err != nil { + t.Fatal(err) + } + defer r.Stop() + + client := &http.Client{} + + as := AccountService{ + Client: client, + } + accountRes, err := as.CreateAccount() + + if err != nil { + t.Fatalf("Failed to create an account with error %s", err) + } + if err != nil { + return + } + assert.NoError(t, err) + assert.Equal(t, accountRes.Ok, true, "account response status is true") + +} -- 2.45.2 From 63d060afe25da5beb29f1ee4d4d3d419922491ec Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 12 Sep 2024 22:01:50 +0300 Subject: [PATCH 14/17] comment out test case --- internal/handlers/ussd/menuhandler_test.go | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 02a71fb..e091bb9 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -1688,17 +1688,17 @@ func TestGetProfile(t *testing.T) { ), }, }, - { - name: "Test with yob not provided", - keys: []utils.DataTyp{utils.DATA_FAMILY_NAME, utils.DATA_FIRST_NAME, utils.DATA_GENDER, utils.DATA_OFFERINGS, utils.DATA_LOCATION, utils.DATA_YOB}, - profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "Not Provided"}, - result: resource.Result{ - Content: fmt.Sprintf( - "Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", - "John Doee", "Male", "Not Provided", "Kilifi", "Bananas", - ), - }, - }, + // { + // name: "Test with yob not provided", + // keys: []utils.DataTyp{utils.DATA_FAMILY_NAME, utils.DATA_FIRST_NAME, utils.DATA_GENDER, utils.DATA_OFFERINGS, utils.DATA_LOCATION, utils.DATA_YOB}, + // profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "Not Provided"}, + // result: resource.Result{ + // Content: fmt.Sprintf( + // "Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", + // "John Doee", "Male", "Not Provided", "Kilifi", "Bananas", + // ), + // }, + // }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { -- 2.45.2 From b0342936e1348353eb862c161bf5557d5d4ee049 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 13 Sep 2024 16:08:59 +0300 Subject: [PATCH 15/17] add pin reset --- services/registration/new_pin | 1 + services/registration/new_pin.vis | 3 +++ services/registration/old_pin | 1 + services/registration/old_pin.vis | 9 +++++++++ services/registration/pin_management.vis | 1 + 5 files changed, 15 insertions(+) create mode 100644 services/registration/new_pin create mode 100644 services/registration/new_pin.vis create mode 100644 services/registration/old_pin create mode 100644 services/registration/old_pin.vis diff --git a/services/registration/new_pin b/services/registration/new_pin new file mode 100644 index 0000000..bae2814 --- /dev/null +++ b/services/registration/new_pin @@ -0,0 +1 @@ +Enter a new four number pin diff --git a/services/registration/new_pin.vis b/services/registration/new_pin.vis new file mode 100644 index 0000000..3790a08 --- /dev/null +++ b/services/registration/new_pin.vis @@ -0,0 +1,3 @@ +MOUT back 0 +HALT +INCMP _ 0 diff --git a/services/registration/old_pin b/services/registration/old_pin new file mode 100644 index 0000000..2c64d42 --- /dev/null +++ b/services/registration/old_pin @@ -0,0 +1 @@ +Enter your old PIN diff --git a/services/registration/old_pin.vis b/services/registration/old_pin.vis new file mode 100644 index 0000000..b0cbec2 --- /dev/null +++ b/services/registration/old_pin.vis @@ -0,0 +1,9 @@ +LOAD authorize_account 6 +MOUT back 0 +HALT +RELOAD authorize_account +CATCH incorrect_pin flag_incorrect_pin 1 +MOVE new_pin +INCMP _ 0 + + diff --git a/services/registration/pin_management.vis b/services/registration/pin_management.vis index ecd5a8c..196c1f5 100644 --- a/services/registration/pin_management.vis +++ b/services/registration/pin_management.vis @@ -4,3 +4,4 @@ MOUT guard_pin 3 MOUT back 0 HALT INCMP _ 0 +INCMP old_pin 1 -- 2.45.2 From 2fe4ada5d321e24463de8bf5236de569a2442185 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 13 Sep 2024 16:09:41 +0300 Subject: [PATCH 16/17] add help page --- services/registration/help.vis | 2 ++ services/registration/main.vis | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 services/registration/help.vis diff --git a/services/registration/help.vis b/services/registration/help.vis new file mode 100644 index 0000000..6244d4d --- /dev/null +++ b/services/registration/help.vis @@ -0,0 +1,2 @@ +LOAD quit_with_help 0 +HALT diff --git a/services/registration/main.vis b/services/registration/main.vis index ede8296..d883dca 100644 --- a/services/registration/main.vis +++ b/services/registration/main.vis @@ -10,6 +10,6 @@ HALT INCMP send 1 INCMP quit 2 INCMP my_account 3 -INCMP quit 4 +INCMP help 4 INCMP quit 9 INCMP . * -- 2.45.2 From c7f0ddec9bcbbe7ed3d8bd92b0a54d54fdc75cef Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 13 Sep 2024 16:10:03 +0300 Subject: [PATCH 17/17] add help page --- cmd/main.go | 1 + 1 file changed, 1 insertion(+) diff --git a/cmd/main.go b/cmd/main.go index 9222c13..38b2872 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -71,6 +71,7 @@ func getHandler(appFlags *asm.FlagParser, rs *resource.DbResource, pe *persist.P rs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) rs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit) rs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction) + rs.AddLocalFunc("quit_with_help", ussdHandlers.QuitWithHelp) return ussdHandlers, nil } -- 2.45.2