Files
godb/tests/main_test.go
T

123 lines
3.0 KiB
Go

package tests
import (
"bufio"
"fmt"
"io"
"os/exec"
"slices"
"strings"
"testing"
)
func runner(commands []string, t *testing.T) []string {
executablePath := "../tmp/godb"
t.Logf("starting godb from %v\n", executablePath)
executable := exec.Command(executablePath)
results := make([]string, 0)
stdin, err := executable.StdinPipe()
if err != nil {
t.Errorf("Failed to create stdin %q\n", err)
}
stdout, err := executable.StdoutPipe()
if err != nil {
t.Errorf("Failed to create stdout %q\n", err)
}
if err := executable.Start(); err != nil {
t.Errorf("Failed to start executable %q\n", err)
}
go func() {
defer stdin.Close()
for _, c := range commands {
_, err = io.WriteString(stdin, c+"\n")
if err != nil {
t.Errorf("Failed to execute %v because of %q\n", c, err)
break
}
}
}()
reader := bufio.NewReader(stdout)
for {
// fmt.Printf("reading command outputs...\n")
line, err := reader.ReadString('\n')
if line != "" {
formattedline := fmt.Sprintf("%v", strings.Trim(strings.ReplaceAll(line, "\x00", ""), "\n"))
// fmt.Printf("formatting and appending result: %v\n", formattedline)
results = append(results, formattedline)
}
if err != nil {
t.Logf("stoped reading due to %q\n", err)
break
}
}
if err := executable.Wait(); err != nil {
t.Logf("Error occured while waiting for cleanup %q\n", err)
}
return results
}
func TestE2E(t *testing.T) {
tests := []struct {
name string
commands []string
expected []string
}{
{
name: "Test Main Loop",
commands: []string{"insert 1 user1 person1@example.com", "select", ".exit"},
expected: []string{"godb > Executed.", "godb > {1 user1 person1@example.com}", "Executed.", "godb > bye!"},
},
{
name: "Test Maximum Length For Values",
commands: []string{"insert 0 " + strings.Repeat("n", 32) + " " + strings.Repeat("n", 255), ".exit"},
expected: []string{"godb > Executed.", "godb > bye!"},
},
{
name: "Test Over Maximum Length For Values",
commands: []string{"insert 0 " + strings.Repeat("n", 42) + " " + strings.Repeat("n", 275), ".exit"},
expected: []string{"godb > Values for either username or email are too long", "godb > bye!"},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
results := runner(test.commands, t)
for i := range results {
results[i] = strings.ReplaceAll(results[i], "\n", "")
}
if !slices.Equal(test.expected, results) {
t.Errorf("Output Mismatch\nExpected: %v\nGot: %v\n", test.expected, results)
}
})
}
}
func TestTableFull(t *testing.T) {
maxRows := 1400
commands := make([]string, 0)
for i := range maxRows {
c := fmt.Sprintf("insert %d user%d person%d@example.com", i, i, i)
commands = append(commands, c)
}
commands = append(commands, ".exit")
results := runner(commands, t)
if results[1300] != "godb > Error: Table is full" {
t.Errorf("Our Tables max capacity is 1300 rows, but we're able to insert %v\n", len(results))
}
}