-
Notifications
You must be signed in to change notification settings - Fork 202
/
Copy pathtest_snippets.lua
4827 lines (4118 loc) · 186 KB
/
test_snippets.lua
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local helpers = dofile('tests/helpers.lua')
local child = helpers.new_child_neovim()
local expect, eq, no_eq = helpers.expect, helpers.expect.equality, helpers.expect.no_equality
local eq_partial_tbl = helpers.expect.equality_partial_tbl
local new_set = MiniTest.new_set
-- Helpers with child processes
--stylua: ignore start
local load_module = function(config) child.mini_load('snippets', config) end
local unload_module = function() child.mini_unload('snippets') end
local set_cursor = function(...) return child.set_cursor(...) end
local get_cursor = function(...) return child.get_cursor(...) end
local set_lines = function(...) return child.set_lines(...) end
local get_lines = function(...) return child.get_lines(...) end
local type_keys = function(...) return child.type_keys(...) end
local sleep = function(ms) helpers.sleep(ms, child) end
local new_buf = function() return child.api.nvim_create_buf(true, false) end
local get_buf = function() return child.api.nvim_get_current_buf() end
local set_buf = function(buf_id) child.api.nvim_set_current_buf(buf_id) end
--stylua: ignore end
local test_dir = 'tests/dir-snippets'
local test_dir_absolute = vim.fn.fnamemodify(test_dir, ':p'):gsub('\\', '/'):gsub('(.)/$', '%1')
-- Time constants
local small_time = helpers.get_time_const(10)
-- Tweak `expect_screenshot()` to test only on Neovim>=0.10 (as it has inline
-- extmarks support). Use `child.expect_screenshot_orig()` for original testing.
child.expect_screenshot_orig = child.expect_screenshot
child.expect_screenshot = function(opts)
if child.fn.has('nvim-0.10') == 0 then return end
child.expect_screenshot_orig(opts)
end
-- Common test wrappers
local forward_lua = function(fun_str)
local lua_cmd = fun_str .. '(...)'
return function(...) return child.lua_get(lua_cmd, { ... }) end
end
local get = forward_lua('MiniSnippets.session.get')
local get_all = function() return get(true) end
local jump = forward_lua('MiniSnippets.session.jump')
local stop = forward_lua('MiniSnippets.session.stop')
-- Common helpers
local get_cur_tabstop = function() return (get() or {}).cur_tabstop end
local validate_active_session = function() eq(child.lua_get('MiniSnippets.session.get() ~= nil'), true) end
local validate_no_active_session = function() eq(child.lua_get('MiniSnippets.session.get() ~= nil'), false) end
local validate_n_sessions = function(n) eq(child.lua_get('#MiniSnippets.session.get(true)'), n) end
local validate_pumvisible = function() eq(child.fn.pumvisible(), 1) end
local validate_no_pumvisible = function() eq(child.fn.pumvisible(), 0) end
local validate_pumitems = function(ref)
if #ref == 0 then validate_no_pumvisible() end
if #ref > 0 then validate_pumvisible() end
eq(vim.tbl_map(function(t) return t.word end, child.fn.complete_info().items), ref)
end
local validate_state = function(mode, lines, cursor)
if mode ~= nil then eq(child.fn.mode(), mode) end
if lines ~= nil then eq(get_lines(), lines) end
if cursor ~= nil then eq(get_cursor(), cursor) end
end
local mock_select = function(user_chosen_id)
child.lua('_G.user_chosen_id = ' .. user_chosen_id)
child.lua([[
vim.ui.select = function(items, opts, on_choice)
local format_item = opts.format_item or function(x) return tostring(x) end
_G.select_args = {
items = items,
items_formatted = vim.tbl_map(format_item, items),
prompt = opts.prompt,
kind = opts.kind
}
on_choice(items[_G.user_chosen_id], _G.user_chosen_id)
end
]])
end
local setup_event_log = function()
child.lua([[
local suffixes = { 'Start', 'Stop', 'Suspend', 'Resume', 'JumpPre', 'Jump' }
local au_events = vim.tbl_map(function(s) return 'MiniSnippetsSession' .. s end, suffixes)
_G.au_log = {}
local log_event = function(args)
table.insert(au_log, { buf_id = args.buf, event = args.match, data = args.data })
end
vim.api.nvim_create_autocmd('User', { pattern = au_events, callback = log_event })
]])
end
local get_au_log = function() return child.lua_get('_G.au_log') end
local clean_au_log = function() return child.lua('_G.au_log = {}') end
local get_snippet_body = function(session) return (session or get()).insert_args.snippet.body end
local make_snippet_body = function(body) return { insert_args = { snippet = body } } end
local make_get_extmark = function(session)
local buf_id, ns_id = session.buf_id, session.ns_id
return function(extmark_id)
local data = child.api.nvim_buf_get_extmark_by_id(buf_id, ns_id, extmark_id, { details = true })
data[3].row, data[3].col = data[1], data[2]
return data[3]
end
end
local validate_session_nodes_partial = function(session, ref_nodes)
local get_extmark = make_get_extmark(session)
local nodes = vim.deepcopy(session.nodes)
-- Replace `extmark_id` (should be present in every node) with extmark data
local replace_extmarks
replace_extmarks = function(n_arr)
for _, n in ipairs(n_arr) do
n.extmark = get_extmark(n.extmark_id)
n.extmark_id = nil
if n.placeholder ~= nil then replace_extmarks(n.placeholder) end
end
end
replace_extmarks(nodes)
eq_partial_tbl(nodes, ref_nodes)
end
local ensure_clean_state = function()
child.lua([[while MiniSnippets.session.get() do MiniSnippets.session.stop() end]])
-- while get() do stop() end
child.ensure_normal_mode()
set_lines({})
clean_au_log()
end
local edit = function(path)
child.cmd('edit ' .. child.fn.fnameescape(path))
-- Slow context needs a small delay to get things up to date
if helpers.is_slow() then sleep(small_time) end
end
-- Output test set ============================================================
local T = new_set({
hooks = {
pre_case = function()
child.setup()
child.set_size(8, 40)
set_buf(new_buf())
-- Mock `vim.notify()`
child.lua([[
_G.notify_log = {}
local inverse_levels = {}
for k, v in pairs(vim.log.levels) do
inverse_levels[v] = k
end
vim.notify = function(msg, lvl, opts)
table.insert(_G.notify_log, { msg, inverse_levels[lvl], opts })
end
]])
-- Add helper for easier RPC communication
child.lua([[
_G.sanitize_object = function(x)
if type(x) == 'function' then return 'function' end
if type(x) == 'table' then
local res = {}
for k, v in pairs(x) do
res[k] = _G.sanitize_object(v)
end
return res
end
return x
end
]])
-- Better interaction with built-in completion
child.o.completeopt = 'menuone,noselect'
load_module()
end,
post_once = child.stop,
n_retry = helpers.get_n_retry(2),
},
})
-- Unit tests =================================================================
T['setup()'] = new_set()
T['setup()']['creates side effects'] = function()
-- Global variable
eq(child.lua_get('type(_G.MiniSnippets)'), 'table')
-- Highlight groups
child.cmd('hi clear')
child.cmd('hi DiagnosticUnderlineError guisp=#ff0000 gui=underline cterm=underline')
child.cmd('hi DiagnosticUnderlineWarn guisp=#ffff00 gui=undercurl cterm=undercurl')
child.cmd('hi DiagnosticUnderlineInfo guisp=#0000ff gui=underdotted cterm=underline')
child.cmd('hi DiagnosticUnderlineHint guisp=#00ffff gui=underdashed cterm=underdashed')
child.cmd('hi DiagnosticUnderlineOk guifg=#00ff00 guibg=#000000')
load_module()
local has_highlight = function(group, value) expect.match(child.cmd_capture('hi ' .. group), value) end
has_highlight('MiniSnippetsCurrent', 'gui=underdouble guisp=#ffff00')
has_highlight('MiniSnippetsCurrentReplace', 'gui=underdouble guisp=#ff0000')
has_highlight('MiniSnippetsFinal', 'gui=underdouble')
has_highlight('MiniSnippetsUnvisited', 'gui=underdouble guisp=#00ffff')
has_highlight('MiniSnippetsVisited', 'gui=underdouble guisp=#0000ff')
end
T['setup()']['creates `config` field'] = function()
eq(child.lua_get('type(_G.MiniSnippets.config)'), 'table')
-- Check default values
local expect_config = function(field, value) eq(child.lua_get('MiniSnippets.config.' .. field), value) end
expect_config('snippets', {})
expect_config('mappings.expand', '<C-j>')
expect_config('mappings.jump_next', '<C-l>')
expect_config('mappings.jump_prev', '<C-h>')
expect_config('mappings.stop', '<C-c>')
expect_config('expand', { prepare = nil, match = nil, select = nil, insert = nil })
end
T['setup()']['respects `config` argument'] = function()
unload_module()
load_module({ snippets = { { prefix = 'a', body = 'axa' } } })
eq(child.lua_get('MiniSnippets.config.snippets'), { { prefix = 'a', body = 'axa' } })
end
T['setup()']['validates `config` argument'] = function()
unload_module()
local expect_config_error = function(config, name, target_type)
expect.error(load_module, vim.pesc(name) .. '.*' .. vim.pesc(target_type), config)
end
expect_config_error('a', 'config', 'table')
expect_config_error({ snippets = 1 }, 'snippets', 'table')
expect_config_error({ mappings = 1 }, 'mappings', 'table')
expect_config_error({ mappings = { expand = 1 } }, 'mappings.expand', 'string')
expect_config_error({ mappings = { jump_next = 1 } }, 'mappings.jump_next', 'string')
expect_config_error({ mappings = { jump_prev = 1 } }, 'mappings.jump_prev', 'string')
expect_config_error({ mappings = { stop = 1 } }, 'mappings.stop', 'string')
expect_config_error({ expand = 1 }, 'expand', 'table')
expect_config_error({ expand = { prepare = 1 } }, 'expand.prepare', 'function')
expect_config_error({ expand = { match = 1 } }, 'expand.match', 'function')
expect_config_error({ expand = { select = 1 } }, 'expand.select', 'function')
expect_config_error({ expand = { insert = 1 } }, 'expand.insert', 'function')
end
T['setup()']['ensures colors'] = function()
child.cmd('colorscheme default')
expect.match(child.cmd_capture('hi MiniSnippetsCurrent'), 'gui=underdouble guisp=#')
end
T['setup()']['adds "code-snippets" filetype detection'] = function()
eq(child.lua_get('vim.filetype.match({ filename = "aaa.code-snippets" })'), 'json')
end
-- Test are high-level. Granular testing is done in tests for `default_*()`.
T['expand()'] = new_set({
hooks = {
pre_case = function()
child.lua([[
_G.context_log = {}
MiniSnippets.config.snippets = {
function(context)
table.insert(_G.context_log, context)
return { { prefix = 'ba', body = 'BA=$1 T0=$0' } }
end,
{ { prefix = 'aa', body = 'AA=$1 T0=$0' } },
{ prefix = 'xx', body = 'XX=$1 T0=$0' },
}]])
child.bo.filetype = 'myft'
end,
},
})
local expand = forward_lua('MiniSnippets.expand')
T['expand()']['works with defaults'] = function()
local validate = function()
-- Should expand snippet with 'ba' prefix, because `default_prepare` sorts
-- resolved snippets in prefix's alphabetical order.
mock_select(2)
expand()
eq(child.lua_get('_G.context_log'), { { buf_id = 2, lang = 'myft' } })
eq(child.lua_get('_G.select_args.items_formatted'), { 'aa │ AA=$1 T0=$0', 'ba │ BA=$1 T0=$0' })
validate_active_session()
validate_state('i', { 'BA= T0=' }, { 1, 3 })
child.lua('_G.context_log, _G.select_args = {}, nil')
end
-- Insert mode
type_keys('i', 'a')
validate()
ensure_clean_state()
-- Normal mode
type_keys('i', 'a', '<Esc>')
validate()
end
T['expand()']['implements proper order of steps'] = function()
type_keys('i', 'a')
mock_select(2)
child.lua([[
_G.steps_log = {}
local wrap_with_log = function(step_name, f)
return function(...)
table.insert(_G.steps_log, { step = step_name, args = { ... } })
return f(...)
end
end
local opts = {
prepare = wrap_with_log('prepare', MiniSnippets.default_prepare),
match = wrap_with_log('match', MiniSnippets.default_match),
select = wrap_with_log('select', MiniSnippets.default_select),
insert = wrap_with_log('insert', MiniSnippets.default_insert),
}
MiniSnippets.expand(opts)
]])
local ref_region = { from = { col = 1, line = 1 }, to = { col = 1, line = 1 } }
local ref_steps_log = {
{
-- Should be called with raw config snippets
step = 'prepare',
args = {
{
'function',
{ { prefix = 'aa', body = 'AA=$1 T0=$0' } },
{ prefix = 'xx', body = 'XX=$1 T0=$0' },
},
},
},
{
-- Should be called with normalized snippet array
step = 'match',
args = {
{
{ prefix = 'aa', body = 'AA=$1 T0=$0', desc = 'AA=$1 T0=$0' },
{ prefix = 'ba', body = 'BA=$1 T0=$0', desc = 'BA=$1 T0=$0' },
{ prefix = 'xx', body = 'XX=$1 T0=$0', desc = 'XX=$1 T0=$0' },
},
},
},
{
-- Should be called with matched snippet array and `insert` function
step = 'select',
args = {
{
{ prefix = 'aa', body = 'AA=$1 T0=$0', desc = 'AA=$1 T0=$0', region = ref_region },
{ prefix = 'ba', body = 'BA=$1 T0=$0', desc = 'BA=$1 T0=$0', region = ref_region },
},
'function',
},
},
{
-- Should be called with selected snippet, `region` should be removed
step = 'insert',
args = { { prefix = 'ba', body = 'BA=$1 T0=$0', desc = 'BA=$1 T0=$0' } },
},
}
eq(child.lua_get('_G.sanitize_object(_G.steps_log)'), ref_steps_log)
end
T['expand()']['uses config as default for steps'] = function()
child.lua([[
_G.log = {}
MiniSnippets.config.expand = {
prepare = function(...)
table.insert(_G.log, 'global prepare')
return MiniSnippets.default_prepare(...)
end,
match = function(...)
table.insert(_G.log, 'global match')
return MiniSnippets.default_match(...)
end,
}
vim.b.minisnippets_config = { expand = {
match = function(...)
table.insert(_G.log, 'buffer-local match')
return MiniSnippets.default_match(...)
end,
}}
]])
mock_select(2)
expand()
-- Should prefer buffer-local over global config
eq(child.lua_get('_G.log'), { 'global prepare', 'buffer-local match' })
end
T['expand()']['prepares for `insert` to be executed at cursor in Insert mode'] = function()
child.lua([[
_G.log = {}
MiniSnippets.config.expand.insert = function(...)
local state = {
mode = vim.fn.mode(),
line = vim.api.nvim_get_current_line(),
cursor = vim.api.nvim_win_get_cursor(0),
}
table.insert(_G.log, state)
end]])
local validate = function(keys, ref_line, ref_cursor)
type_keys(1, 'i', keys)
mock_select(1)
expand()
-- Should ensure Insert mode, remove matched region, ensure cursor
eq(child.lua_get('_G.log'), { { mode = 'i', line = ref_line, cursor = ref_cursor } })
child.lua('_G.log = {}')
ensure_clean_state()
end
-- Insert mode (in different line positions)
-- - Should remove matched region
validate({ 'a line start', '<Esc>', '0', 'a' }, ' line start', { 1, 0 })
validate({ 'line a middle', '<Esc>', 'b<Left>', 'i' }, 'line middle', { 1, 5 })
validate({ 'line end a' }, 'line end ', { 1, 9 })
-- - Empty base for matching (no region to remove)
validate({ 'line start', '<Esc>', '0', 'i' }, 'line start', { 1, 0 })
validate({ 'line middle', '<Esc>', 'b', 'i' }, 'line middle', { 1, 5 })
validate({ 'line end ' }, 'line end ', { 1, 9 })
-- Normal mode
validate({ 'a line start', '<Esc>', '0' }, ' line start', { 1, 0 })
validate({ 'line a middle', '<Esc>', 'b<Left><Left>' }, 'line middle', { 1, 5 })
validate({ 'line end a', '<Esc>' }, 'line end ', { 1, 9 })
validate({ ' line start', '<Esc>', '0' }, ' line start', { 1, 0 })
validate({ 'line middle', '<Esc>', 'b', '<Left>' }, 'line middle', { 1, 4 })
validate({ 'line end ', '<Esc>' }, 'line end ', { 1, 8 })
end
T['expand()']['works with `vim.ui.select` which does not restore Insert mode'] = function()
child.lua([[
vim.ui.select = function(items, opts, on_choice)
vim.api.nvim_feedkeys('\27', 'nx', false)
vim.schedule(function() on_choice(items[1]) end)
end
_G.log = {}
MiniSnippets.config.expand.insert = function(...)
local t = { mode = vim.fn.mode(), line = vim.api.nvim_get_current_line(), cursor = vim.api.nvim_win_get_cursor(0)}
table.insert(_G.log, t)
end
]])
local validate = function(keys, ref_line, ref_cursor)
type_keys('i', keys)
expand()
-- Poke eventloop because both ensuring Insert mode from Normal mode and
-- jumping do not happen immediately
child.poke_eventloop()
eq(child.lua_get('_G.log'), { { mode = 'i', line = ref_line, cursor = ref_cursor } })
ensure_clean_state()
child.lua('_G.log = {}')
end
-- With removing region
validate({ 'uu a' }, 'uu ', { 1, 3 })
validate({ 'uu a vv', '<Left><Left><Left>' }, 'uu vv', { 1, 3 })
validate({ 'a vv', '<Left><Left><Left>' }, ' vv', { 1, 0 })
-- Without removing region. Currently doesn't work as ensuring Insert mode
-- moves cursor one cell to the left (as after `<Esc>i`). It works for case
-- with removing region because there is info about where to put cursor.
-- validate({ 'uu ' }, 'uu ', { 1, 3 })
-- validate({ 'u u', '<Left><Left>' }, 'u u', { 1, 2 })
-- validate({ ' u', '<Left>' }, ' u', { 1, 1 })
end
T['expand()']['accepts `false` for some steps'] = function()
-- Use all snippets if `match = false`
type_keys('i', 'a')
-- - Select snippet that is clearly not matched
mock_select(3)
expand({ match = false })
validate_active_session()
-- - No region is removed because there was no match
validate_state('i', { 'aXX= T0=' }, { 1, 4 })
ensure_clean_state()
-- Force best (first) match insert with `select = false`
type_keys('i', 'a')
expand({ select = false })
validate_active_session()
validate_state('i', { 'AA= T0=' }, { 1, 3 })
ensure_clean_state()
-- Return snippets with `insert = false`
type_keys('i', 'a')
-- - Matched snippets by default
local ref_region = { from = { col = 1, line = 1 }, to = { col = 1, line = 1 } }
local ref_matched_snippets = {
{ prefix = 'aa', body = 'AA=$1 T0=$0', desc = 'AA=$1 T0=$0', region = ref_region },
{ prefix = 'ba', body = 'BA=$1 T0=$0', desc = 'BA=$1 T0=$0', region = ref_region },
}
eq(expand({ insert = false }), ref_matched_snippets)
validate_no_active_session()
validate_state('i', { 'a' }, { 1, 1 })
-- - All snippets if `match = false`
local ref_all_snippets = {
{ prefix = 'aa', body = 'AA=$1 T0=$0', desc = 'AA=$1 T0=$0' },
{ prefix = 'ba', body = 'BA=$1 T0=$0', desc = 'BA=$1 T0=$0' },
{ prefix = 'xx', body = 'XX=$1 T0=$0', desc = 'XX=$1 T0=$0' },
}
eq(expand({ match = false, insert = false }), ref_all_snippets)
validate_no_active_session()
validate_state('i', { 'a' }, { 1, 1 })
end
T['expand()']['does not warn about no matches if `insert = false`'] = function()
-- No matches
type_keys('i', 't')
eq(expand({ insert = false }), {})
-- No snippets at all
child.lua('MiniSnippets.config.snippets = {}')
eq(expand({ match = false, insert = false }), {})
-- In both cases output should be done silently
eq(child.lua_get('_G.notify_log'), {})
end
T['expand()']['validates correct step output'] = function()
local validate_bad_out = function(step_name, bad_output)
child.lua('_G.step_name, _G.bad_output = ' .. vim.inspect(step_name) .. ', ' .. vim.inspect(bad_output))
child.lua('_G.bad_step = function() return _G.bad_output end')
local err_pattern = '`' .. step_name .. '`.*array of snippets'
expect.error(function() child.lua('MiniSnippets.expand({ [_G.step_name] = _G.bad_step })') end, err_pattern)
end
-- Should error about not proper `prepare` output
validate_bad_out('prepare', 1)
validate_bad_out('prepare', { 1 })
validate_bad_out('prepare', { 1 })
validate_bad_out('prepare', { { body = 1 } })
validate_bad_out('prepare', { { body = 'T1=$1', prefix = 1 } })
validate_bad_out('prepare', { { body = 'T1=$1', desc = 1 } })
validate_bad_out('prepare', { { body = 'T1=$1', region = 1 } })
-- Should error about not proper `match` output
validate_bad_out('match', 1)
validate_bad_out('match', { 1 })
validate_bad_out('match', { 1 })
validate_bad_out('match', { { body = 1 } })
validate_bad_out('match', { { body = 'T1=$1', prefix = 1 } })
validate_bad_out('match', { { body = 'T1=$1', desc = 1 } })
validate_bad_out('match', { { body = 'T1=$1', region = 1 } })
-- Should warn about no matches and use `context` returned from `prepare` step
child.lua([[
MiniSnippets.config.expand.prepare = function(...)
return _G.prepare_res or MiniSnippets.default_prepare(...), { data = 'my context' }
end
]])
-- - Should warn about no matches
type_keys('i', 't')
expand()
validate_state('i', { 't' }, { 1, 1 })
local ref_log = { { '(mini.snippets) No matches in context:\n{\n data = "my context"\n}', 'WARN' } }
eq(child.lua_get('_G.notify_log'), ref_log)
child.lua('_G.notify_log = {}')
ensure_clean_state()
-- Should warn about no snippets (as returned by prepare step) at all
child.lua('_G.prepare_res = {}')
type_keys('i', 'a')
expand()
validate_state('i', { 'a' }, { 1, 1 })
ref_log = { { '(mini.snippets) No snippets in context:\n{\n data = "my context"\n}', 'WARN' } }
eq(child.lua_get('_G.notify_log'), ref_log)
child.lua('_G.notify_log = {}')
ensure_clean_state()
end
T['expand()']['validates input'] = function()
expect.error(function() expand({ prepare = 1 }) end, '`opts%.prepare`.*callable')
expect.error(function() expand({ match = 1 }) end, '`opts%.match`.*`false` or callable')
expect.error(function() expand({ select = 1 }) end, '`opts%.select`.*`false` or callable')
expect.error(function() expand({ insert = 1 }) end, '`opts%.insert`.*`false` or callable')
end
T['expand()']['respects `vim.b.minisnippets_config`'] = function()
-- Should process buffer-local config after global config and in this case
-- remove snippets with these prefixes (as body is `nil`)
child.b.minisnippets_config = { snippets = { { prefix = 'aa' }, { prefix = 'ba' } } }
eq(expand({ insert = false, match = false }), { { prefix = 'xx', body = 'XX=$1 T0=$0', desc = 'XX=$1 T0=$0' } })
end
T['expand()']['respects `vim.{g,b}.minidiff_disable`'] = new_set({
parametrize = { { 'g' }, { 'b' } },
}, {
test = function(var_type)
child[var_type].minisnippets_disable = true
mock_select(2)
expand()
validate_no_active_session()
validate_state('n', { '' }, { 1, 0 })
child[var_type].minisnippets_disable = false
mock_select(2)
expand()
validate_active_session()
validate_state('i', { 'BA= T0=' }, { 1, 3 })
end,
})
T['gen_loader'] = new_set({
hooks = {
pre_case = function()
-- Monkey-patch `read_file()` to test caching
child.lua([[
local read_file_orig = MiniSnippets.read_file
_G.read_args_log = {}
MiniSnippets.read_file = function(...)
table.insert(_G.read_args_log, { ... })
return read_file_orig(...)
end
]])
end,
},
})
T['gen_loader']['from_lang()'] = new_set()
T['gen_loader']['from_lang()']['works'] = function()
child.o.runtimepath = test_dir_absolute .. '/subdir,' .. test_dir_absolute
child.lua('_G.loader = MiniSnippets.gen_loader.from_lang()')
local ref_snippet_data = {
-- Should first read runtime files (however nested) from "lua" directory
{
{ { prefix = 'f', body = 'F=$1', desc = 'subdir/snippets/lua/deeper/another.json' } },
{ { prefix = 'e', body = 'E=$1', desc = 'subdir/snippets/lua/file.json' } },
},
{
{ { prefix = 'd', body = 'D=$1', desc = 'subdir/snippets/lua/snips.lua' } },
},
-- And only then from exactly named files (however nested)
{
-- Should read in order of 'runtimepath'
{ { prefix = 'c', body = 'C=$1', desc = 'subdir/snippets/lua.json' } },
{ { prefix = 'a', body = 'A=$1', desc = 'snippets/lua.json' } },
{ { prefix = 'g', body = 'G=$1', desc = 'snippets/nested/lua.json' } },
},
{
{ { prefix = 'b', body = 'B=$1', desc = 'snippets/lua.lua' } },
{ { prefix = 'h', body = 'H=$1', desc = 'snippets/nested/lua.lua' } },
},
}
eq(child.lua_get('_G.loader({ lang = "lua" })'), ref_snippet_data)
-- Should cache output per lang context and thus not call `read_file` again
local read_args_log = child.lua_get('_G.read_args_log')
child.lua('_G.loader({ lang = "lua" })')
eq(child.lua_get('_G.read_args_log'), read_args_log)
end
T['gen_loader']['from_lang()']['respects `opts.lang_patterns`'] = function()
child.o.runtimepath = test_dir_absolute
child.lua('_G.loader = MiniSnippets.gen_loader.from_lang({ lang_patterns = { lua = { "lua.lua" } } })')
local ref_snippet_data = { { { { prefix = 'b', body = 'B=$1', desc = 'snippets/lua.lua' } } } }
eq(child.lua_get('_G.loader({ lang = "lua" })'), ref_snippet_data)
end
T['gen_loader']['from_lang()']['works with not typical `lang` context'] = function()
child.o.runtimepath = test_dir_absolute
child.lua([[_G.loader = MiniSnippets.gen_loader.from_lang() ]])
-- Not string should be silently ignored
eq(child.lua_get('_G.loader({ lang = 1 })'), {})
eq(child.lua_get('_G.loader({ lang = nil })'), {})
eq(child.lua_get('_G.notify_log'), {})
-- Empty string
eq(child.lua_get('_G.loader({ lang = "" })'), {})
-- - Can be made working by explicitly adding language pattern
child.lua([[
local lang_patterns = { [''] = { 'lua.json' } }
_G.loader_2 = MiniSnippets.gen_loader.from_lang({ lang_patterns = lang_patterns })
]])
eq(
child.lua_get('_G.loader_2({ lang = "" })'),
{ { { { prefix = 'a', body = 'A=$1', desc = 'snippets/lua.json' } } } }
)
end
T['gen_loader']['from_lang()']['outputs share cache per pattern'] = function()
child.o.runtimepath = test_dir_absolute .. '/subdir,' .. test_dir_absolute
child.lua([[
local opts_1 = { lang_patterns = { lua = { 'lua.json', 'lua.lua' } } }
_G.loader_1 = MiniSnippets.gen_loader.from_lang(opts_1)
local opts_2 = { lang_patterns = { lua = { 'lua.json', 'lua.code-snippets' } } }
_G.loader_2 = MiniSnippets.gen_loader.from_lang(opts_2)
]])
child.lua_get('_G.loader_1({ lang = "lua" })')
local read_args_log = child.lua_get('_G.read_args_log')
child.lua_get('_G.loader_2({ lang = "lua" })')
-- It should have read one extra 'subdir/snippets/lua.code-snippets', while
-- using cache for all 'lua.json' files
eq(#child.lua_get('_G.read_args_log'), #read_args_log + 1)
end
T['gen_loader']['from_lang()']['respects `opts.cache`'] = function()
child.o.runtimepath = test_dir_absolute
child.lua('_G.loader = MiniSnippets.gen_loader.from_lang({ cache = false })')
child.lua('_G.loader({ lang = "lua" })')
local read_args_log = child.lua_get('_G.read_args_log')
eq(#read_args_log > 0, true)
child.lua('_G.loader({ lang = "lua" })')
eq(#child.lua_get('_G.read_args_log') > #read_args_log, true)
end
T['gen_loader']['from_lang()']['clears cache after `setup()`'] = function()
child.o.runtimepath = test_dir_absolute
child.lua('_G.loader = MiniSnippets.gen_loader.from_lang()')
child.lua('_G.loader({ lang = "lua" })')
local read_args_log = child.lua_get('_G.read_args_log')
child.lua('MiniSnippets.setup()')
child.lua('_G.loader({ lang = "lua" })')
eq(#child.lua_get('_G.read_args_log') > #read_args_log, true)
end
T['gen_loader']['from_lang()']['forwards `opts.cache` and `opts.silent` to `from_runtime()`'] = function()
child.lua([[
local from_runtime_orig = MiniSnippets.gen_loader.from_runtime
_G.from_runtime_args_log = {}
MiniSnippets.gen_loader.from_runtime = function(...)
table.insert(_G.from_runtime_args_log, { ... })
return from_runtime_orig(...)
end
]])
child.o.runtimepath = test_dir_absolute
child.lua([[_G.loader = MiniSnippets.gen_loader.from_lang({ cache = false, silent = true })]])
child.lua('_G.loader({ lang = "lua" })')
local from_runtime_args_log = child.lua_get('_G.from_runtime_args_log')
eq(from_runtime_args_log[1][2], { cache = false, silent = true })
eq(from_runtime_args_log[2][2], { cache = false, silent = true })
-- Should not reuse generate `from_runtime()` loaders
child.lua('_G.loader({ lang = "lua" })')
eq(child.lua_get('_G.from_runtime_args_log'), from_runtime_args_log)
end
T['gen_loader']['from_lang()']['validates input'] = function()
local validate_lang_patterns_error = function(lang_patterns, err_pattern)
child.lua('_G.lang_patterns = ' .. vim.inspect(lang_patterns))
local lua_cmd = 'MiniSnippets.gen_loader.from_lang({ lang_patterns = _G.lang_patterns })'
expect.error(function() child.lua(lua_cmd) end, err_pattern)
end
validate_lang_patterns_error({ 'lua' }, 'Keys of `opts.lang_patterns`.*string')
validate_lang_patterns_error({ lua = 'lua.lua' }, 'Values of `opts.lang_patterns`.*arrays')
validate_lang_patterns_error({ lua = { 1 } }, 'Values of `opts.lang_patterns`.*string')
end
T['gen_loader']['from_runtime()'] = new_set()
T['gen_loader']['from_runtime()']['works'] = function()
child.o.runtimepath = test_dir_absolute .. '/subdir'
child.lua([[_G.loader = MiniSnippets.gen_loader.from_runtime('lua/**/*.json')]])
local ref_snippets = {
{ { prefix = 'f', body = 'F=$1', desc = 'subdir/snippets/lua/deeper/another.json' } },
{ { prefix = 'e', body = 'E=$1', desc = 'subdir/snippets/lua/file.json' } },
}
eq(child.lua_get('_G.loader()'), ref_snippets)
local read_args_log = child.lua_get('_G.read_args_log')
-- Should cache output per pattern and thus not call `read_file` again
eq(child.lua_get('_G.loader()'), ref_snippets)
eq(child.lua_get('_G.read_args_log'), read_args_log)
child.lua([[_G.loader_2 = MiniSnippets.gen_loader.from_runtime('lua/**/snips.lua')]])
eq(child.lua_get('_G.loader_2()'), { { { prefix = 'd', body = 'D=$1', desc = 'subdir/snippets/lua/snips.lua' } } })
eq(#child.lua_get('_G.read_args_log') > #read_args_log, true)
-- Should read all matching files (not just first)
child.o.runtimepath = (test_dir_absolute .. '/subdir') .. ',' .. test_dir_absolute
child.lua([[_G.loader_all = MiniSnippets.gen_loader.from_runtime('lua.json')]])
local ref_snippets_all = {
{ { prefix = 'c', body = 'C=$1', desc = 'subdir/snippets/lua.json' } },
{ { prefix = 'a', body = 'A=$1', desc = 'snippets/lua.json' } },
}
eq(child.lua_get('_G.loader_all()'), ref_snippets_all)
end
T['gen_loader']['from_runtime()']['outputs share cache'] = function()
child.o.runtimepath = test_dir_absolute
child.lua([[
_G.loader_1 = MiniSnippets.gen_loader.from_runtime('lua.json')
_G.loader_2 = MiniSnippets.gen_loader.from_runtime('lua.json')
]])
child.lua_get('_G.loader_1()')
local read_args_log = child.lua_get('_G.read_args_log')
eq(#read_args_log > 0, true)
child.lua_get('_G.loader_2()')
eq(child.lua_get('_G.read_args_log'), read_args_log)
end
T['gen_loader']['from_runtime()']['respects `opts.cache`'] = function()
child.o.runtimepath = test_dir_absolute
child.lua([[_G.loader = MiniSnippets.gen_loader.from_runtime('lua.json', { cache = false })]])
child.lua('_G.loader()')
local read_args_log = child.lua_get('_G.read_args_log')
-- Should use `read_file()` again as no caching is done
child.lua('_G.loader()')
eq(#child.lua_get('_G.read_args_log') > #read_args_log, true)
end
T['gen_loader']['from_runtime()']['forwards `opts.cache` and `opts.silent` to `read_file()`'] = function()
child.o.runtimepath = test_dir_absolute
child.lua([[_G.loader = MiniSnippets.gen_loader.from_runtime('lua.json', { cache = false, silent = true })]])
child.lua('_G.loader()')
local read_args_log = child.lua_get('_G.read_args_log')
eq(read_args_log[1][2], { cache = false, silent = true })
end
T['gen_loader']['from_runtime()']['respects `opts.all`'] = function()
child.o.runtimepath = (test_dir_absolute .. '/subdir') .. ',' .. test_dir_absolute
child.lua([[_G.loader_first = MiniSnippets.gen_loader.from_runtime('lua.json', { all = false })]])
local ref_snippets_first = { { { prefix = 'c', body = 'C=$1', desc = 'subdir/snippets/lua.json' } } }
eq(child.lua_get('_G.loader_first()'), ref_snippets_first)
end
T['gen_loader']['from_runtime()']['clears cache after `setup()`'] = function()
child.o.runtimepath = test_dir_absolute
child.lua([[_G.loader = MiniSnippets.gen_loader.from_runtime('lua.lua')]])
child.lua('_G.loader()')
local read_args_log = child.lua_get('_G.read_args_log')
child.lua('MiniSnippets.setup()')
child.lua('_G.loader()')
eq(#child.lua_get('_G.read_args_log') > #read_args_log, true)
end
T['gen_loader']['from_runtime()']['validates input'] = function()
expect.error(function() child.lua('MiniSnippets.gen_loader.from_runtime(1)') end, '`pattern`.*string')
end
T['gen_loader']['from_file()'] = new_set()
T['gen_loader']['from_file()']['works'] = function()
-- Should be able to work with relative paths
child.lua('_G.loader = MiniSnippets.gen_loader.from_file("file-array.lua")')
-- Should silently return `{}` if file is absent
eq(child.lua_get('_G.loader()'), {})
eq(child.lua_get('_G.notify_log'), {})
-- Should load file if present and show warnings
child.fn.chdir(test_dir_absolute)
local out = child.lua_get('_G.loader()')
eq(#out, 5)
eq(out[1], { prefix = 'lua_a', body = 'LUA_A=$1', desc = 'Desc LUA_A' })
expect.match(child.lua_get('_G.notify_log')[1][1], 'There were problems')
-- Should work with paths stargin with "~"
local path_tilde = child.lua([[
local path_tilde = vim.fn.fnamemodify('file-array.lua', ':p:~')
_G.loader_tilde = MiniSnippets.gen_loader.from_file(path_tilde)
return path_tilde
]])
if path_tilde:sub(1, 1) ~= '~' then return end
eq(child.lua_get('_G.loader_tilde()'), out)
end
T['gen_loader']['from_file()']['does not cache if there were reading problems'] = function()
local temp_file = child.lua([[
local temp_file = vim.fn.tempname() .. '.lua'
_G.loader = MiniSnippets.gen_loader.from_file(temp_file)
return temp_file
]])
MiniTest.finally(function() child.fn.delete(temp_file) end)
child.fn.writefile({ 'return 1' }, temp_file)
eq(child.lua_get('_G.loader()'), {})
child.fn.writefile({ 'return { { prefix = "a", body = "A=$1" } }' }, temp_file)
eq(child.lua_get('_G.loader()'), { { prefix = 'a', body = 'A=$1' } })
end
T['gen_loader']['from_file()']['forwards `opts` to `read_file()`'] = function()
child.fn.chdir(test_dir_absolute)
child.lua([[
local loader = MiniSnippets.gen_loader.from_file('file-array.lua', { cache = false, silent = true })
loader()
]])
local full_path = child.fn.fnamemodify('file-array.lua', ':p')
eq(child.lua_get('_G.read_args_log'), { { full_path, { cache = false, silent = true } } })
end
T['gen_loader']['from_file()']['clears cache after `setup()`'] = function()
child.fn.chdir(test_dir_absolute)
child.lua([[_G.loader = MiniSnippets.gen_loader.from_file('file-array.lua')]])
child.lua('_G.loader()')
local read_args_log = child.lua_get('_G.read_args_log')
child.lua('MiniSnippets.setup()')
child.lua('_G.loader()')
eq(#child.lua_get('_G.read_args_log') > #read_args_log, true)
end
T['gen_loader']['from_file()']['validates input'] = function()
expect.error(function() child.lua('MiniSnippets.gen_loader.from_file(1)') end, '`path`.*string')
end
T['read_file()'] = new_set()
local read_file = forward_lua('MiniSnippets.read_file')
local validate_problems = function(path_pattern, problem_pattern, clean)
local log = child.lua_get('_G.notify_log')
eq(#log, 1)
local pattern = '%(mini%.snippets%) There were problems reading file.*'
.. path_pattern
.. '.*:\n.*'
.. problem_pattern
expect.match(log[1][1], pattern)
expect.match(log[1][2], 'WARN')
if clean == nil or clean then child.lua('_G.notify_log = {}') end
end
T['read_file()']['works with dict-like content'] = function()
local validate = function(filename)
local ref = {
{ prefix = 'lua_a', body = 'LUA_A=$1', desc = 'Desc LUA_A' },
{ prefix = 'lua_b', body = 'LUA_B=$1', description = 'Desc LUA_B' },
-- Should try to use table fields as description
{ prefix = nil, body = 'LUA_C=$1', desc = 'name_c' },
-- Should still return non-unique prefixes
{ prefix = 'd', body = 'D1=$1', desc = 'dupl1' },
{ prefix = 'd', body = nil, desc = 'Dupl2' },
}
local out = read_file(test_dir_absolute .. '/' .. filename)
eq(type(out), 'table')
-- - Order is not guaranteed (but usually it is alphabetical by fields)
local compare = function(a, b) return (a.desc or a.description or '') < (b.desc or b.description or '') end
table.sort(out, compare)
table.sort(ref, compare)
eq(out, ref)
-- - Order of problems is also not guaranteed
validate_problems(vim.pesc(filename), 'not a valid snippet data.*prefix = 1', false)
validate_problems(vim.pesc(filename), 'not a valid snippet data.*2')
end
validate('file-dict.lua')
validate('file-dict.json')
validate('file-dict.code-snippets')
end
T['read_file()']['works with array-like content'] = function()
local validate = function(filename)
local ref = {
{ prefix = 'lua_a', body = 'LUA_A=$1', desc = 'Desc LUA_A' },
-- Should not infer desc-like fields as there is no dict name to infer from
{ prefix = 'lua_b', body = 'LUA_B=$1', description = 'Desc LUA_B' },
{ prefix = nil, body = 'LUA_C=$1' },
-- Should still return non-unique prefixes
{ prefix = 'd', body = 'D1=$1' },
{ prefix = 'd', body = nil, desc = 'Dupl2' },
}
-- Order of valid entries should be preserved
eq(read_file(test_dir_absolute .. '/' .. filename), ref)
validate_problems(vim.pesc(filename), 'not a valid snippet data.*prefix = 1.*not a valid snippet data.*2')
end
validate('file-array.lua')
validate('file-array.json')
validate('file-array.code-snippets')
end
T['read_file()']['works with relative paths'] = function()
child.fn.chdir(test_dir_absolute)
eq(read_file('snippets/lua.json'), { { prefix = 'a', body = 'A=$1', desc = 'snippets/lua.json' } })
-- Should cache per full path
child.fn.chdir('subdir')
eq(read_file('snippets/lua.json'), { { prefix = 'c', body = 'C=$1', desc = 'subdir/snippets/lua.json' } })