I am testing a piece of code, called Compile
:
// Compile takes in code, and returns JSON
// bytes and an error if there was one
func Compile(in string) ([]byte, error) {
// iterate through every line in the code
for _, line := range strings.Split(in, "
") {
// Divide the line into sections
// for easier processing
tokens := strings.Split(line, " ")
for _, a := range availableExpressions {
for _, b := range availableStatements {
if tokens[1] == b {
// It is an expression, so
// calculate the value of
// the expression
var val int
num1, err := strconv.Atoi(tokens[0])
if err != nil {
return nil, err
}
num2, err := strconv.Atoi(tokens[1])
if err != nil {
return nil, err
}
args := []int{num1, num2}
switch b {
case "+":
val = args[0] + args[1]
case "*":
val = args[0] * args[1]
case "-":
val = args[0] - args[1]
case "/":
val = args[0] / args[1]
}
cmd := &Mixed{
isExpression: true,
isStatement: false,
Value: &Expression{
Name: b,
// for some reason go doesn't
// let me put args directly
Arguments: []interface{}{args},
Value: val,
}}
fmt.Println(cmd.Value)
commands = append(commands, cmd)
} else if tokens[0] == a {
// argument is a statement, don't bother
// to evaluate the value
arguments := strings.Join(tokens[1:], " ")
cmd := &Mixed{
isStatement: true,
isExpression: false,
Value: &Statement{
Name: a,
Arguments: []interface{}{arguments},
}}
fmt.Println(cmd.Value)
commands = append(commands, cmd)
}
}
}
}
gen, err := json.Marshal(commands)
// fmt prints an empty slice
// no matter what is in
fmt.Println(commands)
// empty the commands
commands = make([]*Mixed, 0)
if err != nil {
return nil, err
}
return gen, nil
}
But when running the test:
$ cat compile_test.go
package main
import "fmt"
import "testing"
func TestCompile(t *testing.T) {
cases := []struct {
in string
out string
}{
{
in: "print \"Hello World\"",
out: "[{\"Name\":\"print\",\"Arguments\":[\"Hello World\"]}]",
},
{
in: "print \"My name is Jack White\"",
out: "[{\"Name\":\"print\",\"Arguments\":[\"My name is Jack White\"]}]",
},
}
real_stuff, err := Compile(cases[0].in)
if err != nil {
fmt.Printf("error: %s
", err)
}
if string(real_stuff) != cases[0].out {
fmt.Printf("got %s, expected %s
", string(real_stuff), cases[0].out)
t.Fail()
}
real_stuff, err = Compile(cases[1].in)
if err != nil {
fmt.Printf("error: %s
", err)
}
if string(real_stuff) != cases[1].out {
fmt.Printf("got %s, expected %s
", string(real_stuff), cases[1].out)
t.Fail()
}
}
$ go test
[]
got [], expected [{"Name":"print","Arguments":["Hello World"]}]
[]
got [], expected [{"Name":"print","Arguments":["My name is Jack White"]}]
--- FAIL: TestCompile (0.06s)
Can someone explain why the test fails and why Compile
doesn't work?