From 0c08654df35dd7bac88c0ea24836e595ec0d5b20 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 21 Oct 2024 16:42:57 +0300 Subject: [PATCH 01/21] move driver to testutil --- driver/groupdriver.go | 111 ------------------------------------------ 1 file changed, 111 deletions(-) delete mode 100644 driver/groupdriver.go diff --git a/driver/groupdriver.go b/driver/groupdriver.go deleted file mode 100644 index 68cb7e3..0000000 --- a/driver/groupdriver.go +++ /dev/null @@ -1,111 +0,0 @@ -package driver - -import ( - "encoding/json" - "log" - "os" - "regexp" -) - -type Step struct { - Input string `json:"input"` - ExpectedContent string `json:"expectedContent"` -} - -func (s *Step) MatchesExpectedContent(content []byte) (bool, error) { - pattern := regexp.QuoteMeta(s.ExpectedContent) - re, err := regexp.Compile(pattern) - if err != nil { - return false, err - } - if re.Match([]byte(content)) { - return true, nil - } - return false, nil -} - -// Group represents a group of steps -type Group struct { - Name string `json:"name"` - Steps []Step `json:"steps"` -} - -type TestCase struct { - Name string - Input string - ExpectedContent string -} - -func (s *TestCase) MatchesExpectedContent(content []byte) (bool, error) { - pattern := regexp.QuoteMeta(s.ExpectedContent) - re, err := regexp.Compile(pattern) - if err != nil { - return false, err - } - // Check if the content matches the regex pattern - if re.Match(content) { - return true, nil - } - return false, nil -} - -// DataGroup represents the overall structure of the JSON. -type DataGroup struct { - Groups []Group `json:"groups"` -} - -type Session struct { - Name string `json:"name"` - Groups []Group `json:"groups"` -} - -func ReadData() []Session { - data, err := os.ReadFile("test_setup.json") - if err != nil { - log.Fatalf("Failed to read file: %v", err) - } - // Unmarshal JSON data - var sessions []Session - err = json.Unmarshal(data, &sessions) - if err != nil { - log.Fatalf("Failed to unmarshal JSON: %v", err) - } - - return sessions -} - -func FilterGroupsByName(groups []Group, name string) []Group { - var filteredGroups []Group - for _, group := range groups { - if group.Name == name { - filteredGroups = append(filteredGroups, group) - } - } - return filteredGroups -} - -func LoadTestGroups(filePath string) (DataGroup, error) { - var sessionsData DataGroup - data, err := os.ReadFile(filePath) - if err != nil { - return sessionsData, err - } - err = json.Unmarshal(data, &sessionsData) - return sessionsData, err -} - -func CreateTestCases(group DataGroup) []TestCase { - var tests []TestCase - for _, group := range group.Groups { - for _, step := range group.Steps { - // Create a test case for each group - tests = append(tests, TestCase{ - Name: group.Name, - Input: step.Input, - ExpectedContent: step.ExpectedContent, - }) - } - } - - return tests -} From 14455f65cb974a8e65a5b35f344af8914b0654e5 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 21 Oct 2024 16:43:24 +0300 Subject: [PATCH 02/21] move account service to testutil --- internal/handlers/server/accountservice.go | 59 ---------------------- 1 file changed, 59 deletions(-) diff --git a/internal/handlers/server/accountservice.go b/internal/handlers/server/accountservice.go index 5b71e6f..1ddf7e7 100644 --- a/internal/handlers/server/accountservice.go +++ b/internal/handlers/server/accountservice.go @@ -4,7 +4,6 @@ import ( "encoding/json" "io" "net/http" - "time" "git.grassecon.net/urdt/ussd/config" "git.grassecon.net/urdt/ussd/internal/models" @@ -19,9 +18,6 @@ type AccountServiceInterface interface { type AccountService struct { } -type TestAccountService struct { -} - // CheckAccountStatus retrieves the status of an account transaction based on the provided tracking ID. // // Parameters: @@ -96,58 +92,3 @@ func (as *AccountService) CreateAccount() (*models.AccountResponse, error) { } return &accountResp, nil } - -func (tas *TestAccountService) CreateAccount() (*models.AccountResponse, error) { - return &models.AccountResponse{ - Ok: true, - Result: struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - }{ - CustodialId: json.Number("182"), - PublicKey: "0x48ADca309b5085852207FAaf2816eD72B52F527C", - TrackingId: "28ebe84d-b925-472c-87ae-bbdfa1fb97be", - }, - }, nil -} - -func (tas *TestAccountService) CheckBalance(publicKey string) (*models.BalanceResponse, error) { - - balanceResponse := &models.BalanceResponse{ - Ok: true, - Result: struct { - Balance string `json:"balance"` - Nonce json.Number `json:"nonce"` - }{ - Balance: "0.003 CELO", - Nonce: json.Number("0"), - }, - } - - return balanceResponse, nil -} - -func (tas *TestAccountService) CheckAccountStatus(trackingId string) (*models.TrackStatusResponse, error) { - trackResponse := &models.TrackStatusResponse{ - Ok: true, - Result: struct { - Transaction struct { - CreatedAt time.Time "json:\"createdAt\"" - Status string "json:\"status\"" - TransferValue json.Number "json:\"transferValue\"" - TxHash string "json:\"txHash\"" - TxType string "json:\"txType\"" - } - }{ - Transaction: models.Transaction{ - CreatedAt: time.Now(), - Status: "SUCCESS", - TransferValue: json.Number("0.5"), - TxHash: "0x123abc456def", - TxType: "transfer", - }, - }, - } - return trackResponse, nil -} From 3af943f77c81f44b0cee548611aa3a1f7a9863f2 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 21 Oct 2024 16:44:02 +0300 Subject: [PATCH 03/21] move account service tags switch to test tags package --- internal/testutil/offlinetest.go | 11 ----------- internal/testutil/onlinetest.go | 9 --------- 2 files changed, 20 deletions(-) delete mode 100644 internal/testutil/offlinetest.go delete mode 100644 internal/testutil/onlinetest.go diff --git a/internal/testutil/offlinetest.go b/internal/testutil/offlinetest.go deleted file mode 100644 index 476ade3..0000000 --- a/internal/testutil/offlinetest.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !online - -package testutil - -import ( - "git.grassecon.net/urdt/ussd/internal/handlers/server" -) - -var ( - AccountService server.AccountServiceInterface = &server.TestAccountService{} -) diff --git a/internal/testutil/onlinetest.go b/internal/testutil/onlinetest.go deleted file mode 100644 index ddb5cf0..0000000 --- a/internal/testutil/onlinetest.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build online - -package testutil - -import "git.grassecon.net/urdt/ussd/internal/handlers/server" - -var ( - AccountService server.AccountServiceInterface -) From a904cdbf44f0f83f29e1151fe4d7e81f768d8abd Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 21 Oct 2024 16:45:06 +0300 Subject: [PATCH 04/21] move driver to testutil --- internal/testutil/driver/groupdriver.go | 111 ++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 internal/testutil/driver/groupdriver.go diff --git a/internal/testutil/driver/groupdriver.go b/internal/testutil/driver/groupdriver.go new file mode 100644 index 0000000..68cb7e3 --- /dev/null +++ b/internal/testutil/driver/groupdriver.go @@ -0,0 +1,111 @@ +package driver + +import ( + "encoding/json" + "log" + "os" + "regexp" +) + +type Step struct { + Input string `json:"input"` + ExpectedContent string `json:"expectedContent"` +} + +func (s *Step) MatchesExpectedContent(content []byte) (bool, error) { + pattern := regexp.QuoteMeta(s.ExpectedContent) + re, err := regexp.Compile(pattern) + if err != nil { + return false, err + } + if re.Match([]byte(content)) { + return true, nil + } + return false, nil +} + +// Group represents a group of steps +type Group struct { + Name string `json:"name"` + Steps []Step `json:"steps"` +} + +type TestCase struct { + Name string + Input string + ExpectedContent string +} + +func (s *TestCase) MatchesExpectedContent(content []byte) (bool, error) { + pattern := regexp.QuoteMeta(s.ExpectedContent) + re, err := regexp.Compile(pattern) + if err != nil { + return false, err + } + // Check if the content matches the regex pattern + if re.Match(content) { + return true, nil + } + return false, nil +} + +// DataGroup represents the overall structure of the JSON. +type DataGroup struct { + Groups []Group `json:"groups"` +} + +type Session struct { + Name string `json:"name"` + Groups []Group `json:"groups"` +} + +func ReadData() []Session { + data, err := os.ReadFile("test_setup.json") + if err != nil { + log.Fatalf("Failed to read file: %v", err) + } + // Unmarshal JSON data + var sessions []Session + err = json.Unmarshal(data, &sessions) + if err != nil { + log.Fatalf("Failed to unmarshal JSON: %v", err) + } + + return sessions +} + +func FilterGroupsByName(groups []Group, name string) []Group { + var filteredGroups []Group + for _, group := range groups { + if group.Name == name { + filteredGroups = append(filteredGroups, group) + } + } + return filteredGroups +} + +func LoadTestGroups(filePath string) (DataGroup, error) { + var sessionsData DataGroup + data, err := os.ReadFile(filePath) + if err != nil { + return sessionsData, err + } + err = json.Unmarshal(data, &sessionsData) + return sessionsData, err +} + +func CreateTestCases(group DataGroup) []TestCase { + var tests []TestCase + for _, group := range group.Groups { + for _, step := range group.Steps { + // Create a test case for each group + tests = append(tests, TestCase{ + Name: group.Name, + Input: step.Input, + ExpectedContent: step.ExpectedContent, + }) + } + } + + return tests +} From 961d8d1a5ce11964430ec50527d7cd529497c53e Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 21 Oct 2024 16:46:29 +0300 Subject: [PATCH 05/21] update package import --- menutraversal_test/menu_traversal_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/menutraversal_test/menu_traversal_test.go b/menutraversal_test/menu_traversal_test.go index 5eb1ef8..7391e5b 100644 --- a/menutraversal_test/menu_traversal_test.go +++ b/menutraversal_test/menu_traversal_test.go @@ -9,8 +9,8 @@ import ( "regexp" "testing" - "git.grassecon.net/urdt/ussd/driver" "git.grassecon.net/urdt/ussd/internal/testutil" + "git.grassecon.net/urdt/ussd/internal/testutil/driver" "github.com/gofrs/uuid" ) From 4a9ef6b5f24cba95c583991b5c35d79016f93cb3 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 21 Oct 2024 16:47:00 +0300 Subject: [PATCH 06/21] move test account service to testutil --- .../testservice/TestAccountService.go | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 internal/testutil/testservice/TestAccountService.go diff --git a/internal/testutil/testservice/TestAccountService.go b/internal/testutil/testservice/TestAccountService.go new file mode 100644 index 0000000..40c3886 --- /dev/null +++ b/internal/testutil/testservice/TestAccountService.go @@ -0,0 +1,65 @@ +package testservice + +import ( + "encoding/json" + "time" + + "git.grassecon.net/urdt/ussd/internal/models" +) + +type TestAccountService struct { +} + +func (tas *TestAccountService) CreateAccount() (*models.AccountResponse, error) { + return &models.AccountResponse{ + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: json.Number("182"), + PublicKey: "0x48ADca309b5085852207FAaf2816eD72B52F527C", + TrackingId: "28ebe84d-b925-472c-87ae-bbdfa1fb97be", + }, + }, nil +} + +func (tas *TestAccountService) CheckBalance(publicKey string) (*models.BalanceResponse, error) { + balanceResponse := &models.BalanceResponse{ + Ok: true, + Result: struct { + Balance string `json:"balance"` + Nonce json.Number `json:"nonce"` + }{ + Balance: "0.003 CELO", + Nonce: json.Number("0"), + }, + } + + return balanceResponse, nil +} + +func (tas *TestAccountService) CheckAccountStatus(trackingId string) (*models.TrackStatusResponse, error) { + trackResponse := &models.TrackStatusResponse{ + Ok: true, + Result: struct { + Transaction struct { + CreatedAt time.Time "json:\"createdAt\"" + Status string "json:\"status\"" + TransferValue json.Number "json:\"transferValue\"" + TxHash string "json:\"txHash\"" + TxType string "json:\"txType\"" + } + }{ + Transaction: models.Transaction{ + CreatedAt: time.Now(), + Status: "SUCCESS", + TransferValue: json.Number("0.5"), + TxHash: "0x123abc456def", + TxType: "transfer", + }, + }, + } + return trackResponse, nil +} From 549d09890b86d73b6ac9f6f4bad34107df5e2274 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 21 Oct 2024 16:47:25 +0300 Subject: [PATCH 07/21] update imports --- internal/testutil/TestEngine.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/internal/testutil/TestEngine.go b/internal/testutil/TestEngine.go index 2432a3f..ca48655 100644 --- a/internal/testutil/TestEngine.go +++ b/internal/testutil/TestEngine.go @@ -13,6 +13,8 @@ import ( "git.grassecon.net/urdt/ussd/internal/handlers" "git.grassecon.net/urdt/ussd/internal/handlers/server" "git.grassecon.net/urdt/ussd/internal/storage" + "git.grassecon.net/urdt/ussd/internal/testutil/testservice" + "git.grassecon.net/urdt/ussd/internal/testutil/testtag" testdataloader "github.com/peteole/testdata-loader" ) @@ -79,12 +81,12 @@ func TestEngine(sessionId string) (engine.Engine, func(), chan bool) { os.Exit(1) } - if AccountService == nil { - AccountService = &server.AccountService{} + if testtag.AccountService == nil { + testtag.AccountService = &server.AccountService{} } - switch AccountService.(type) { - case *server.TestAccountService: + switch testtag.AccountService.(type) { + case *testservice.TestAccountService: go func() { eventChannel <- false }() @@ -97,7 +99,7 @@ func TestEngine(sessionId string) (engine.Engine, func(), chan bool) { panic("Unknown account service type") } - hl, err := lhs.GetHandler(AccountService) + hl, err := lhs.GetHandler(testtag.AccountService) if err != nil { fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) From f3a5178de70d4a6290b1fc2b3746174581a54341 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 21 Oct 2024 16:47:43 +0300 Subject: [PATCH 08/21] update imports --- internal/handlers/ussd/menuhandler_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 38c468c..42e97fd 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -15,9 +15,10 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" - "git.grassecon.net/urdt/ussd/internal/handlers/server" "git.grassecon.net/urdt/ussd/internal/mocks" "git.grassecon.net/urdt/ussd/internal/models" + "git.grassecon.net/urdt/ussd/internal/testutil/testservice" + "git.grassecon.net/urdt/ussd/internal/utils" "github.com/alecthomas/assert/v2" testdataloader "github.com/peteole/testdata-loader" @@ -31,7 +32,7 @@ var ( func TestNewHandlers(t *testing.T) { fm, err := NewFlagManager(flagsPath) - accountService := server.TestAccountService{} + accountService := testservice.TestAccountService{} if err != nil { t.Logf(err.Error()) } From eaac771722225641a28271502b10267094763936 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 21 Oct 2024 16:48:24 +0300 Subject: [PATCH 09/21] move into testtag package --- internal/testutil/testtag/offlinetest.go | 12 ++++++++++++ internal/testutil/testtag/onlinetest.go | 9 +++++++++ 2 files changed, 21 insertions(+) create mode 100644 internal/testutil/testtag/offlinetest.go create mode 100644 internal/testutil/testtag/onlinetest.go diff --git a/internal/testutil/testtag/offlinetest.go b/internal/testutil/testtag/offlinetest.go new file mode 100644 index 0000000..70e2e80 --- /dev/null +++ b/internal/testutil/testtag/offlinetest.go @@ -0,0 +1,12 @@ +// +build !online + +package testtag + +import ( + "git.grassecon.net/urdt/ussd/internal/handlers/server" + accountservice "git.grassecon.net/urdt/ussd/internal/testutil/testservice" +) + +var ( + AccountService server.AccountServiceInterface = &accountservice.TestAccountService{} +) diff --git a/internal/testutil/testtag/onlinetest.go b/internal/testutil/testtag/onlinetest.go new file mode 100644 index 0000000..92cbb14 --- /dev/null +++ b/internal/testutil/testtag/onlinetest.go @@ -0,0 +1,9 @@ +// +build online + +package testtag + +import "git.grassecon.net/urdt/ussd/internal/handlers/server" + +var ( + AccountService server.AccountServiceInterface +) From e05dbb4885d033c398713adffbea31c36e8a2279 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 22 Oct 2024 20:36:58 +0300 Subject: [PATCH 10/21] check for back option --- internal/handlers/ussd/menuhandler.go | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 36d1ad5..2c4a4a5 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -27,6 +27,7 @@ var ( logg = logging.NewVanilla().WithDomain("ussdmenuhandler") scriptDir = path.Join("services", "registration") translationDir = path.Join(scriptDir, "locale") + backOption = []byte("0") ) // FlagManager handles centralized flag management @@ -326,6 +327,9 @@ func (h *Handlers) SaveFirstname(ctx context.Context, sym string, input []byte) return res, fmt.Errorf("missing session") } if len(input) > 0 { + if bytes.Equal(input, backOption) { + return res, nil + } firstName := string(input) store := h.userdataStore err = store.WriteEntry(ctx, sessionId, utils.DATA_FIRST_NAME, []byte(firstName)) @@ -345,8 +349,10 @@ func (h *Handlers) SaveFamilyname(ctx context.Context, sym string, input []byte) if !ok { return res, fmt.Errorf("missing session") } - if len(input) > 0 { + if bytes.Equal(input, backOption) { + return res, nil + } familyName := string(input) store := h.userdataStore err = store.WriteEntry(ctx, sessionId, utils.DATA_FAMILY_NAME, []byte(familyName)) @@ -389,8 +395,10 @@ func (h *Handlers) SaveLocation(ctx context.Context, sym string, input []byte) ( if !ok { return res, fmt.Errorf("missing session") } - if len(input) > 0 { + if bytes.Equal(input, backOption) { + return res, nil + } location := string(input) store := h.userdataStore err = store.WriteEntry(ctx, sessionId, utils.DATA_LOCATION, []byte(location)) @@ -411,7 +419,9 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re if !ok { return res, fmt.Errorf("missing session") } - + if bytes.Equal(input, backOption) { + return res, nil + } gender := strings.Split(symbol, "_")[1] store := h.userdataStore err = store.WriteEntry(ctx, sessionId, utils.DATA_GENDER, []byte(gender)) From 306666a15e321ea3c9b81ed9496d1634ccfbb479 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 22 Oct 2024 20:37:30 +0300 Subject: [PATCH 11/21] load and reload after halt --- services/registration/enter_familyname.vis | 3 +-- services/registration/enter_location.vis | 2 +- services/registration/enter_name.vis | 6 +----- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/services/registration/enter_familyname.vis b/services/registration/enter_familyname.vis index b9fe7b0..5a684ed 100644 --- a/services/registration/enter_familyname.vis +++ b/services/registration/enter_familyname.vis @@ -1,9 +1,8 @@ CATCH incorrect_pin flag_incorrect_pin 1 CATCH profile_update_success flag_allow_update 1 -LOAD save_familyname 0 -RELOAD save_familyname MOUT back 0 HALT +LOAD save_familyname 0 RELOAD save_familyname INCMP _ 0 INCMP pin_entry * diff --git a/services/registration/enter_location.vis b/services/registration/enter_location.vis index fdd29ce..c8da2dd 100644 --- a/services/registration/enter_location.vis +++ b/services/registration/enter_location.vis @@ -1,8 +1,8 @@ CATCH incorrect_pin flag_incorrect_pin 1 CATCH profile_update_success flag_allow_update 1 -LOAD save_location 0 MOUT back 0 HALT +LOAD save_location 0 RELOAD save_location INCMP _ 0 INCMP pin_entry * diff --git a/services/registration/enter_name.vis b/services/registration/enter_name.vis index 563577e..799b2a1 100644 --- a/services/registration/enter_name.vis +++ b/services/registration/enter_name.vis @@ -1,12 +1,8 @@ CATCH incorrect_pin flag_incorrect_pin 1 CATCH profile_update_success flag_allow_update 1 -LOAD save_firstname 0 -RELOAD save_firstname MOUT back 0 HALT +LOAD save_firstname 0 RELOAD save_firstname INCMP _ 0 INCMP pin_entry * - - - From 1e6cf6a33a94a6ebbe8a212b0db1c231ba7fe7ec Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 23 Oct 2024 11:08:51 +0300 Subject: [PATCH 12/21] run mod tidy --- go.mod | 13 ++++++++++++- go.sum | 35 ++++++++++++++++++++++++++++++----- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 38be305..3349bf8 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,18 @@ require ( gopkg.in/leonelquinteros/gotext.v1 v1.3.1 ) -require github.com/joho/godotenv v1.5.1 // indirect +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.7.0 // indirect + github.com/jackc/puddle/v2 v2.2.1 // indirect + github.com/joho/godotenv v1.5.1 + github.com/kr/text v0.2.0 // indirect + github.com/rogpeppe/go-internal v1.13.1 // indirect + golang.org/x/crypto v0.27.0 // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/text v0.18.0 // indirect +) require ( github.com/alecthomas/participle/v2 v2.0.0 // indirect diff --git a/go.sum b/go.sum index 2abec41..ef40172 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,3 @@ -git.defalsify.org/vise.git v0.1.0-rc.3.0.20240923162317-c20d557a3dbb h1:6P4kxihcwMjDKzvUFC6t2zGNb7MDW+l/ACGlSAN1N8Y= -git.defalsify.org/vise.git v0.1.0-rc.3.0.20240923162317-c20d557a3dbb/go.mod h1:JDguWmcoWBdsnpw7PUjVZAEpdC/ubBmjdUBy3tjP63M= -git.defalsify.org/vise.git v0.2.0 h1:X2ZgiGRq4C+9qOlDMP0b/oE5QHjVQNT4aEFZB88ST0Q= -git.defalsify.org/vise.git v0.2.0/go.mod h1:JDguWmcoWBdsnpw7PUjVZAEpdC/ubBmjdUBy3tjP63M= git.defalsify.org/vise.git v0.2.1-0.20241017112704-307fa6fcdc6b h1:dxBplsIlzJHV+5EH+gzB+w08Blt7IJbb2jeRe1OEjLU= git.defalsify.org/vise.git v0.2.1-0.20241017112704-307fa6fcdc6b/go.mod h1:jyBMe1qTYUz3mmuoC9JQ/TvFeW0vTanCUcPu3H8p4Ck= github.com/alecthomas/assert/v2 v2.2.2 h1:Z/iVC0xZfWTaFNE6bA3z07T86hd45Xe2eLt6WVy2bbk= @@ -12,6 +8,8 @@ github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c h1:H9Nm+I7Cg/YVPpEV1RzU3Wq2pjamPc/UtHDgItcb7lE= github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c/go.mod h1:rGod7o6KPeJ+hyBpHfhi4v7blx9sf+QsHsA7KAsdN6U= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fxamacker/cbor/v2 v2.4.0 h1:ri0ArlOR+5XunOP8CRUowT0pSJOwhW098ZCUyskZD88= @@ -22,23 +20,50 @@ github.com/graygnuorg/go-gdbm v0.0.0-20220711140707-71387d66dce4 h1:U4kkNYryi/qf github.com/graygnuorg/go-gdbm v0.0.0-20220711140707-71387d66dce4/go.mod h1:zpZDgZFzeq9s0MIeB1P50NIEWDFFHSFBohI/NbaTD/Y= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.7.0 h1:FG6VLIdzvAPhnYqP14sQ2xhFLkiUQHCs6ySqO91kF4g= +github.com/jackc/pgx/v5 v5.7.0/go.mod h1:awP1KNnjylvpxHuHP63gzjhnGkI1iw+PMoIwvoleN/8= +github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= +github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mattn/kinako v0.0.0-20170717041458-332c0a7e205a h1:0Q3H0YXzMHiciXtRcM+j0jiCe8WKPQHoRgQiRTnfcLY= github.com/mattn/kinako v0.0.0-20170717041458-332c0a7e205a/go.mod h1:CdTTBOYzS5E4mWS1N8NWP6AHI19MP0A2B18n3hLzRMk= +github.com/pashagolub/pgxmock/v4 v4.3.0 h1:DqT7fk0OCK6H0GvqtcMsLpv8cIwWqdxWgfZNLeHCb/s= +github.com/pashagolub/pgxmock/v4 v4.3.0/go.mod h1:9VoVHXwS3XR/yPtKGzwQvwZX1kzGB9sM8SviDcHDa3A= github.com/peteole/testdata-loader v0.3.0 h1:8jckE9KcyNHgyv/VPoaljvKZE0Rqr8+dPVYH6rfNr9I= github.com/peteole/testdata-loader v0.3.0/go.mod h1:Mt0ZbRtb56u8SLJpNP+BnQbENljMorYBpqlvt3cS83U= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 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= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 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.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From f3a028f1fc73ef2a84b80787585386af59b83920 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 24 Oct 2024 12:03:32 +0300 Subject: [PATCH 13/21] move to testutil --- internal/mocks/dbmock.go | 59 ------------------- internal/mocks/httpmocks/enginemock.go | 30 ---------- .../mocks/httpmocks/requesthandlermock.go | 47 --------------- internal/mocks/httpmocks/requestparsermock.go | 15 ----- internal/mocks/httpmocks/writermock.go | 25 -------- internal/mocks/servicemock.go | 26 -------- internal/mocks/userdbmock.go | 24 -------- 7 files changed, 226 deletions(-) delete mode 100644 internal/mocks/dbmock.go delete mode 100644 internal/mocks/httpmocks/enginemock.go delete mode 100644 internal/mocks/httpmocks/requesthandlermock.go delete mode 100644 internal/mocks/httpmocks/requestparsermock.go delete mode 100644 internal/mocks/httpmocks/writermock.go delete mode 100644 internal/mocks/servicemock.go delete mode 100644 internal/mocks/userdbmock.go diff --git a/internal/mocks/dbmock.go b/internal/mocks/dbmock.go deleted file mode 100644 index 0b40eab..0000000 --- a/internal/mocks/dbmock.go +++ /dev/null @@ -1,59 +0,0 @@ -package mocks - -import ( - "context" - - "git.defalsify.org/vise.git/lang" - "github.com/stretchr/testify/mock" -) - -type MockDb struct { - mock.Mock -} - -func (m *MockDb) SetPrefix(prefix uint8) { - m.Called(prefix) -} - -func (m *MockDb) Prefix() uint8 { - args := m.Called() - return args.Get(0).(uint8) -} - -func (m *MockDb) Safe() bool { - args := m.Called() - return args.Get(0).(bool) -} - -func (m *MockDb) SetLanguage(language *lang.Language) { - m.Called(language) -} - -func (m *MockDb) SetLock(uint8, bool) error { - args := m.Called() - return args.Error(0) -} - -func (m *MockDb) Connect(ctx context.Context, connectionStr string) error { - args := m.Called(ctx, connectionStr) - return args.Error(0) -} - -func (m *MockDb) SetSession(sessionId string) { - m.Called(sessionId) -} - -func (m *MockDb) Put(ctx context.Context, key, value []byte) error { - args := m.Called(ctx, key, value) - return args.Error(0) -} - -func (m *MockDb) Get(ctx context.Context, key []byte) ([]byte, error) { - args := m.Called(ctx, key) - return nil, args.Error(0) -} - -func (m *MockDb) Close() error { - args := m.Called(nil) - return args.Error(0) -} diff --git a/internal/mocks/httpmocks/enginemock.go b/internal/mocks/httpmocks/enginemock.go deleted file mode 100644 index 12d07f4..0000000 --- a/internal/mocks/httpmocks/enginemock.go +++ /dev/null @@ -1,30 +0,0 @@ -package httpmocks - -import ( - "context" - "io" -) - -// MockEngine implements the engine.Engine interface for testing -type MockEngine struct { - InitFunc func(context.Context) (bool, error) - ExecFunc func(context.Context, []byte) (bool, error) - FlushFunc func(context.Context, io.Writer) (int, error) - FinishFunc func() error -} - -func (m *MockEngine) Init(ctx context.Context) (bool, error) { - return m.InitFunc(ctx) -} - -func (m *MockEngine) Exec(ctx context.Context, input []byte) (bool, error) { - return m.ExecFunc(ctx, input) -} - -func (m *MockEngine) Flush(ctx context.Context, w io.Writer) (int, error) { - return m.FlushFunc(ctx, w) -} - -func (m *MockEngine) Finish() error { - return m.FinishFunc() -} diff --git a/internal/mocks/httpmocks/requesthandlermock.go b/internal/mocks/httpmocks/requesthandlermock.go deleted file mode 100644 index f17abce..0000000 --- a/internal/mocks/httpmocks/requesthandlermock.go +++ /dev/null @@ -1,47 +0,0 @@ -package httpmocks - -import ( - "git.defalsify.org/vise.git/engine" - "git.defalsify.org/vise.git/persist" - "git.defalsify.org/vise.git/resource" - "git.grassecon.net/urdt/ussd/internal/handlers" -) - -// MockRequestHandler implements handlers.RequestHandler interface for testing -type MockRequestHandler struct { - ProcessFunc func(handlers.RequestSession) (handlers.RequestSession, error) - GetConfigFunc func() engine.Config - GetEngineFunc func(cfg engine.Config, rs resource.Resource, pe *persist.Persister) engine.Engine - OutputFunc func(rs handlers.RequestSession) (handlers.RequestSession, error) - ResetFunc func(rs handlers.RequestSession) (handlers.RequestSession, error) - ShutdownFunc func() - GetRequestParserFunc func() handlers.RequestParser -} - -func (m *MockRequestHandler) Process(rqs handlers.RequestSession) (handlers.RequestSession, error) { - return m.ProcessFunc(rqs) -} - -func (m *MockRequestHandler) GetConfig() engine.Config { - return m.GetConfigFunc() -} - -func (m *MockRequestHandler) GetEngine(cfg engine.Config, rs resource.Resource, pe *persist.Persister) engine.Engine { - return m.GetEngineFunc(cfg, rs, pe) -} - -func (m *MockRequestHandler) Output(rs handlers.RequestSession) (handlers.RequestSession, error) { - return m.OutputFunc(rs) -} - -func (m *MockRequestHandler) Reset(rs handlers.RequestSession) (handlers.RequestSession, error) { - return m.ResetFunc(rs) -} - -func (m *MockRequestHandler) Shutdown() { - m.ShutdownFunc() -} - -func (m *MockRequestHandler) GetRequestParser() handlers.RequestParser { - return m.GetRequestParserFunc() -} diff --git a/internal/mocks/httpmocks/requestparsermock.go b/internal/mocks/httpmocks/requestparsermock.go deleted file mode 100644 index 54b16bf..0000000 --- a/internal/mocks/httpmocks/requestparsermock.go +++ /dev/null @@ -1,15 +0,0 @@ -package httpmocks - -// MockRequestParser implements the handlers.RequestParser interface for testing -type MockRequestParser struct { - GetSessionIdFunc func(any) (string, error) - GetInputFunc func(any) ([]byte, error) -} - -func (m *MockRequestParser) GetSessionId(rq any) (string, error) { - return m.GetSessionIdFunc(rq) -} - -func (m *MockRequestParser) GetInput(rq any) ([]byte, error) { - return m.GetInputFunc(rq) -} diff --git a/internal/mocks/httpmocks/writermock.go b/internal/mocks/httpmocks/writermock.go deleted file mode 100644 index 0d171d2..0000000 --- a/internal/mocks/httpmocks/writermock.go +++ /dev/null @@ -1,25 +0,0 @@ -package httpmocks - -import "net/http" - -// MockWriter implements a mock io.Writer for testing -type MockWriter struct { - WriteStringCalled bool - WrittenString string -} - -func (m *MockWriter) Write(p []byte) (n int, err error) { - return len(p), nil -} - -func (m *MockWriter) WriteString(s string) (n int, err error) { - m.WriteStringCalled = true - m.WrittenString = s - return len(s), nil -} - -func (m *MockWriter) Header() http.Header { - return http.Header{} -} - -func (m *MockWriter) WriteHeader(statusCode int) {} \ No newline at end of file diff --git a/internal/mocks/servicemock.go b/internal/mocks/servicemock.go deleted file mode 100644 index d828045..0000000 --- a/internal/mocks/servicemock.go +++ /dev/null @@ -1,26 +0,0 @@ -package mocks - -import ( - "git.grassecon.net/urdt/ussd/internal/models" - "github.com/stretchr/testify/mock" -) - -// MockAccountService implements AccountServiceInterface for testing -type MockAccountService struct { - mock.Mock -} - -func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) { - args := m.Called() - return args.Get(0).(*models.AccountResponse), args.Error(1) -} - -func (m *MockAccountService) CheckBalance(publicKey string) (*models.BalanceResponse, error) { - args := m.Called(publicKey) - return args.Get(0).(*models.BalanceResponse), args.Error(1) -} - -func (m *MockAccountService) CheckAccountStatus(trackingId string) (*models.TrackStatusResponse, error) { - args := m.Called(trackingId) - return args.Get(0).(*models.TrackStatusResponse), args.Error(1) -} \ No newline at end of file diff --git a/internal/mocks/userdbmock.go b/internal/mocks/userdbmock.go deleted file mode 100644 index ff3f18d..0000000 --- a/internal/mocks/userdbmock.go +++ /dev/null @@ -1,24 +0,0 @@ -package mocks - -import ( - "context" - - "git.defalsify.org/vise.git/db" - "git.grassecon.net/urdt/ussd/internal/utils" - "github.com/stretchr/testify/mock" -) - -type MockUserDataStore struct { - db.Db - mock.Mock -} - -func (m *MockUserDataStore) ReadEntry(ctx context.Context, sessionId string, typ utils.DataTyp) ([]byte, error) { - args := m.Called(ctx, sessionId, typ) - return args.Get(0).([]byte), args.Error(1) -} - -func (m *MockUserDataStore) WriteEntry(ctx context.Context, sessionId string, typ utils.DataTyp, value []byte) error { - args := m.Called(ctx, sessionId, typ, value) - return args.Error(0) -} From 651969668f64e82fcfe18a26b9a18f5b44fef677 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 24 Oct 2024 12:05:11 +0300 Subject: [PATCH 14/21] move to testutil --- internal/testutil/mocks/dbmock.go | 59 +++++++++++++++++++ .../testutil/mocks/httpmocks/enginemock.go | 30 ++++++++++ .../mocks/httpmocks/requesthandlermock.go | 47 +++++++++++++++ .../mocks/httpmocks/requestparsermock.go | 15 +++++ .../testutil/mocks/httpmocks/writermock.go | 25 ++++++++ internal/testutil/mocks/servicemock.go | 26 ++++++++ 6 files changed, 202 insertions(+) create mode 100644 internal/testutil/mocks/dbmock.go create mode 100644 internal/testutil/mocks/httpmocks/enginemock.go create mode 100644 internal/testutil/mocks/httpmocks/requesthandlermock.go create mode 100644 internal/testutil/mocks/httpmocks/requestparsermock.go create mode 100644 internal/testutil/mocks/httpmocks/writermock.go create mode 100644 internal/testutil/mocks/servicemock.go diff --git a/internal/testutil/mocks/dbmock.go b/internal/testutil/mocks/dbmock.go new file mode 100644 index 0000000..0b40eab --- /dev/null +++ b/internal/testutil/mocks/dbmock.go @@ -0,0 +1,59 @@ +package mocks + +import ( + "context" + + "git.defalsify.org/vise.git/lang" + "github.com/stretchr/testify/mock" +) + +type MockDb struct { + mock.Mock +} + +func (m *MockDb) SetPrefix(prefix uint8) { + m.Called(prefix) +} + +func (m *MockDb) Prefix() uint8 { + args := m.Called() + return args.Get(0).(uint8) +} + +func (m *MockDb) Safe() bool { + args := m.Called() + return args.Get(0).(bool) +} + +func (m *MockDb) SetLanguage(language *lang.Language) { + m.Called(language) +} + +func (m *MockDb) SetLock(uint8, bool) error { + args := m.Called() + return args.Error(0) +} + +func (m *MockDb) Connect(ctx context.Context, connectionStr string) error { + args := m.Called(ctx, connectionStr) + return args.Error(0) +} + +func (m *MockDb) SetSession(sessionId string) { + m.Called(sessionId) +} + +func (m *MockDb) Put(ctx context.Context, key, value []byte) error { + args := m.Called(ctx, key, value) + return args.Error(0) +} + +func (m *MockDb) Get(ctx context.Context, key []byte) ([]byte, error) { + args := m.Called(ctx, key) + return nil, args.Error(0) +} + +func (m *MockDb) Close() error { + args := m.Called(nil) + return args.Error(0) +} diff --git a/internal/testutil/mocks/httpmocks/enginemock.go b/internal/testutil/mocks/httpmocks/enginemock.go new file mode 100644 index 0000000..12d07f4 --- /dev/null +++ b/internal/testutil/mocks/httpmocks/enginemock.go @@ -0,0 +1,30 @@ +package httpmocks + +import ( + "context" + "io" +) + +// MockEngine implements the engine.Engine interface for testing +type MockEngine struct { + InitFunc func(context.Context) (bool, error) + ExecFunc func(context.Context, []byte) (bool, error) + FlushFunc func(context.Context, io.Writer) (int, error) + FinishFunc func() error +} + +func (m *MockEngine) Init(ctx context.Context) (bool, error) { + return m.InitFunc(ctx) +} + +func (m *MockEngine) Exec(ctx context.Context, input []byte) (bool, error) { + return m.ExecFunc(ctx, input) +} + +func (m *MockEngine) Flush(ctx context.Context, w io.Writer) (int, error) { + return m.FlushFunc(ctx, w) +} + +func (m *MockEngine) Finish() error { + return m.FinishFunc() +} diff --git a/internal/testutil/mocks/httpmocks/requesthandlermock.go b/internal/testutil/mocks/httpmocks/requesthandlermock.go new file mode 100644 index 0000000..f17abce --- /dev/null +++ b/internal/testutil/mocks/httpmocks/requesthandlermock.go @@ -0,0 +1,47 @@ +package httpmocks + +import ( + "git.defalsify.org/vise.git/engine" + "git.defalsify.org/vise.git/persist" + "git.defalsify.org/vise.git/resource" + "git.grassecon.net/urdt/ussd/internal/handlers" +) + +// MockRequestHandler implements handlers.RequestHandler interface for testing +type MockRequestHandler struct { + ProcessFunc func(handlers.RequestSession) (handlers.RequestSession, error) + GetConfigFunc func() engine.Config + GetEngineFunc func(cfg engine.Config, rs resource.Resource, pe *persist.Persister) engine.Engine + OutputFunc func(rs handlers.RequestSession) (handlers.RequestSession, error) + ResetFunc func(rs handlers.RequestSession) (handlers.RequestSession, error) + ShutdownFunc func() + GetRequestParserFunc func() handlers.RequestParser +} + +func (m *MockRequestHandler) Process(rqs handlers.RequestSession) (handlers.RequestSession, error) { + return m.ProcessFunc(rqs) +} + +func (m *MockRequestHandler) GetConfig() engine.Config { + return m.GetConfigFunc() +} + +func (m *MockRequestHandler) GetEngine(cfg engine.Config, rs resource.Resource, pe *persist.Persister) engine.Engine { + return m.GetEngineFunc(cfg, rs, pe) +} + +func (m *MockRequestHandler) Output(rs handlers.RequestSession) (handlers.RequestSession, error) { + return m.OutputFunc(rs) +} + +func (m *MockRequestHandler) Reset(rs handlers.RequestSession) (handlers.RequestSession, error) { + return m.ResetFunc(rs) +} + +func (m *MockRequestHandler) Shutdown() { + m.ShutdownFunc() +} + +func (m *MockRequestHandler) GetRequestParser() handlers.RequestParser { + return m.GetRequestParserFunc() +} diff --git a/internal/testutil/mocks/httpmocks/requestparsermock.go b/internal/testutil/mocks/httpmocks/requestparsermock.go new file mode 100644 index 0000000..54b16bf --- /dev/null +++ b/internal/testutil/mocks/httpmocks/requestparsermock.go @@ -0,0 +1,15 @@ +package httpmocks + +// MockRequestParser implements the handlers.RequestParser interface for testing +type MockRequestParser struct { + GetSessionIdFunc func(any) (string, error) + GetInputFunc func(any) ([]byte, error) +} + +func (m *MockRequestParser) GetSessionId(rq any) (string, error) { + return m.GetSessionIdFunc(rq) +} + +func (m *MockRequestParser) GetInput(rq any) ([]byte, error) { + return m.GetInputFunc(rq) +} diff --git a/internal/testutil/mocks/httpmocks/writermock.go b/internal/testutil/mocks/httpmocks/writermock.go new file mode 100644 index 0000000..0d171d2 --- /dev/null +++ b/internal/testutil/mocks/httpmocks/writermock.go @@ -0,0 +1,25 @@ +package httpmocks + +import "net/http" + +// MockWriter implements a mock io.Writer for testing +type MockWriter struct { + WriteStringCalled bool + WrittenString string +} + +func (m *MockWriter) Write(p []byte) (n int, err error) { + return len(p), nil +} + +func (m *MockWriter) WriteString(s string) (n int, err error) { + m.WriteStringCalled = true + m.WrittenString = s + return len(s), nil +} + +func (m *MockWriter) Header() http.Header { + return http.Header{} +} + +func (m *MockWriter) WriteHeader(statusCode int) {} \ No newline at end of file diff --git a/internal/testutil/mocks/servicemock.go b/internal/testutil/mocks/servicemock.go new file mode 100644 index 0000000..d828045 --- /dev/null +++ b/internal/testutil/mocks/servicemock.go @@ -0,0 +1,26 @@ +package mocks + +import ( + "git.grassecon.net/urdt/ussd/internal/models" + "github.com/stretchr/testify/mock" +) + +// MockAccountService implements AccountServiceInterface for testing +type MockAccountService struct { + mock.Mock +} + +func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) { + args := m.Called() + return args.Get(0).(*models.AccountResponse), args.Error(1) +} + +func (m *MockAccountService) CheckBalance(publicKey string) (*models.BalanceResponse, error) { + args := m.Called(publicKey) + return args.Get(0).(*models.BalanceResponse), args.Error(1) +} + +func (m *MockAccountService) CheckAccountStatus(trackingId string) (*models.TrackStatusResponse, error) { + args := m.Called(trackingId) + return args.Get(0).(*models.TrackStatusResponse), args.Error(1) +} \ No newline at end of file From 5692440099109d321a7a8487407b82fcd6cb561c Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 24 Oct 2024 12:05:27 +0300 Subject: [PATCH 15/21] move to testutil --- internal/testutil/mocks/userdbmock.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 internal/testutil/mocks/userdbmock.go diff --git a/internal/testutil/mocks/userdbmock.go b/internal/testutil/mocks/userdbmock.go new file mode 100644 index 0000000..ff3f18d --- /dev/null +++ b/internal/testutil/mocks/userdbmock.go @@ -0,0 +1,24 @@ +package mocks + +import ( + "context" + + "git.defalsify.org/vise.git/db" + "git.grassecon.net/urdt/ussd/internal/utils" + "github.com/stretchr/testify/mock" +) + +type MockUserDataStore struct { + db.Db + mock.Mock +} + +func (m *MockUserDataStore) ReadEntry(ctx context.Context, sessionId string, typ utils.DataTyp) ([]byte, error) { + args := m.Called(ctx, sessionId, typ) + return args.Get(0).([]byte), args.Error(1) +} + +func (m *MockUserDataStore) WriteEntry(ctx context.Context, sessionId string, typ utils.DataTyp, value []byte) error { + args := m.Called(ctx, sessionId, typ, value) + return args.Error(0) +} From 57a07af8caee42c2a5a64abffaa41e7203a93fa5 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 24 Oct 2024 12:06:44 +0300 Subject: [PATCH 16/21] correct import --- internal/http/http_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/http/http_test.go b/internal/http/http_test.go index 8f6f312..14bb90a 100644 --- a/internal/http/http_test.go +++ b/internal/http/http_test.go @@ -13,7 +13,7 @@ import ( "git.defalsify.org/vise.git/engine" "git.grassecon.net/urdt/ussd/internal/handlers" - "git.grassecon.net/urdt/ussd/internal/mocks/httpmocks" + "git.grassecon.net/urdt/ussd/internal/testutil/mocks/httpmocks" ) // invalidRequestType is a custom type to test invalid request scenarios From f99486c19067bfe084e08b1811500c6173b8e350 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 24 Oct 2024 12:07:00 +0300 Subject: [PATCH 17/21] correct import --- internal/handlers/ussd/menuhandler_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 42e97fd..482e997 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -15,8 +15,8 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" - "git.grassecon.net/urdt/ussd/internal/mocks" "git.grassecon.net/urdt/ussd/internal/models" + "git.grassecon.net/urdt/ussd/internal/testutil/mocks" "git.grassecon.net/urdt/ussd/internal/testutil/testservice" "git.grassecon.net/urdt/ussd/internal/utils" From a3be98c5144f46171a970a044ceff0114d8a9337 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 25 Oct 2024 09:36:43 +0300 Subject: [PATCH 18/21] update test account service --- .../testservice/TestAccountService.go | 34 ++++++++++++------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/internal/testutil/testservice/TestAccountService.go b/internal/testutil/testservice/TestAccountService.go index 40c3886..81f66ef 100644 --- a/internal/testutil/testservice/TestAccountService.go +++ b/internal/testutil/testservice/TestAccountService.go @@ -1,31 +1,29 @@ package testservice import ( + "context" "encoding/json" "time" "git.grassecon.net/urdt/ussd/internal/models" + "github.com/grassrootseconomics/eth-custodial/pkg/api" ) type TestAccountService struct { } -func (tas *TestAccountService) CreateAccount() (*models.AccountResponse, error) { - return &models.AccountResponse{ - Ok: true, - Result: struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - }{ - CustodialId: json.Number("182"), - PublicKey: "0x48ADca309b5085852207FAaf2816eD72B52F527C", - TrackingId: "28ebe84d-b925-472c-87ae-bbdfa1fb97be", +func (tas *TestAccountService) CreateAccount(ctx context.Context) (*api.OKResponse, error) { + return &api.OKResponse{ + Ok: true, + Description: "Account creation succeeded", + Result: map[string]any{ + "trackingId": "075ccc86-f6ef-4d33-97d5-e91cfb37aa0d", + "publicKey": "0x623EFAFa8868df4B934dd12a8B26CB3Dd75A7AdD", }, }, nil } -func (tas *TestAccountService) CheckBalance(publicKey string) (*models.BalanceResponse, error) { +func (tas *TestAccountService) CheckBalance(ctx context.Context, publicKey string) (*models.BalanceResponse, error) { balanceResponse := &models.BalanceResponse{ Ok: true, Result: struct { @@ -40,7 +38,7 @@ func (tas *TestAccountService) CheckBalance(publicKey string) (*models.BalanceRe return balanceResponse, nil } -func (tas *TestAccountService) CheckAccountStatus(trackingId string) (*models.TrackStatusResponse, error) { +func (tas *TestAccountService) CheckAccountStatus(ctx context.Context, trackingId string) (*models.TrackStatusResponse, error) { trackResponse := &models.TrackStatusResponse{ Ok: true, Result: struct { @@ -63,3 +61,13 @@ func (tas *TestAccountService) CheckAccountStatus(trackingId string) (*models.Tr } return trackResponse, nil } + +func (tas *TestAccountService) TrackAccountStatus(ctx context.Context, publicKey string) (*api.OKResponse, error) { + return &api.OKResponse{ + Ok: true, + Description: "Account creation succeeded", + Result: map[string]any{ + "active": true, + }, + }, nil +} From a0e97cfe5b07638d37fdb57a03333001ee81f4da Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 25 Oct 2024 09:37:16 +0300 Subject: [PATCH 19/21] remove test account service implementation --- internal/handlers/server/accountservice.go | 60 ---------------------- 1 file changed, 60 deletions(-) diff --git a/internal/handlers/server/accountservice.go b/internal/handlers/server/accountservice.go index a861e71..93e57a3 100644 --- a/internal/handlers/server/accountservice.go +++ b/internal/handlers/server/accountservice.go @@ -28,9 +28,6 @@ type AccountServiceInterface interface { type AccountService struct { } -type TestAccountService struct { -} - // Parameters: // - trackingId: A unique identifier for the account.This should be obtained from a previous call to // CreateAccount or a similar function that returns an AccountResponse. The `trackingId` field in the @@ -167,60 +164,3 @@ func (as *AccountService) CreateAccount(ctx context.Context) (*api.OKResponse, e } return &okResponse, nil } - -func (tas *TestAccountService) CreateAccount(ctx context.Context) (*api.OKResponse, error) { - return &api.OKResponse{ - Ok: true, - Description: "Account creation request received successfully", - Result: map[string]any{"publicKey": "0x48ADca309b5085852207FAaf2816eD72B52F527C", "trackingId": "28ebe84d-b925-472c-87ae-bbdfa1fb97be"}, - }, nil - -} - -func (tas *TestAccountService) CheckBalance(ctx context.Context, publicKey string) (*models.BalanceResponse, error) { - balanceResponse := &models.BalanceResponse{ - Ok: true, - Result: struct { - Balance string `json:"balance"` - Nonce json.Number `json:"nonce"` - }{ - Balance: "0.003 CELO", - Nonce: json.Number("0"), - }, - } - return balanceResponse, nil -} - -func (tas *TestAccountService) TrackAccountStatus(ctx context.Context, publicKey string) (*api.OKResponse, error) { - return &api.OKResponse{ - Ok: true, - Description: "Account creation succeeded", - Result: map[string]any{ - "active": true, - }, - }, nil -} - -func (tas *TestAccountService) CheckAccountStatus(ctx context.Context, trackingId string) (*models.TrackStatusResponse, error) { - trackResponse := &models.TrackStatusResponse{ - Ok: true, - Result: struct { - Transaction struct { - CreatedAt time.Time "json:\"createdAt\"" - Status string "json:\"status\"" - TransferValue json.Number "json:\"transferValue\"" - TxHash string "json:\"txHash\"" - TxType string "json:\"txType\"" - } - }{ - Transaction: models.Transaction{ - CreatedAt: time.Now(), - Status: "SUCCESS", - TransferValue: json.Number("0.5"), - TxHash: "0x123abc456def", - TxType: "transfer", - }, - }, - } - return trackResponse, nil -} From 3792bfdc1f0250122d77b13001ef03f84d2cc996 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 25 Oct 2024 09:38:09 +0300 Subject: [PATCH 20/21] run mod tidy --- go.mod | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index 7112503..0b30354 100644 --- a/go.mod +++ b/go.mod @@ -7,19 +7,17 @@ toolchain go1.23.2 require ( git.defalsify.org/vise.git v0.2.1-0.20241017112704-307fa6fcdc6b github.com/alecthomas/assert/v2 v2.2.2 + github.com/grassrootseconomics/eth-custodial v1.3.0-beta github.com/peteole/testdata-loader v0.3.0 gopkg.in/leonelquinteros/gotext.v1 v1.3.1 - ) -require github.com/joho/godotenv v1.5.1 - require ( - github.com/grassrootseconomics/eth-custodial v1.3.0-beta github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgx/v5 v5.7.1 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/joho/godotenv v1.5.1 github.com/kr/text v0.2.0 // indirect github.com/rogpeppe/go-internal v1.13.1 // indirect golang.org/x/crypto v0.27.0 // indirect @@ -42,7 +40,4 @@ require ( github.com/stretchr/testify v1.9.0 github.com/x448/float16 v0.8.4 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - ) - - From 4e1b2d5ddb13e6cec13bc82515c53df72670c79b Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 25 Oct 2024 18:01:52 +0300 Subject: [PATCH 21/21] update account services --- internal/handlers/server/accountservice.go | 86 ------------------- .../testservice/TestAccountService.go | 28 ++++++ 2 files changed, 28 insertions(+), 86 deletions(-) diff --git a/internal/handlers/server/accountservice.go b/internal/handlers/server/accountservice.go index 8ef909d..890d1db 100644 --- a/internal/handlers/server/accountservice.go +++ b/internal/handlers/server/accountservice.go @@ -8,7 +8,6 @@ import ( "io" "net/http" "os" - "time" "git.grassecon.net/urdt/ussd/config" "git.grassecon.net/urdt/ussd/internal/models" @@ -184,88 +183,3 @@ func (as *AccountService) FetchVouchers(ctx context.Context, publicKey string) ( } return &holdings, nil } - -func (tas *TestAccountService) CreateAccount(ctx context.Context) (*api.OKResponse, error) { - return &api.OKResponse{ - Ok: true, - Description: "Account creation request received successfully", - Result: map[string]any{"publicKey": "0x48ADca309b5085852207FAaf2816eD72B52F527C", "trackingId": "28ebe84d-b925-472c-87ae-bbdfa1fb97be"}, - }, nil - -} - -func (tas *TestAccountService) CheckBalance(ctx context.Context, publicKey string) (*models.BalanceResponse, error) { - balanceResponse := &models.BalanceResponse{ - Ok: true, - Result: struct { - Balance string `json:"balance"` - Nonce json.Number `json:"nonce"` - }{ - Balance: "0.003 CELO", - Nonce: json.Number("0"), - }, - } - return balanceResponse, nil -} - -func (tas *TestAccountService) TrackAccountStatus(ctx context.Context, publicKey string) (*api.OKResponse, error) { - return &api.OKResponse{ - Ok: true, - Description: "Account creation succeeded", - Result: map[string]any{ - "active": true, - }, - }, nil -} - -func (tas *TestAccountService) CheckAccountStatus(ctx context.Context, trackingId string) (*models.TrackStatusResponse, error) { - trackResponse := &models.TrackStatusResponse{ - Ok: true, - Result: struct { - Transaction struct { - CreatedAt time.Time "json:\"createdAt\"" - Status string "json:\"status\"" - TransferValue json.Number "json:\"transferValue\"" - TxHash string "json:\"txHash\"" - TxType string "json:\"txType\"" - } - }{ - Transaction: models.Transaction{ - CreatedAt: time.Now(), - Status: "SUCCESS", - TransferValue: json.Number("0.5"), - TxHash: "0x123abc456def", - TxType: "transfer", - }, - }, - } - return trackResponse, nil -} - -func (tas *TestAccountService) FetchVouchers(ctx context.Context, publicKey string) (*models.VoucherHoldingResponse, error) { - return &models.VoucherHoldingResponse{ - Ok: true, - Result: struct { - Holdings []struct { - ContractAddress string `json:"contractAddress"` - TokenSymbol string `json:"tokenSymbol"` - TokenDecimals string `json:"tokenDecimals"` - Balance string `json:"balance"` - } `json:"holdings"` - }{ - Holdings: []struct { - ContractAddress string `json:"contractAddress"` - TokenSymbol string `json:"tokenSymbol"` - TokenDecimals string `json:"tokenDecimals"` - Balance string `json:"balance"` - }{ - { - ContractAddress: "0x6CC75A06ac72eB4Db2eE22F781F5D100d8ec03ee", - TokenSymbol: "SRF", - TokenDecimals: "6", - Balance: "2745987", - }, - }, - }, - }, nil -} diff --git a/internal/testutil/testservice/TestAccountService.go b/internal/testutil/testservice/TestAccountService.go index 81f66ef..6332345 100644 --- a/internal/testutil/testservice/TestAccountService.go +++ b/internal/testutil/testservice/TestAccountService.go @@ -71,3 +71,31 @@ func (tas *TestAccountService) TrackAccountStatus(ctx context.Context, publicKey }, }, nil } + +func (tas *TestAccountService) FetchVouchers(ctx context.Context, publicKey string) (*models.VoucherHoldingResponse, error) { + return &models.VoucherHoldingResponse{ + Ok: true, + Result: struct { + Holdings []struct { + ContractAddress string `json:"contractAddress"` + TokenSymbol string `json:"tokenSymbol"` + TokenDecimals string `json:"tokenDecimals"` + Balance string `json:"balance"` + } `json:"holdings"` + }{ + Holdings: []struct { + ContractAddress string `json:"contractAddress"` + TokenSymbol string `json:"tokenSymbol"` + TokenDecimals string `json:"tokenDecimals"` + Balance string `json:"balance"` + }{ + { + ContractAddress: "0x6CC75A06ac72eB4Db2eE22F781F5D100d8ec03ee", + TokenSymbol: "SRF", + TokenDecimals: "6", + Balance: "2745987", + }, + }, + }, + }, nil +}