summaryrefslogtreecommitdiff
path: root/internal/plugin/plugin_test.go
blob: d020c310920de1fec63345198a9190b400723efa (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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package plugin

// White-box tests. Package plugin (not plugin_test) so unexported types and
// functions — load, loadDir, Plugin.has, Plugin.callWithBuilder,
// Plugin.callNoReturn — are directly accessible.

import (
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	lua "github.com/yuin/gopher-lua"

	"github.com/shiv/internal/store"
)

// ── helpers ───────────────────────────────────────────────────────────────────

// writeLua writes a Lua script to a temp file and returns its path.
// The file is removed when the test ends.
func writeLua(t *testing.T, src string) string {
	t.Helper()
	f, err := os.CreateTemp("", "shiv-plugin-*.lua")
	require.NoError(t, err)
	_, err = f.WriteString(src)
	require.NoError(t, err)
	require.NoError(t, f.Close())
	t.Cleanup(func() { os.Remove(f.Name()) })
	return f.Name()
}

// newTestStore opens a temp SQLite store for plugin tests.
func newTestStore(t *testing.T) *store.Store {
	t.Helper()
	f, err := os.CreateTemp("", "shiv-plugin-store-*.shiv")
	require.NoError(t, err)
	f.Close()
	t.Cleanup(func() { os.Remove(f.Name()) })
	st, err := store.Open(f.Name())
	require.NoError(t, err)
	t.Cleanup(func() { st.Close() })
	return st
}

// loadPlugin is a convenience wrapper around load that also registers cleanup.
func loadPlugin(t *testing.T, src string, st *store.Store) *Plugin {
	t.Helper()
	path := writeLua(t, src)
	p, err := load(path, st)
	require.NoError(t, err)
	t.Cleanup(func() { p.close() })
	return p
}

// ── load ──────────────────────────────────────────────────────────────────────

func TestLoad_ValidScript_ReturnsPlugin(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `-- empty script`, st)
	assert.NotNil(t, p)
}

func TestLoad_InvalidScript_ReturnsError(t *testing.T) {
	st := newTestStore(t)
	path := writeLua(t, `this is not valid lua %%%`)
	_, err := load(path, st)
	assert.Error(t, err)
}

func TestLoad_NonExistentFile_ReturnsError(t *testing.T) {
	st := newTestStore(t)
	_, err := load("/does/not/exist.lua", st)
	assert.Error(t, err)
}

func TestLoad_CallsOnLoad(t *testing.T) {
	st := newTestStore(t)
	// on_load sets a global that we can check afterwards.
	p := loadPlugin(t, `
		loaded = false
		function on_load()
			loaded = true
		end
	`, st)

	p.mu.Lock()
	v := p.L.GetGlobal("loaded")
	p.mu.Unlock()

	assert.Equal(t, lua.LTrue, v)
}

func TestLoad_OnLoadError_PluginStillLoaded(t *testing.T) {
	st := newTestStore(t)
	// on_load errors are logged but must not prevent the plugin from loading.
	p, err := func() (*Plugin, error) {
		path := writeLua(t, `
			function on_load()
				error("intentional on_load failure")
			end
		`)
		return load(path, st)
	}()
	// load itself should succeed despite on_load failing.
	require.NoError(t, err)
	assert.NotNil(t, p)
	p.close()
}

func TestLoad_SetsName(t *testing.T) {
	st := newTestStore(t)
	path := writeLua(t, `-- empty`)
	p, err := load(path, st)
	require.NoError(t, err)
	defer p.close()
	assert.Equal(t, filepath.Base(path), p.name)
}

// ── has ───────────────────────────────────────────────────────────────────────

func TestHas_DefinedFunction_ReturnsTrue(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `function on_request(r) return r end`, st)
	assert.True(t, p.has("on_request"))
}

func TestHas_UndefinedFunction_ReturnsFalse(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `-- empty`, st)
	assert.False(t, p.has("on_request"))
}

func TestHas_NilGlobal_ReturnsFalse(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `on_request = nil`, st)
	assert.False(t, p.has("on_request"))
}

// ── callNoReturn ──────────────────────────────────────────────────────────────

func TestCallNoReturn_UndefinedFunction_ReturnsNil(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `-- empty`, st)
	err := p.callNoReturn("no_such_fn", lua.LNil)
	assert.NoError(t, err)
}

func TestCallNoReturn_FunctionExecutes(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `
		called = false
		function my_fn()
			called = true
		end
	`, st)

	err := p.callNoReturn("my_fn", lua.LNil)
	require.NoError(t, err)

	p.mu.Lock()
	v := p.L.GetGlobal("called")
	p.mu.Unlock()
	assert.Equal(t, lua.LTrue, v)
}

func TestCallNoReturn_FunctionReceivesArg(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `
		received = nil
		function my_fn(arg)
			received = arg
		end
	`, st)

	p.mu.Lock()
	arg := p.L.NewTable()
	p.L.SetField(arg, "key", lua.LString("value"))
	p.mu.Unlock()

	err := p.callNoReturn("my_fn", arg)
	require.NoError(t, err)

	p.mu.Lock()
	tbl, ok := p.L.GetGlobal("received").(*lua.LTable)
	p.mu.Unlock()
	require.True(t, ok)

	p.mu.Lock()
	v := tbl.RawGetString("key")
	p.mu.Unlock()
	assert.Equal(t, lua.LString("value"), v)
}

func TestCallNoReturn_LuaError_ReturnsError(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `
		function bad_fn()
			error("intentional error")
		end
	`, st)

	err := p.callNoReturn("bad_fn", lua.LNil)
	assert.Error(t, err)
}

func TestCallNoReturn_Timeout_ReturnsError(t *testing.T) {
	st := newTestStore(t)
	// Infinite loop — must be killed by the context timeout.
	p := loadPlugin(t, `
		function infinite()
			while true do end
		end
	`, st)

	start := time.Now()
	err := p.callNoReturn("infinite", lua.LNil)
	elapsed := time.Since(start)

	assert.Error(t, err)
	// Should terminate within a reasonable margin of callTimeout (500ms).
	assert.Less(t, elapsed, callTimeout+300*time.Millisecond)
}

// ── callWithBuilder ───────────────────────────────────────────────────────────

func TestCallWithBuilder_UndefinedFunction_ReturnsNilNoError(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `-- empty`, st)

	ret, err := p.callWithBuilder("no_such_fn", func(L *lua.LState) *lua.LTable {
		return L.NewTable()
	})

	assert.NoError(t, err)
	assert.Nil(t, ret)
}

func TestCallWithBuilder_BuilderRunsUnderLock(t *testing.T) {
	// Verify the builder is called (indirectly — if it panics the test fails).
	st := newTestStore(t)
	p := loadPlugin(t, `function fn(t) return t end`, st)

	builderCalled := false
	ret, err := p.callWithBuilder("fn", func(L *lua.LState) *lua.LTable {
		builderCalled = true
		tbl := L.NewTable()
		L.SetField(tbl, "x", lua.LString("hello"))
		return tbl
	})

	require.NoError(t, err)
	assert.True(t, builderCalled)
	assert.NotNil(t, ret)
}

func TestCallWithBuilder_FunctionCanModifyTable(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `
		function transform(t)
			t.result = "modified"
			return t
		end
	`, st)

	ret, err := p.callWithBuilder("transform", func(L *lua.LState) *lua.LTable {
		tbl := L.NewTable()
		L.SetField(tbl, "result", lua.LString("original"))
		return tbl
	})

	require.NoError(t, err)
	require.NotNil(t, ret)

	p.mu.Lock()
	v := ret.RawGetString("result")
	p.mu.Unlock()
	assert.Equal(t, lua.LString("modified"), v)
}

func TestCallWithBuilder_FunctionReturnsNil_ReturnsNilTable(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `function fn(t) return nil end`, st)

	ret, err := p.callWithBuilder("fn", func(L *lua.LState) *lua.LTable {
		return L.NewTable()
	})

	assert.NoError(t, err)
	assert.Nil(t, ret)
}

func TestCallWithBuilder_LuaError_ReturnsError(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `
		function bad(t)
			error("builder error")
		end
	`, st)

	_, err := p.callWithBuilder("bad", func(L *lua.LState) *lua.LTable {
		return L.NewTable()
	})

	assert.Error(t, err)
}

func TestCallWithBuilder_Timeout_ReturnsError(t *testing.T) {
	st := newTestStore(t)
	p := loadPlugin(t, `
		function slow(t)
			while true do end
		end
	`, st)

	start := time.Now()
	_, err := p.callWithBuilder("slow", func(L *lua.LState) *lua.LTable {
		return L.NewTable()
	})
	elapsed := time.Since(start)

	assert.Error(t, err)
	assert.Less(t, elapsed, callTimeout+300*time.Millisecond)
}

// ── loadDir ───────────────────────────────────────────────────────────────────

func TestLoadDir_NonExistentDir_ReturnsNilSlice(t *testing.T) {
	st := newTestStore(t)
	plugins, err := loadDir("/does/not/exist", st)
	assert.NoError(t, err)
	assert.Nil(t, plugins)
}

func TestLoadDir_EmptyDir_ReturnsEmpty(t *testing.T) {
	st := newTestStore(t)
	dir := t.TempDir()
	plugins, err := loadDir(dir, st)
	assert.NoError(t, err)
	assert.Empty(t, plugins)
}

func TestLoadDir_LoadsLuaFiles(t *testing.T) {
	st := newTestStore(t)
	dir := t.TempDir()

	require.NoError(t, os.WriteFile(filepath.Join(dir, "a.lua"), []byte(`x = 1`), 0644))
	require.NoError(t, os.WriteFile(filepath.Join(dir, "b.lua"), []byte(`y = 2`), 0644))
	require.NoError(t, os.WriteFile(filepath.Join(dir, "readme.txt"), []byte(`not lua`), 0644))

	plugins, err := loadDir(dir, st)
	require.NoError(t, err)
	assert.Len(t, plugins, 2)
	for _, p := range plugins {
		p.close()
	}
}

func TestLoadDir_SkipsDirectories(t *testing.T) {
	st := newTestStore(t)
	dir := t.TempDir()

	require.NoError(t, os.Mkdir(filepath.Join(dir, "subdir.lua"), 0755))
	require.NoError(t, os.WriteFile(filepath.Join(dir, "real.lua"), []byte(`z = 3`), 0644))

	plugins, err := loadDir(dir, st)
	require.NoError(t, err)
	assert.Len(t, plugins, 1)
	for _, p := range plugins {
		p.close()
	}
}

func TestLoadDir_InvalidLuaSkipped_OthersLoaded(t *testing.T) {
	st := newTestStore(t)
	dir := t.TempDir()

	require.NoError(t, os.WriteFile(filepath.Join(dir, "good.lua"), []byte(`g = 1`), 0644))
	require.NoError(t, os.WriteFile(filepath.Join(dir, "bad.lua"), []byte(`%%% invalid`), 0644))

	plugins, err := loadDir(dir, st)
	require.NoError(t, err)
	// bad.lua skipped, good.lua loaded
	assert.Len(t, plugins, 1)
	assert.Equal(t, "good.lua", plugins[0].name)
	for _, p := range plugins {
		p.close()
	}
}