aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/ast/test_util.go
blob: b9fe12152bf7bf377fbd2772d1abe07ea6ffec98 (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
91
92
93
94
95
96
97
98
99
100
// Copyright 2017 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package ast

import (
	"bufio"
	"bytes"
	"io/ioutil"
	"path/filepath"
	"strings"
	"testing"
)

type ErrorMatcher struct {
	Data   []byte
	expect []*errorDesc
	got    []*errorDesc
}

type errorDesc struct {
	file    string
	line    int
	col     int
	text    string
	matched bool
}

func NewErrorMatcher(t *testing.T, file string) *ErrorMatcher {
	data, err := ioutil.ReadFile(file)
	if err != nil {
		t.Fatalf("failed to open input file: %v", err)
	}
	var stripped []byte
	var errors []*errorDesc
	s := bufio.NewScanner(bytes.NewReader(data))
	for i := 1; s.Scan(); i++ {
		ln := s.Bytes()
		for {
			pos := bytes.LastIndex(ln, []byte("###"))
			if pos == -1 {
				break
			}
			errors = append(errors, &errorDesc{
				file: filepath.Base(file),
				line: i,
				text: strings.TrimSpace(string(ln[pos+3:])),
			})
			ln = ln[:pos]
		}
		stripped = append(stripped, ln...)
		stripped = append(stripped, '\n')
	}
	if err := s.Err(); err != nil {
		t.Fatalf("failed to scan input file: %v", err)
	}
	return &ErrorMatcher{
		Data:   stripped,
		expect: errors,
	}
}

func (em *ErrorMatcher) ErrorHandler(pos Pos, msg string) {
	em.got = append(em.got, &errorDesc{
		file: pos.File,
		line: pos.Line,
		col:  pos.Col,
		text: msg,
	})
}

func (em *ErrorMatcher) Count() int {
	return len(em.got)
}

func (em *ErrorMatcher) Check(t *testing.T) {
nextErr:
	for _, e := range em.got {
		for _, want := range em.expect {
			if want.matched || want.line != e.line || want.text != e.text {
				continue
			}
			want.matched = true
			continue nextErr
		}
		t.Errorf("unexpected error:\n%v:%v:%v: %v", e.file, e.line, e.col, e.text)
	}
	for _, want := range em.expect {
		if want.matched {
			continue
		}
		t.Errorf("unmatched error:\n%v:%v: %v", want.file, want.line, want.text)
	}
}

func (em *ErrorMatcher) DumpErrors(t *testing.T) {
	for _, e := range em.got {
		t.Logf("%v:%v:%v: %v", e.file, e.line, e.col, e.text)
	}
}