all repos

clerk @ 18b35e4

missing tooling for ledger/hledger

clerk/internal/lsp/textdocument_completion_test.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
bump go to 1.27, 1 month ago
1
// TODO:
2
package lsp
3
4
import (
5
	"fmt"
6
	"strings"
7
	"testing"
8
	"time"
9
10
	"go.lsp.dev/protocol"
11
	"go.lsp.dev/uri"
12
13
	"olexsmir.xyz/clerk/internal/lsp/lsputil"
14
	"olexsmir.xyz/clerk/internal/testutil/golden"
15
	"olexsmir.xyz/clerk/journal"
16
)
17
18
func TestDetectCompletion_NoJournal(t *testing.T) {
19
	// detection must not depend on a parse
20
	i := strings.Index("    no^te foo\n", "^")
21
	content := "    note foo\n"
22
	ctx, _ := detectCompletionCtx(content, i)
23
	if ctx != cmplAccount {
24
		t.Errorf("ctx = %v, want account", ctx)
25
	}
26
}
27
28
func TestDateStyle(t *testing.T) {
29
	tests := map[string]struct {
30
		history []string
31
		sep     byte
32
		hasYear bool
33
	}{
34
		"empty":    {nil, '-', true},
35
		"dash":     {[]string{"2024-01-02"}, '-', true},
36
		"slash":    {[]string{"2024/01/20"}, '/', true},
37
		"yearless": {[]string{"6-10"}, '-', false},
38
	}
39
	for name, tt := range tests {
40
		t.Run(name, func(t *testing.T) {
41
			sep, hasYear := dateStyle(tt.history)
42
			if sep != tt.sep || hasYear != tt.hasYear {
43
				t.Errorf("dateStyle = %q/%v, want %q/%v", sep, hasYear, tt.sep, tt.hasYear)
44
			}
45
		})
46
	}
47
}
48
49
func TestDateTokenEnd(t *testing.T) {
50
	tests := map[string]struct {
51
		content string
52
		start   int
53
		want    int
54
	}{
55
		"full date":            {"2024-01-02 x", 0, 10},
56
		"unpadded":             {"2024/1/2 x", 0, 8},
57
		"yearless":             {"6-10 x", 0, 4},
58
		"stops at =":           {"2024-01-02=2024-01-03", 0, 10},
59
		"stops at comment":     {"2024-01-02;x", 0, 10},
60
		"partial trailing sep": {"2024- x", 0, 5},
61
		"partial mid":          {"2024-0 x", 0, 6},
62
	}
63
	for name, tt := range tests {
64
		t.Run(name, func(t *testing.T) {
65
			if got := dateTokenEnd(tt.content, tt.start); got != tt.want {
66
				t.Errorf("dateTokenEnd = %d, want %d", got, tt.want)
67
			}
68
		})
69
	}
70
}
71
72
func TestDatePatternMatch(t *testing.T) {
73
	tests := map[string]struct {
74
		pattern, canonical string
75
		want               bool
76
	}{
77
		"digit subsequence":   {"2024-01-0", "2024-01-05", true},
78
		"same sep":            {"2024/0", "2024/01/20", true},
79
		"other sep rejected":  {"2024/0", "2024-01-20", false},
80
		"yearless":            {"6-10", "6-10", true},
81
		"yearless padded rej": {"06-10", "6-10", false},
82
		"no match":            {"2025", "2024-01-20", false},
83
		"empty":               {"", "2024-01-20", true},
84
	}
85
	for name, tt := range tests {
86
		t.Run(name, func(t *testing.T) {
87
			if got := datePatternMatch(tt.pattern, tt.canonical); got != tt.want {
88
				t.Errorf("datePatternMatch = %v, want %v", got, tt.want)
89
			}
90
		})
91
	}
92
}
93
94
func TestGolden_Completion(t *testing.T) {
95
	for _, tt := range []string{"completion-contexts", "completion-journal", "completion-no-transactions"} {
96
		t.Run(tt, func(t *testing.T) {
97
			ar := golden.Read(t, tt)
98
			h := newTxtarHarness(t, ar)
99
			h.srv.applySettings([]byte(`{"latin_to_cyrillic_completion": true}`))
100
101
			var b strings.Builder
102
			for i, c := range h.cursors {
103
				tdp := h.textDocumentPosition(i)
104
				res, err := h.srv.Completion(t.Context(), &protocol.CompletionParams{
105
					TextDocumentPositionParams: tdp,
106
				})
107
				if err != nil {
108
					t.Fatal(err)
109
				}
110
				ctx, start := detectCompletionCtx(h.content, c)
111
				fmt.Fprintf(&b, "%d:%d %s %q\n", tdp.Position.Line, tdp.Position.Character, ctx, h.content[start:c])
112
				list, ok := res.(*protocol.CompletionList)
113
				if !ok {
114
					t.Fatalf("Completion returned %T, want *protocol.CompletionList", res)
115
				}
116
				now := time.Now()
117
				var sep byte
118
				var hasYear bool
119
				if ctx == cmplDate {
120
					if an := h.srv.analysisFor(h.uri); an != nil {
121
						sep, hasYear = dateStyle(an.DateStrings)
122
					}
123
				}
124
				for _, item := range list.Items {
125
					label := item.Label
126
					if ctx == cmplDate {
127
						switch label {
128
						case renderDate(now, sep, hasYear):
129
							label = "today"
130
						case renderDate(now.AddDate(0, 0, -1), sep, hasYear):
131
							label = "yesterday"
132
						case renderDate(now.AddDate(0, 0, -2), sep, hasYear):
133
							label = "2 days ago"
134
						}
135
					}
136
					fmt.Fprintf(&b, "  %s\n", label)
137
				}
138
			}
139
			golden.Assert(t, ar, b.String())
140
		})
141
	}
142
}
143
144
func (c cmplCtx) String() string {
145
	switch c {
146
	case cmplNone:
147
		return "none"
148
	case cmplAccount:
149
		return "account"
150
	case cmplPayee:
151
		return "payee"
152
	case cmplCommodity:
153
		return "commodity"
154
	case cmplTagName:
155
		return "tag"
156
	case cmplTagValue:
157
		return "tag-value"
158
	case cmplDate:
159
		return "date"
160
	case cmplDirective:
161
		return "directive"
162
	default:
163
		return "?"
164
	}
165
}
166
167
func BenchmarkCompletion(b *testing.B) {
168
	path := "../../journal/testdata/journals/actual-1ktxns-100accts.journal"
169
	rj, err := journal.NewLoader().Resolve(path)
170
	if err != nil {
171
		b.Fatal(err)
172
	}
173
	content := string(rj.Occurrences[0].Src)
174
175
	srv := NewServer("test")
176
	srv.server.openDoc(uri.URI("file:///test.journal"), content, 1, "journal")
177
	srv.server.analysisFor(uri.URI("file:///test.journal")) // warm the per-doc cache
178
179
	for tname, tt := range map[string]int{
180
		"1k txns, account":        strings.Index(content, "\n  1:2:3 ") + len("\n  ") + 2,
181
		"1k txns, empty payee":    strings.Index(content, "transaction 1") + len("transaction "),
182
		"1k txns, commodity":      strings.Index(content, "2 B @@") + len("2 B"),
183
		"1k txns, date":           strings.Index(content, "2000-01-0") + len("2000-01-0"),
184
		"1k txns, price date":     strings.Index(content, "P 2000-01-0") + len("P 2000-01-0"),
185
		"1k txns, price quantity": strings.Index(content, "P 2000-01-01 A  0.70") + len("P 2000-01-01 A  0.70"),
186
	} {
187
		b.Run(tname, func(b *testing.B) {
188
			line, col := lsputil.LineCol(content, tt)
189
			params := &protocol.CompletionParams{
190
				TextDocument: protocol.TextDocumentIdentifier{URI: uri.URI("file:///test.journal")},
191
				Position:     protocol.Position{Line: uint32(line), Character: uint32(col)},
192
			}
193
194
			// warm up
195
			if _, err := srv.server.Completion(b.Context(), params); err != nil {
196
				b.Fatal(err)
197
			}
198
			b.ReportAllocs()
199
			b.ResetTimer()
200
			for b.Loop() {
201
				if _, err := srv.server.Completion(b.Context(), params); err != nil {
202
					b.Fatal(err)
203
				}
204
			}
205
			// guard: line-local lexing must stay far below the old whole-file
206
			// relex (~3ms on this file); the measured target is sub-ms
207
			if avg := b.Elapsed() / time.Duration(b.N); avg > 2*time.Millisecond {
208
				b.Fatalf("completion %v/op: whole-file relex regression", avg)
209
			}
210
		})
211
	}
212
}
213
214
func BenchmarkCompletionTransliteration(b *testing.B) {
215
	tails := []string{"а", "б", "в", "г", "д", "е", "є", "ж", "з", "и", "і", "ї", "й", "к", "л", "м", "н", "о", "п", "р"}
216
	var sb strings.Builder
217
	for _, n := range []string{"Витрати", "Доходи", "Активи", "Капітал", "Зобовязання"} {
218
		for _, t := range tails {
219
			fmt.Fprintf(&sb, "account %s:%s%s\n", n, n, t)
220
		}
221
	}
222
	sb.WriteString("account vyt")
223
	content := sb.String()
224
225
	srv := NewServer("test")
226
	srv.server.openDoc(uri.URI("file:///test.journal"), content, 1, "journal")
227
	srv.server.analysisFor(uri.URI("file:///test.journal")) // warm the per-doc cache
228
	srv.server.applySettings([]byte(`{"latin_to_cyrillic_completion": true}`))
229
230
	line, col := lsputil.LineCol(content, len(content))
231
	params := &protocol.CompletionParams{
232
		TextDocument: protocol.TextDocumentIdentifier{URI: uri.URI("file:///test.journal")},
233
		Position:     protocol.Position{Line: uint32(line), Character: uint32(col)},
234
	}
235
236
	warm, err := srv.server.Completion(b.Context(), params)
237
	if err != nil {
238
		b.Fatal(err)
239
	}
240
241
	// Guard: the Cyrillic corpus completes only through the transliterated
242
	// pattern; without it the list collapses to the latin "vyt" placeholder.
243
	if got := len(warm.(*protocol.CompletionList).Items); got <= 1 {
244
		b.Fatalf("transliteration matching did not engage (items: %d)", got)
245
	}
246
247
	b.ReportAllocs()
248
	b.ResetTimer()
249
	for b.Loop() {
250
		if _, err := srv.server.Completion(b.Context(), params); err != nil {
251
			b.Fatal(err)
252
		}
253
	}
254
}