|
5 | 5 | "io/ioutil"
|
6 | 6 | "os"
|
7 | 7 | "path/filepath"
|
| 8 | + "strconv" |
8 | 9 | "strings"
|
9 | 10 | "testing"
|
10 | 11 |
|
@@ -79,6 +80,11 @@ func TestLexers(t *testing.T) {
|
79 | 80 | assert.NoError(t, err)
|
80 | 81 |
|
81 | 82 | for _, file := range files {
|
| 83 | + // skip text analysis test files |
| 84 | + if file.Name() == "analysis" { |
| 85 | + continue |
| 86 | + } |
| 87 | + |
82 | 88 | if file.IsDir() {
|
83 | 89 | dirname := filepath.Join("testdata", file.Name())
|
84 | 90 | lexer := lexers.Get(file.Name())
|
@@ -117,3 +123,52 @@ func TestLexers(t *testing.T) {
|
117 | 123 | }
|
118 | 124 | }
|
119 | 125 | }
|
| 126 | + |
| 127 | +func FileTestAnalysis(t *testing.T, lexer chroma.Lexer, actualFilepath, expectedFilepath string) { |
| 128 | + t.Helper() |
| 129 | + t.Run(lexer.Config().Name+"/"+actualFilepath, func(t *testing.T) { |
| 130 | + expectedData, err := ioutil.ReadFile(expectedFilepath) |
| 131 | + assert.NoError(t, err) |
| 132 | + |
| 133 | + analyser, ok := lexer.(chroma.Analyser) |
| 134 | + assert.True(t, ok, "lexer %q does not set analyser", lexer.Config().Name) |
| 135 | + |
| 136 | + data, err := ioutil.ReadFile(actualFilepath) |
| 137 | + assert.NoError(t, err) |
| 138 | + |
| 139 | + actual := analyser.AnalyseText(string(data)) |
| 140 | + |
| 141 | + if os.Getenv("RECORD") == "true" { |
| 142 | + // Update the expected file with the generated output of this lexer |
| 143 | + f, err := os.Create(expectedFilepath) |
| 144 | + defer f.Close() // nolint: gosec |
| 145 | + assert.NoError(t, err) |
| 146 | + |
| 147 | + _, err = f.WriteString(strconv.FormatFloat(float64(actual), 'f', -1, 32)) |
| 148 | + assert.NoError(t, err) |
| 149 | + } else { |
| 150 | + expected, err := strconv.ParseFloat(strings.TrimSpace(string(expectedData)), 32) |
| 151 | + assert.NoError(t, err) |
| 152 | + |
| 153 | + assert.Equal(t, float32(expected), actual) |
| 154 | + } |
| 155 | + }) |
| 156 | +} |
| 157 | + |
| 158 | +func TestLexersTextAnalyser(t *testing.T) { |
| 159 | + files, err := filepath.Glob("testdata/analysis/*.actual") |
| 160 | + assert.NoError(t, err) |
| 161 | + |
| 162 | + for _, actualFilepath := range files { |
| 163 | + filename := filepath.Base(actualFilepath) |
| 164 | + baseFilename := strings.TrimSuffix(filename, filepath.Ext(filename)) |
| 165 | + lexerName := strings.Split(baseFilename, ".")[0] |
| 166 | + |
| 167 | + lexer := lexers.Get(lexerName) |
| 168 | + assert.NotNil(t, lexer, "no lexer found for name %q", lexerName) |
| 169 | + |
| 170 | + expectedFilepath := "testdata/analysis/" + baseFilename + ".expected" |
| 171 | + |
| 172 | + FileTestAnalysis(t, lexer, actualFilepath, expectedFilepath) |
| 173 | + } |
| 174 | +} |
0 commit comments