Compare commits

..

10 Commits

12 changed files with 222 additions and 211 deletions

View File

@ -1,60 +0,0 @@
package driver
import (
"encoding/json"
"os"
)
type StepTest struct {
Input string `json:"input"`
ExpectedContent string `json:"expectedContent"`
}
// Group represents a group of steps.
type GroupTest struct {
Name string `json:"name"`
Steps []Step `json:"steps"`
}
// DataGroup represents the overall structure of the JSON.
type DataGroup struct {
Groups []Group `json:"groups"`
}
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) []struct {
Name string
Input string
ExpectedContent string
} {
var tests []struct {
Name string
Input string
ExpectedContent string
}
for _, group := range group.Groups {
for _, step := range group.Steps {
// Create a test case for each group
tests = append(tests, struct {
Name string
Input string
ExpectedContent string
}{
Name: group.Name,
Input: step.Input,
ExpectedContent: step.ExpectedContent,
})
}
}
return tests
}

View File

@ -1,55 +0,0 @@
package driver
import (
"encoding/json"
"log"
"os"
)
type Step struct {
Input string `json:"input"`
ExpectedContent string `json:"expectedContent"`
}
type Group struct {
Name string `json:"name"`
Steps []Step `json:"steps"`
}
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 Map[T any, U any](input []T, fn func(T) U) []U {
result := make([]U, len(input))
for i, v := range input {
result[i] = fn(v)
}
return result
}

111
driver/testdriver.go Normal file
View File

@ -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 := `.*\?.*|.*`
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
}
// 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) {
re, err := regexp.Compile(s.ExpectedContent)
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
}

View File

@ -1,5 +0,0 @@
// +build !online
package engine
const OnlineTestEnabled = false

View File

@ -1,5 +0,0 @@
// +build online
package engine
const OnlineTestEnabled = true

View File

@ -238,56 +238,16 @@ func (h *Handlers) SaveTemporaryPin(ctx context.Context, sym string, input []byt
accountPIN := string(input)
if accountPIN != "0" { // for the 0:Back case
// Validate that the PIN is a 4-digit number
if !isValidPIN(accountPIN) {
res.FlagSet = append(res.FlagSet, flag_incorrect_pin)
return res, nil
}
store := h.userdataStore
err = store.WriteEntry(ctx, sessionId, utils.DATA_TEMPORARY_PIN, []byte(accountPIN))
if err != nil {
return res, err
}
// Validate that the PIN is a 4-digit number
if !isValidPIN(accountPIN) {
res.FlagSet = append(res.FlagSet, flag_incorrect_pin)
return res, nil
}
return res, nil
}
func (h *Handlers) GetVoucherList(ctx context.Context, sym string, input []byte) (resource.Result, error) {
var res resource.Result
vouchers := []string{
"SRF",
"CRF",
"VCF",
"VSAPA",
"FSTMP",
"FSAW",
"PTAQ",
"VCRXT",
"VSGAQ",
"QPWIQQ",
"FSTMP",
"FSAW",
"PTAQ",
"VCRXT",
"VSGAQ",
"QPWIQQ",
"FSTMP",
"FSAW",
"PTAQ",
"VCRXT",
"VSGAQ",
"QPWIQQ",
store := h.userdataStore
err = store.WriteEntry(ctx, sessionId, utils.DATA_TEMPORARY_PIN, []byte(accountPIN))
if err != nil {
return res, err
}
var numberedVouchers []string
for i, voucher := range vouchers {
numberedVouchers = append(numberedVouchers, fmt.Sprintf("%d:%s", i+1, voucher))
}
res.Content = strings.Join(numberedVouchers, "\n")
return res, nil
}

View File

@ -1,10 +1,11 @@
package engine
package testutil
import (
"context"
"fmt"
"os"
"path"
"time"
"git.defalsify.org/vise.git/engine"
"git.defalsify.org/vise.git/logging"
@ -21,12 +22,13 @@ var (
scriptDir = path.Join(baseDir, "services", "registration")
)
func TestEngine(sessionId string) (engine.Engine, func()) {
var accountService server.AccountServiceInterface
func TestEngine(sessionId string) (engine.Engine, func(), chan bool) {
ctx := context.Background()
ctx = context.WithValue(ctx, "SessionId", sessionId)
pfp := path.Join(scriptDir, "pp.csv")
var eventChannel = make(chan bool)
cfg := engine.Config{
Root: "root",
SessionId: sessionId,
@ -77,12 +79,21 @@ func TestEngine(sessionId string) (engine.Engine, func()) {
os.Exit(1)
}
if OnlineTestEnabled {
accountService = &server.AccountService{}
} else {
accountService = &server.MockAccountService{}
switch AccountService.(type) {
case *server.MockAccountService:
go func() {
eventChannel <- false
}()
case *server.AccountService:
go func() {
time.Sleep(5 * time.Second) // Wait for 5 seconds
eventChannel <- true
}()
default:
panic("Unknown account service type")
}
hl, err := lhs.GetHandler(accountService)
hl, err := lhs.GetHandler(AccountService)
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
os.Exit(1)
@ -90,7 +101,6 @@ func TestEngine(sessionId string) (engine.Engine, func()) {
en := lhs.GetEngine()
en = en.WithFirst(hl.Init)
cleanFn := func() {
err := en.Finish()
if err != nil {
@ -105,5 +115,5 @@ func TestEngine(sessionId string) (engine.Engine, func()) {
}
//en = en.WithDebug(nil)
return en, cleanFn
return en, cleanFn, eventChannel
}

View File

@ -0,0 +1,13 @@
// +build !online
package testutil
import (
"git.grassecon.net/urdt/ussd/internal/handlers/server"
)
var AccountService server.AccountServiceInterface
func init() {
AccountService = &server.MockAccountService{}
}

View File

@ -0,0 +1,12 @@
//go:build online
// +build online
package testutil
import "git.grassecon.net/urdt/ussd/internal/handlers/server"
var AccountService server.AccountServiceInterface
func init() {
AccountService = &server.AccountService{}
}

View File

@ -18,4 +18,4 @@ INCMP select_gender 3
INCMP enter_yob 4
INCMP enter_location 5
INCMP enter_offerings 6
INCMP view_profile 7
INCMP view_profile 7

View File

@ -8,7 +8,7 @@ MOUT help 4
MOUT quit 9
HALT
INCMP send 1
INCMP my_vouchers 2
INCMP quit 2
INCMP my_account 3
INCMP help 4
INCMP quit 9

View File

@ -8,10 +8,9 @@ import (
"os"
"regexp"
"testing"
"time"
"git.grassecon.net/urdt/ussd/driver"
enginetest "git.grassecon.net/urdt/ussd/engine"
"git.grassecon.net/urdt/ussd/internal/testutil"
"github.com/gofrs/uuid"
)
@ -55,7 +54,7 @@ func TestMain(m *testing.M) {
}
func TestAccountCreationSuccessful(t *testing.T) {
en, fn := enginetest.TestEngine(sessionID)
en, fn, eventChannel := testutil.TestEngine(sessionID)
defer fn()
ctx := context.Background()
sessions := testData
@ -76,14 +75,18 @@ func TestAccountCreationSuccessful(t *testing.T) {
t.Fatalf("Test case '%s' failed during Flush: %v", group.Name, err)
}
b := w.Bytes()
if !bytes.Equal(b, []byte(step.ExpectedContent)) {
match, err := step.MatchesExpectedContent(b)
if err != nil {
t.Fatalf("Error compiling regex for step '%s': %v", step.Input, err)
}
if !match {
t.Fatalf("expected:\n\t%s\ngot:\n\t%s\n", step.ExpectedContent, b)
}
}
}
}
// Adding a sleep after the test to wait for registration to complete the process
time.Sleep(5 * time.Second)
<-eventChannel
}
func TestAccountRegistrationRejectTerms(t *testing.T) {
@ -94,7 +97,7 @@ func TestAccountRegistrationRejectTerms(t *testing.T) {
t.Fail()
}
edgeCaseSessionID := v.String()
en, fn := enginetest.TestEngine(edgeCaseSessionID)
en, fn, _ := testutil.TestEngine(edgeCaseSessionID)
defer fn()
ctx := context.Background()
sessions := testData
@ -116,7 +119,11 @@ func TestAccountRegistrationRejectTerms(t *testing.T) {
}
b := w.Bytes()
if !bytes.Equal(b, []byte(step.ExpectedContent)) {
match, err := step.MatchesExpectedContent(b)
if err != nil {
t.Fatalf("Error compiling regex for step '%s': %v", step.Input, err)
}
if !match {
t.Fatalf("expected:\n\t%s\ngot:\n\t%s\n", step.ExpectedContent, b)
}
}
@ -125,7 +132,7 @@ func TestAccountRegistrationRejectTerms(t *testing.T) {
}
func TestSendWithInvalidInputs(t *testing.T) {
en, fn := enginetest.TestEngine(sessionID)
en, fn, _ := testutil.TestEngine(sessionID)
defer fn()
ctx := context.Background()
sessions := testData
@ -153,8 +160,11 @@ func TestSendWithInvalidInputs(t *testing.T) {
// Replace placeholder {public_key} with the actual dynamic public key
expectedContent := bytes.Replace([]byte(step.ExpectedContent), []byte("{public_key}"), []byte(publicKey), -1)
if !bytes.Equal(b, expectedContent) {
match, err := step.MatchesExpectedContent(b)
if err != nil {
t.Fatalf("Error compiling regex for step '%s': %v", step.Input, err)
}
if !match {
t.Fatalf("expected:\n\t%s\ngot:\n\t%s\n", expectedContent, b)
}
}
@ -163,7 +173,7 @@ func TestSendWithInvalidInputs(t *testing.T) {
}
func TestMyAccount_Check_My_Balance(t *testing.T) {
en, fn := enginetest.TestEngine(sessionID)
en, fn, _ := testutil.TestEngine(sessionID)
defer fn()
ctx := context.Background()
sessions := testData
@ -185,7 +195,11 @@ func TestMyAccount_Check_My_Balance(t *testing.T) {
t.Errorf("Test case '%s' failed during Flush: %v", group.Name, err)
}
b := w.Bytes()
if !bytes.Equal(b, []byte(step.ExpectedContent)) {
match, err := step.MatchesExpectedContent(b)
if err != nil {
t.Fatalf("Error compiling regex for step '%s': %v", step.Input, err)
}
if !match {
t.Fatalf("expected:\n\t%s\ngot:\n\t%s\n", step.ExpectedContent, b)
}
}
@ -194,7 +208,7 @@ func TestMyAccount_Check_My_Balance(t *testing.T) {
}
func TestMainMenuHelp(t *testing.T) {
en, fn := enginetest.TestEngine(sessionID)
en, fn, _ := testutil.TestEngine(sessionID)
defer fn()
ctx := context.Background()
sessions := testData
@ -216,7 +230,11 @@ func TestMainMenuHelp(t *testing.T) {
}
b := w.Bytes()
if !bytes.Equal(b, []byte(step.ExpectedContent)) {
match, err := step.MatchesExpectedContent(b)
if err != nil {
t.Fatalf("Error compiling regex for step '%s': %v", step.Input, err)
}
if !match {
t.Fatalf("expected:\n\t%s\ngot:\n\t%s\n", step.ExpectedContent, b)
}
}
@ -225,7 +243,7 @@ func TestMainMenuHelp(t *testing.T) {
}
func TestMainMenuQuit(t *testing.T) {
en, fn := enginetest.TestEngine(sessionID)
en, fn, _ := testutil.TestEngine(sessionID)
defer fn()
ctx := context.Background()
sessions := testData
@ -247,7 +265,11 @@ func TestMainMenuQuit(t *testing.T) {
}
b := w.Bytes()
if !bytes.Equal(b, []byte(step.ExpectedContent)) {
match, err := step.MatchesExpectedContent(b)
if err != nil {
t.Fatalf("Error compiling regex for step '%s': %v", step.Input, err)
}
if !match {
t.Fatalf("expected:\n\t%s\ngot:\n\t%s\n", step.ExpectedContent, b)
}
}
@ -256,7 +278,7 @@ func TestMainMenuQuit(t *testing.T) {
}
func TestMyAccount_Check_Community_Balance(t *testing.T) {
en, fn := enginetest.TestEngine(sessionID)
en, fn, _ := testutil.TestEngine(sessionID)
defer fn()
ctx := context.Background()
sessions := testData
@ -278,7 +300,11 @@ func TestMyAccount_Check_Community_Balance(t *testing.T) {
t.Errorf("Test case '%s' failed during Flush: %v", group.Name, err)
}
b := w.Bytes()
if !bytes.Equal(b, []byte(step.ExpectedContent)) {
match, err := step.MatchesExpectedContent(b)
if err != nil {
t.Fatalf("Error compiling regex for step '%s': %v", step.Input, err)
}
if !match {
t.Fatalf("expected:\n\t%s\ngot:\n\t%s\n", step.ExpectedContent, b)
}
}
@ -286,10 +312,8 @@ func TestMyAccount_Check_Community_Balance(t *testing.T) {
}
}
func TestMyAccount_MyAddress(t *testing.T) {
en, fn := enginetest.TestEngine(sessionID)
en, fn, _ := testutil.TestEngine(sessionID)
defer fn()
ctx := context.Background()
sessions := testData
@ -313,10 +337,12 @@ func TestMyAccount_MyAddress(t *testing.T) {
b := w.Bytes()
publicKey := extractPublicKey(b)
expectedContent := bytes.Replace([]byte(step.ExpectedContent), []byte("{public_key}"), []byte(publicKey), -1)
if !bytes.Equal(b, expectedContent) {
match, err := step.MatchesExpectedContent(b)
if err != nil {
t.Fatalf("Error compiling regex for step '%s': %v", step.Input, err)
}
if !match {
t.Fatalf("expected:\n\t%s\ngot:\n\t%s\n", expectedContent, b)
}
}
@ -329,7 +355,7 @@ func TestGroups(t *testing.T) {
if err != nil {
log.Fatalf("Failed to load test groups: %v", err)
}
en, fn := enginetest.TestEngine(sessionID)
en, fn, _ := testutil.TestEngine(sessionID)
defer fn()
ctx := context.Background()
// Create test cases from loaded groups
@ -349,7 +375,11 @@ func TestGroups(t *testing.T) {
t.Errorf("Test case '%s' failed during Flush: %v", tt.Name, err)
}
b := w.Bytes()
if !bytes.Equal(b, []byte(tt.ExpectedContent)) {
match, err := tt.MatchesExpectedContent(b)
if err != nil {
t.Fatalf("Error compiling regex for step '%s': %v", tt.Input, err)
}
if !match {
t.Fatalf("expected:\n\t%s\ngot:\n\t%s\n", tt.ExpectedContent, b)
}