<- Back to shtanton's homepage
aboutsummaryrefslogtreecommitdiff
path: root/subex/main_test.go
blob: 0b4ee1be1a3fdd42d56e8e656b5db06b2e1d2431 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package subex

import (
	"main/walk"
	"reflect"
	"strings"
	"testing"
)

func buildTransducer(subex string) Transducer {
	lexer := NewStringRuneReader(subex)
	ast := Parse(lexer)
	transducer := CompileTransducer(ast)
	return transducer
}

func fmtValueList(values []walk.Value) string {
	var builder strings.Builder
	builder.WriteRune('[')
	for i, value := range values {
		if i != 0 {
			builder.WriteString(", ")
		}
		builder.WriteString(value.Debug())
	}
	builder.WriteRune(']')
	return builder.String()
}

func TestSubexMain(t *testing.T) {
	type test struct {
		subex string
		input []walk.Value
		expected []walk.Value
	}

	tests := []test {
		{
			subex: `..+`,
			input: []walk.Value {
				walk.NumberValue(12),
				walk.NumberValue(34),
			},
			expected: []walk.Value {
				walk.NumberValue(46),
			},
		},
		{
			subex: `.`,
			input: []walk.Value {
				walk.MapValue {{
					Key: "a",
					Value: walk.StringValue("b"),
				}},
			},
			expected: []walk.Value {
				walk.MapValue {{
					Key: "a",
					Value: walk.StringValue("b"),
				}},
			},
		},
		{
			subex: `~(.$_(.{-0}))~`,
			input: []walk.Value {
				walk.StringValue("hello"),
			},
			expected: []walk.Value {
				walk.StringValue("ello"),
			},
		},
	}

	for _, test := range tests {
		lexer := NewStringRuneReader(test.subex)
		ast := Parse(lexer)
		transducer := CompileTransducer(ast)
		output, err := RunTransducer(transducer, test.input)

		if err {
			t.Errorf("Subex %q rejected input %v", test.subex, fmtValueList(test.input))
			t.Logf("AST: %v", ast)
			continue
		}

		if !reflect.DeepEqual(output, test.expected) {
			t.Errorf("Subex %q transformed input %s to output %s", test.subex, fmtValueList(test.input), fmtValueList(output))
		}
	}
}