-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathtest_sessions.lua
More file actions
1278 lines (1020 loc) · 45.4 KB
/
Copy pathtest_sessions.lua
File metadata and controls
1278 lines (1020 loc) · 45.4 KB
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
-- General design of testing sessions is to have each session file define
-- `_G.session_file` variable with value being path to sourced session. So
-- these assumptions are assumed:
-- - If `_G.session_file` is `nil`, no session file was sourced.
-- - If `_G.session_file` is not `nil`, its value is a relative (to project
-- root) path to a session file that was sourced.
local helpers = dofile('tests/helpers.lua')
local child = helpers.new_child_neovim()
local expect, eq = helpers.expect, helpers.expect.equality
local new_set = MiniTest.new_set
local project_root = vim.fs.normalize(vim.fn.getcwd())
local empty_dir_relpath = 'tests/dir-sessions/empty'
local empty_dir_path = project_root .. '/' .. empty_dir_relpath
-- Helpers with child processes
local load_module = function(config) child.mini_load('sessions', config) end
local unload_module = function() child.mini_unload('sessions') end
local reload_module = function(config) child.mini_reload('sessions', config) end
local reload_from_strconfig = function(strconfig) child.mini_reload_strconfig('sessions', strconfig) end
local set_lines = function(...) return child.set_lines(...) end
local make_path = function(...) return vim.fs.normalize(table.concat({ ... }, '/')) end
local cd = function(...) child.cmd('cd ' .. make_path(...)) end
local sleep = function(ms) helpers.sleep(ms, child) end
-- Make helpers
local cleanup_directories = function()
-- Cleanup files for directories to have invariant properties
-- Ensure 'empty' directory doesn't exist
child.fn.delete(empty_dir_path, 'rf')
-- Ensure 'missing-directory' doesn't exist
child.fn.delete('tests/dir-sessions/missing-directory', 'rf')
-- Ensure 'global' does not contain file 'Session.vim'
local files = { 'tests/dir-sessions/global/Session.vim' }
for _, f in ipairs(files) do
child.fn.delete(f)
end
end
local get_latest_message = function() return child.cmd_capture('1messages') end
local get_buf_names = function()
return child.lua_get('vim.tbl_map(function(x) return vim.fn.bufname(x) end, vim.api.nvim_list_bufs())')
end
local compare_buffer_names = function(x, y)
-- Don't test exact equality because different Neovim versions create
-- different buffer order when sourcing session (see
-- https://github.com/vim/vim/pull/9520)
table.sort(x)
table.sort(y)
eq(x, y)
end
-- Helpers for validating sessions
local populate_sessions = function(delay)
delay = delay or 0
child.fn.delete(empty_dir_path, 'rf')
child.fn.mkdir(empty_dir_path)
local make_file = function(name)
local path = make_path(empty_dir_path, name)
local value = make_path(empty_dir_relpath, name)
child.fn.writefile({ ([[lua _G.session_file = '%s']]):format(value) }, path)
end
make_file('session_a')
-- Modification time is up to seconds, so wait to ensure correct order
sleep(delay)
make_file('session_b')
return empty_dir_path
end
local validate_session_loaded = function(relative_path)
local path = make_path('tests/dir-sessions', relative_path)
-- It should actually source file
eq(child.lua_get('_G.session_file'), path)
-- It should set `this_session`
eq(child.v.this_session, make_path(project_root, path))
end
local validate_no_session_loaded = function() eq(child.lua_get('type(_G.session_file)'), 'nil') end
local reset_session_indicator = function() child.lua('_G.session_file = nil') end
-- Helpers for testing hooks
--stylua: ignore
local make_hook_string = function(pre_post, action, hook_type)
if hook_type == 'config' then
return string.format(
[[{ %s = { %s = function(...) _G.hooks_args = { ... }; _G.hooks_%s_%s = 'config' end }}]],
pre_post, action, pre_post, action
)
end
if hook_type == 'opts' then
return string.format(
[[{ %s = function(...) _G.hooks_args = { ... }; _G.hooks_%s_%s = 'opts' end }]],
pre_post, pre_post, action
)
end
end
local validate_executed_hook = function(pre_post, action, value)
local var_name = ('_G.hooks_%s_%s'):format(pre_post, action)
eq(child.lua_get(var_name), value)
-- Only one argument should be passed
local hooks_args = child.lua_get('_G.hooks_args')
eq(vim.tbl_keys(hooks_args), { 1 })
-- It is a session data
local data = hooks_args[1]
local keys = vim.tbl_keys(data)
table.sort(keys)
eq(keys, { 'modify_time', 'name', 'path', 'type' })
eq(vim.tbl_map(function(x) return type(data[x]) end, keys), { 'number', 'string', 'string', 'string' })
end
-- Time constants
local one_second_delay = 1000
local small_time = helpers.get_time_const(10)
-- Output test set ============================================================
local T = new_set({
hooks = {
pre_case = function()
child.setup()
-- Ensure `require('mini.sessions')` is always possible (which might not be
-- the case with all present `cd` calls)
child.cmd('set rtp+=' .. project_root)
-- Ensure always identical starting current directory
cd(project_root)
-- Ensure directory structure invariants
cleanup_directories()
-- Make all showed messages full width
child.o.cmdheight = 10
-- Load module
load_module()
-- Ensure clear message history
child.cmd('messages clear')
end,
post_once = function()
cleanup_directories()
child.stop()
end,
},
n_retry = helpers.get_n_retry(1),
})
-- Unit tests =================================================================
T['setup()'] = new_set()
T['setup()']['creates side effects'] = function()
-- Global variable
eq(child.lua_get('type(_G.MiniSessions)'), 'table')
-- Autocommand group
eq(child.fn.exists('#MiniSessions'), 1)
end
T['setup()']['creates `config` field'] = function()
eq(child.lua_get('type(_G.MiniSessions.config)'), 'table')
-- Check default values
local expect_config = function(field, value) eq(child.lua_get('MiniSessions.config.' .. field), value) end
expect_config('autoread', false)
expect_config('autowrite', true)
expect_config('directory', child.fn.stdpath('data') .. '/session')
expect_config('file', 'Session.vim')
expect_config('force', { read = false, write = true, delete = false })
expect_config('hooks.pre', { read = nil, write = nil, delete = nil })
expect_config('hooks.post', { read = nil, write = nil, delete = nil })
expect_config('verbose', { read = false, write = true, delete = true })
end
T['setup()']['respects `config` argument'] = function()
reload_module({ autoread = true })
eq(child.lua_get('MiniSessions.config.autoread'), true)
end
T['setup()']['validates `config` argument'] = function()
unload_module()
local expect_config_error = function(config, name, target_type)
expect.error(function() load_module(config) end, vim.pesc(name) .. '.*' .. vim.pesc(target_type))
end
expect_config_error('a', 'config', 'table')
expect_config_error({ autoread = 'a' }, 'autoread', 'boolean')
expect_config_error({ autowrite = 'a' }, 'autowrite', 'boolean')
expect_config_error({ directory = 1 }, 'directory', 'string')
expect_config_error({ file = 1 }, 'file', 'string')
expect_config_error({ force = 'a' }, 'force', 'table')
expect_config_error({ force = { read = 'a' } }, 'force.read', 'boolean')
expect_config_error({ force = { write = 'a' } }, 'force.write', 'boolean')
expect_config_error({ force = { delete = 'a' } }, 'force.delete', 'boolean')
expect_config_error({ hooks = 'a' }, 'hooks', 'table')
expect_config_error({ hooks = { pre = 'a' } }, 'hooks.pre', 'table')
expect_config_error({ hooks = { pre = { read = 'a' } } }, 'hooks.pre.read', 'function')
expect_config_error({ hooks = { pre = { write = 'a' } } }, 'hooks.pre.write', 'function')
expect_config_error({ hooks = { pre = { delete = 'a' } } }, 'hooks.pre.delete', 'function')
expect_config_error({ hooks = { post = 'a' } }, 'hooks.post', 'table')
expect_config_error({ hooks = { post = { read = 'a' } } }, 'hooks.post.read', 'function')
expect_config_error({ hooks = { post = { write = 'a' } } }, 'hooks.post.write', 'function')
expect_config_error({ hooks = { post = { delete = 'a' } } }, 'hooks.post.delete', 'function')
expect_config_error({ verbose = 'a' }, 'verbose', 'table')
expect_config_error({ verbose = { read = 'a' } }, 'verbose.read', 'boolean')
expect_config_error({ verbose = { write = 'a' } }, 'verbose.write', 'boolean')
expect_config_error({ verbose = { delete = 'a' } }, 'verbose.delete', 'boolean')
end
T['setup()']['detects sessions and respects `config.directory`'] = function()
cd('tests', 'dir-sessions')
reload_module({ directory = 'global' })
local detected = child.lua_get('MiniSessions.detected')
-- Should be a table with correct keys
eq(type(detected), 'table')
local keys = vim.tbl_keys(detected)
table.sort(keys)
--stylua: ignore
eq(keys, {
'.session', 'Session.vim', 'session1', 'session2.vim', 'session3.lua',
'session_cd_global', 'session_cd_local', 'session_cd_local_2'
})
-- Elements should have correct structure
local cur_dir = child.fn.getcwd()
local session_dir = make_path(cur_dir, 'global')
for key, val in pairs(detected) do
eq(type(val.modify_time), 'number')
eq(val.name, key)
if val.name == 'Session.vim' then
eq(val.type, 'local')
eq(val.path, make_path(cur_dir, 'Session.vim'))
else
eq(val.type, 'global')
eq(val.path, make_path(session_dir, val.name))
end
end
end
T['setup()']['prefers local session file over global'] = function()
-- Make file 'Session.vim' be in both `config.directory` and current one
local path_local = 'tests/dir-sessions/global/Session.vim'
child.fn.writefile({ ([[lua _G.session_file = '%s']]):format(path_local) }, path_local)
cd('tests', 'dir-sessions')
reload_module({ directory = 'global' })
local detected = child.lua_get('MiniSessions.detected')
local expected_path = project_root .. '/tests/dir-sessions/Session.vim'
eq(detected['Session.vim'].path, expected_path)
end
T['setup()']['allows empty string for `config.directory`'] = function()
reload_module({ directory = '' })
eq(child.lua_get('MiniSessions.detected'), {})
end
T['setup()']['creates missing `config.directory`'] = function()
local directory = 'tests/dir-sessions/missing-directory'
eq(child.fn.isdirectory(directory), 0)
reload_module({ directory = directory })
eq(child.fn.isdirectory(directory), 1)
end
T['setup()']['does not create `config.directory` if it is an existing file'] = function()
reload_module({ directory = 'lua/mini/sessions.lua' })
expect.match(get_latest_message(), '%(mini%.sessions%).*lua/mini/sessions%.lua.*is not a directory path')
end
T['setup()']['respects `config.file`'] = function()
cd('tests', 'dir-sessions', 'local')
reload_module({ autowrite = false, file = 'alternative-local-session' })
local detected = child.lua_get('MiniSessions.detected')
eq(detected['Session.vim'], nil)
eq(detected['alternative-local-session'].type, 'local')
end
T['setup()']['allows empty string for `config.file`'] = function()
cd('tests/dir-sessions')
reload_module({ file = '' })
local detected = child.lua_get('MiniSessions.detected')
eq(vim.tbl_filter(function(x) return x.type == 'local' end, detected), {})
end
T['detected'] = new_set()
T['detected']['is present'] = function()
cd('tests', 'dir-sessions')
reload_module({ directory = 'global' })
eq(child.lua_get('type(MiniSessions.detected)'), 'table')
end
T['detected']['is an empty table if no sessions are detected'] = function()
reload_module({ directory = vim.fn.fnamemodify(child.fn.tempname(), ':h') })
eq(child.lua_get('MiniSessions.detected'), {})
end
T['read()'] = new_set()
T['read()']['works'] = function()
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
child.lua([[MiniSessions.read('session1')]])
validate_session_loaded('global/session1')
end
T['read()']['works with no detected sessions'] = function()
reload_module({ directory = '', file = '' })
eq(child.lua_get('MiniSessions.detected'), {})
expect.no_error(function() child.lua('MiniSessions.read()') end)
expect.match(get_latest_message(), '%(mini%.sessions%) There are no detected sessions')
end
T['read()']['accepts only name of detected session'] = function()
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
expect.error(
function() child.lua([[MiniSessions.read('session-absent')]]) end,
'%(mini%.sessions%) "session%-absent" is not a name for detected session'
)
validate_no_session_loaded()
end
T['read()']['removes stale local session from detected'] = function()
-- Start in 'local' directory
cd('tests', 'dir-sessions', 'local')
reload_module({ autowrite = false, directory = project_root .. '/tests/dir-sessions/global' })
eq(child.lua_get([[MiniSessions.detected['Session.vim'] ~= nil]]), true)
-- Test yes local -> no local
child.lua([[MiniSessions.read('session_cd_global')]])
validate_session_loaded('global/session_cd_global')
eq(child.lua_get([[MiniSessions.detected['Session.vim'] ~= nil]]), false)
-- Test no local -> yes local
child.lua([[MiniSessions.read('session_cd_local')]])
validate_session_loaded('global/session_cd_local')
eq(child.lua_get([[MiniSessions.detected['Session.vim'] ~= nil]]), true)
-- Test yes local -> yes other local
child.lua([[MiniSessions.read('session_cd_local_2')]])
validate_session_loaded('global/session_cd_local_2')
eq(child.lua_get([[MiniSessions.detected['Session.vim'] ~= nil]]), true)
local other_local_path = project_root .. '/tests/dir-sessions/local-2/Session.vim'
eq(child.lua_get([[MiniSessions.detected['Session.vim'].path ]]), other_local_path)
end
T['read()']['makes detected sessions up to date'] = function()
local new_session = 'tests/dir-sessions/global/new_session'
MiniTest.finally(function() vim.fn.delete(new_session) end)
-- Detect sessions without new session
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
eq(child.lua_get('MiniSessions.detected.new_session == nil'), true)
-- Create new session file manually and try to read it directly without
-- reloading whole module.
child.fn.writefile({ 'lua _G.session_file = ' .. vim.inspect(new_session) }, new_session)
child.lua([[MiniSessions.read('new_session')]])
validate_session_loaded('global/new_session')
end
local setup_unsaved_buffers = function()
child.o.hidden = true
local res = {}
set_lines({ 'aaa' })
table.insert(res, child.api.nvim_get_current_buf())
child.cmd('e foo')
set_lines({ 'bbb' })
table.insert(res, child.api.nvim_get_current_buf())
return res
end
T['read()']['does not source if there are unsaved listed buffers'] = function()
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
-- Setup unsaved buffers
local unsaved_buffers = setup_unsaved_buffers()
-- Session should not be sourced
local error_pattern =
vim.pesc('(mini.sessions) There are unsaved listed buffers: ' .. table.concat(unsaved_buffers, ', ') .. '.')
expect.error(function() child.lua([[MiniSessions.read('session1')]]) end, error_pattern)
validate_no_session_loaded()
end
T['read()']['ignores unsaved not listed buffers'] = function()
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
local buf_id = child.api.nvim_create_buf(false, false)
child.api.nvim_buf_set_lines(buf_id, 0, -1, true, { 'aaa' })
eq(child.api.nvim_buf_get_option(buf_id, 'modified'), true)
eq(child.api.nvim_buf_get_option(buf_id, 'buflisted'), false)
child.lua([[MiniSessions.read('session1')]])
validate_session_loaded('global/session1')
end
T['read()']['uses by default local session'] = function()
cd('tests', 'dir-sessions', 'local')
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
eq(child.lua_get([[MiniSessions.detected['Session.vim'].type]]), 'local')
child.lua('MiniSessions.read()')
validate_session_loaded('local/Session.vim')
end
T['read()']['uses by default latest global session'] = function()
local session_dir = populate_sessions(one_second_delay + small_time)
reload_module({ autowrite = false, directory = session_dir })
child.lua('MiniSessions.read()')
validate_session_loaded('empty/session_b')
end
T['read()']['respects `force` from `config` and `opts` argument'] = function()
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global', force = { read = true } })
-- Should overwrite unsaved buffers and load session if `force` is `true`
setup_unsaved_buffers()
child.lua([[MiniSessions.read('session1')]])
validate_session_loaded('global/session1')
-- Should prefer `opts` over `config`
setup_unsaved_buffers()
reset_session_indicator()
expect.error(
function() child.lua([[MiniSessions.read('session2.vim', { force = false })]]) end,
'%(mini%.sessions%) There are unsaved listed buffers'
)
validate_no_session_loaded()
end
T['read()']['does not stop on source error'] = function()
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
local session_file = 'tests/dir-sessions/global/session_with_error'
local folded_file = 'tests/dir-sessions/folded_file'
local extra_file = 'tests/dir-sessions/extra_file'
MiniTest.finally(function()
vim.fn.delete(session_file)
vim.fn.delete(folded_file)
vim.fn.delete(extra_file)
end)
-- Create buffer with non-trivial folds to imitate "No folds found" error
child.o.foldmethod = 'indent'
child.cmd('edit ' .. folded_file)
set_lines({ 'a', '\ta', '\ta', 'a', '\ta', '\ta' })
child.cmd('write')
child.cmd('normal! zM')
child.cmd('2 | normal! zo')
-- Create another buffer to check correct session read
child.cmd('edit ' .. extra_file)
set_lines({ 'This should be preserved in session' })
child.cmd('write')
-- Write session and make sure it contains call to open folds
child.cmd('edit ' .. folded_file)
child.cmd('mksession ' .. session_file)
local session_lines = table.concat(child.fn.readfile(session_file), '\n')
expect.match(session_lines, 'normal! zo')
-- Modify file so that no folds will be found by session file
child.fn.writefile({ 'No folds in this file' }, folded_file)
-- Cleanly read session which should open foldless file without errors
child.restart()
load_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
expect.no_error(function() child.lua([[MiniSessions.read('session_with_error')]]) end)
local buffers = child.api.nvim_list_bufs()
eq(#buffers, 2)
child.api.nvim_set_current_buf(buffers[1])
local buf_name_1 = child.fs.normalize(child.api.nvim_buf_get_name(0))
eq(vim.endswith(buf_name_1, '/' .. folded_file), true)
eq(child.api.nvim_buf_get_lines(0, 0, -1, true), { 'No folds in this file' })
child.api.nvim_set_current_buf(buffers[2])
local buf_name_2 = child.fs.normalize(child.api.nvim_buf_get_name(0))
eq(vim.endswith(buf_name_2, '/' .. extra_file), true)
eq(child.api.nvim_buf_get_lines(0, 0, -1, true), { 'This should be preserved in session' })
end
T['read()']['writes current session prior to reading a new one'] = function()
local cur_session = project_root .. '/tests/dir-sessions/global/current-session'
MiniTest.finally(function() child.fn.delete(cur_session) end)
local validate = function(ref_autowrite)
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
child.v.this_session = cur_session
child.lua('MiniSessions.config.autowrite = ' .. tostring(ref_autowrite))
eq(child.fn.filereadable(cur_session), 0)
child.lua('MiniSessions.read("session1")')
-- Should only write current if `autowrite` is enabled
eq(child.fn.filereadable(cur_session), ref_autowrite and 1 or 0)
child.fn.delete(cur_session)
end
validate(true)
validate(false)
end
T['read()']['respects hooks from `config` and `opts` argument'] = new_set({
parametrize = { { 'pre' }, { 'post' } },
}, {
test = function(pre_post)
-- Should use `config`
local hook_string_config = make_hook_string(pre_post, 'read', 'config')
reload_from_strconfig({
autowrite = 'false',
directory = [['tests/dir-sessions/global']],
hooks = hook_string_config,
})
child.lua([[MiniSessions.read('session1')]])
validate_session_loaded('global/session1')
validate_executed_hook(pre_post, 'read', 'config')
-- - Make sure that current session is not written
child.v.this_session = ''
-- Should prefer `opts` over `config`
local hook_string_opts = make_hook_string(pre_post, 'read', 'opts')
child.lua(([[MiniSessions.read('session2.vim', { hooks = %s })]]):format(hook_string_opts))
validate_session_loaded('global/session2.vim')
validate_executed_hook(pre_post, 'read', 'opts')
end,
})
T['read()']['respects `verbose` from `config` and `opts` argument'] = function()
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global', verbose = { read = true } })
-- Should give message about read session
child.lua([[MiniSessions.read('session1')]])
validate_session_loaded('global/session1')
expect.match(get_latest_message(), '%(mini%.sessions%) Read session.*session1')
-- - Make sure that current session is not written
child.v.this_session = ''
-- Should prefer `opts` over `config`
reset_session_indicator()
child.lua([[MiniSessions.read('session2.vim', { verbose = false })]])
validate_session_loaded('global/session2.vim')
end
T['read()']['respects `vim.{g,b}.minisessions_disable`'] = new_set({
parametrize = { { 'g' }, { 'b' } },
}, {
test = function(var_type)
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
child[var_type].minisessions_disable = true
reset_session_indicator()
child.lua([[MiniSessions.read('session1')]])
validate_no_session_loaded()
end,
})
T['write()'] = new_set()
T['write()']['works'] = function()
child.fn.mkdir(empty_dir_path)
reload_module({ autowrite = false, directory = empty_dir_path })
-- Setup buffers and autocommands
child.cmd('e foo | e bar')
local buf_names_expected = get_buf_names()
child.lua('_G.n_pre, _G.n_post = 0, 0')
child.cmd('au SessionWritePost * lua _G.n_post = _G.n_post + 1')
if child.fn.has('nvim-0.13') == 1 then child.cmd('au SessionWritePre * lua _G.n_pre = _G.n_pre + 1') end
child.lua('MiniSessions.write("new_session")')
-- Should trigger session-related events
eq(child.lua_get('_G.n_post'), 1)
eq(child.lua_get('_G.n_pre'), child.fn.has('nvim-0.13'))
-- Should update `v:this_session`
local path_expected = make_path(empty_dir_path, 'new_session')
eq(child.v.this_session, path_expected)
-- Verify that written session is correct
child.cmd('%bwipeout')
child.cmd('source ' .. path_expected)
compare_buffer_names(get_buf_names(), buf_names_expected)
end
T['write()']['updates `v:this_session`'] = function()
child.fn.mkdir(empty_dir_path)
reload_module({ autowrite = false, directory = empty_dir_path })
eq(child.v.this_session, '')
child.lua([[MiniSessions.write('new_session')]])
eq(child.v.this_session, make_path(empty_dir_path, 'new_session'))
end
T['write()']['updates `MiniSessions.detected` with new session'] = function()
child.fn.mkdir(empty_dir_path)
reload_module({ autowrite = false, directory = empty_dir_path })
eq(child.lua_get('MiniSessions.detected'), {})
child.lua([[MiniSessions.write('new_session')]])
eq(child.lua_get('MiniSessions.detected.new_session').path, make_path(empty_dir_path, 'new_session'))
end
T['write()']['updates `MiniSessions.detected` for present session'] = function()
local session_dir = populate_sessions(one_second_delay + small_time)
reload_module({ directory = session_dir })
child.lua([[MiniSessions.read('session_a')]])
sleep(one_second_delay + small_time)
child.lua([[MiniSessions.write('session_a')]])
local detected = child.lua_get('MiniSessions.detected')
eq(detected.session_a.modify_time > detected.session_b.modify_time, true)
end
T['write()']['validates `session_name`'] = function()
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
expect.error(
function() child.lua([[MiniSessions.write('')]]) end,
'%(mini%.sessions%) Supply non%-empty session name'
)
end
T['write()']['writes by default to `v:this_session`'] = function()
local session_dir = populate_sessions()
reload_module({ directory = session_dir })
child.lua([[MiniSessions.read('session_a')]])
-- Verify that `v:this_session` points to correct place
local session_path = make_path(session_dir, 'session_a')
eq(child.v.this_session, session_path)
-- Write session with `session_name = nil`
child.cmd('e foo | e bar')
local buf_names_expected = get_buf_names()
child.lua('MiniSessions.write()')
-- Verify that it was actually written to `v:this_session`
child.cmd('%bwipeout!')
child.cmd('source ' .. session_path)
compare_buffer_names(get_buf_names(), buf_names_expected)
end
T['write()']['writes to current directory if passed name of local session file'] = function()
reload_module({ file = 'new-local-session', directory = '' })
child.fn.mkdir(empty_dir_path)
cd(empty_dir_path)
child.lua([[MiniSessions.write('new-local-session')]])
local path = make_path(empty_dir_path, 'new-local-session')
eq(child.fn.filereadable(path), 1)
end
T['write()']['writes to global directory'] = function()
child.fn.mkdir(empty_dir_path)
reload_module({ file = '', directory = empty_dir_path })
child.lua([[MiniSessions.write('new-global-session')]])
local target_path = make_path(empty_dir_path, 'new-global-session')
eq(child.fn.filereadable(target_path), 1)
end
T['write()']['respects `force` from `config` and `opts` argument'] = function()
child.fn.mkdir(empty_dir_path)
reload_module({ directory = empty_dir_path, force = { write = false } })
-- Should not allow writing to existing file if `force` is `false`
local path = make_path(empty_dir_path, 'existing-file')
child.fn.writefile({}, path)
expect.error(
function() child.lua([[MiniSessions.write('existing-file')]]) end,
[[%(mini%.sessions%) Can't write to existing]]
)
eq(child.fn.readfile(path), {})
-- Should prefer `opts` over `config`
child.lua([[MiniSessions.write('existing-file', { force = true })]])
eq(#child.fn.readfile(path) > 0, true)
end
T['write()']['respects hooks from `config` and `opts` argument'] = new_set({
parametrize = { { 'pre' }, { 'post' } },
}, {
test = function(pre_post)
child.fn.mkdir(empty_dir_path)
local path
-- Should use `config`
local hook_string_config = make_hook_string(pre_post, 'write', 'config')
reload_from_strconfig({ directory = vim.inspect(empty_dir_path), hooks = hook_string_config })
child.lua([[MiniSessions.write('file_01')]])
path = make_path(empty_dir_path, 'file_01')
eq(#child.fn.readfile(path) > 0, true)
validate_executed_hook(pre_post, 'write', 'config')
-- Should prefer `opts` over `config`
local hook_string_opts = make_hook_string(pre_post, 'write', 'opts')
child.lua(([[MiniSessions.write('file_02', { hooks = %s })]]):format(hook_string_opts))
path = make_path(empty_dir_path, 'file_02')
eq(#child.fn.readfile(path) > 0, true)
validate_executed_hook(pre_post, 'write', 'opts')
end,
})
T['write()']['respects `verbose` from `config` and `opts` argument'] = function()
child.fn.mkdir(empty_dir_path)
reload_module({ directory = empty_dir_path, verbose = { write = false } })
local msg_pattern = '%(mini%.sessions%) Written session.*session%-written'
-- Should not give message about written session
child.lua([[MiniSessions.write('session-written')]])
local path = make_path(empty_dir_path, 'session-written')
eq(#child.fn.readfile(path) > 0, true)
expect.no_match(get_latest_message(), msg_pattern)
-- Should prefer `opts` over `config`
child.fn.delete(path)
child.lua([[MiniSessions.write('session-written', { verbose = true })]])
eq(#child.fn.readfile(path) > 0, true)
expect.match(get_latest_message(), msg_pattern)
end
T['write()']['respects `vim.{g,b}.minisessions_disable`'] = new_set({
parametrize = { { 'g' }, { 'b' } },
}, {
test = function(var_type)
child.fn.mkdir(empty_dir_path)
reload_module({ directory = empty_dir_path })
local path = make_path(empty_dir_path, 'session-file')
child[var_type].minisessions_disable = true
child.fn.delete(path)
child.lua([[MiniSessions.write('session-file')]])
eq(child.fn.filereadable('session-file'), 0)
end,
})
T['delete()'] = new_set()
T['delete()']['works'] = function()
local session_dir = populate_sessions()
reload_module({ directory = session_dir })
local path = make_path(session_dir, 'session_a')
eq(child.lua_get('MiniSessions.detected')['session_a'].path, path)
child.lua([[MiniSessions.delete('session_a')]])
eq(child.fn.filereadable(path), 0)
end
T['delete()']['validates presence of detected sessions'] = function()
reload_module({ file = '', directory = '' })
expect.error(
function() child.lua([[MiniSessions.delete('aaa')]]) end,
'%(mini%.sessions%) There are no detected sessions'
)
end
T['delete()']['validates `session_name`'] = function()
reload_module({ directory = 'tests/dir-sessions/global' })
expect.error(
function() child.lua([[MiniSessions.delete('')]]) end,
'%(mini%.sessions%) Supply non%-empty session name'
)
end
T['delete()']['deletes by default `v:this_session`'] = function()
local session_dir = populate_sessions()
reload_module({ directory = session_dir, force = { delete = true } })
child.lua([[MiniSessions.read('session_a')]])
local path = make_path(session_dir, 'session_a')
eq(child.v.this_session, path)
child.lua('MiniSessions.delete()')
eq(child.fn.filereadable(path), 0)
-- Should also update `v:this_session`
eq(child.v.this_session, '')
end
T['delete()']['deletes from current directory if passed name of local session file'] = function()
local session_dir = populate_sessions()
cd(session_dir)
reload_module({ file = 'session_a', directory = '' })
eq(child.lua_get('MiniSessions.detected.session_a.type'), 'local')
child.lua([[MiniSessions.delete('session_a')]])
local path = make_path(session_dir, 'session_a')
eq(child.fn.filereadable(path), 0)
end
T['delete()']['deletes from global directory'] = function()
local session_dir = populate_sessions()
reload_module({ file = '', directory = session_dir })
eq(child.lua_get('MiniSessions.detected.session_a.type'), 'global')
child.lua([[MiniSessions.delete('session_a')]])
local path = make_path(session_dir, 'session_a')
eq(child.fn.filereadable(path), 0)
end
T['delete()']['makes detected sessions up to date'] = function()
local new_session = 'tests/dir-sessions/global/new_session'
MiniTest.finally(function() vim.fn.delete(new_session) end)
-- Detect sessions without new session
reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
eq(child.lua_get('MiniSessions.detected.new_session == nil'), true)
-- Create new session file manually and try to delete it directly without
-- reloading whole module.
child.fn.writefile({ 'lua _G.session_file = ' .. vim.inspect(new_session) }, new_session)
child.lua([[MiniSessions.delete('new_session')]])
eq(child.fn.filereadable(new_session), 0)
end
T['delete()']['respects `force` from `config` and `opts` argument'] = function()
local session_dir = populate_sessions()
reload_module({ directory = session_dir, force = { delete = true } })
local path
-- Should allow deleting current session if `force` is `false`
child.lua([[MiniSessions.read('session_a')]])
path = make_path(session_dir, 'session_a')
eq(child.v.this_session, path)
child.lua([[MiniSessions.delete('session_a')]])
eq(child.fn.filereadable(path), 0)
-- Should prefer `opts` over `config`
child.lua([[MiniSessions.read('session_b')]])
path = make_path(session_dir, 'session_b')
eq(child.v.this_session, path)
expect.error(
function() child.lua([[MiniSessions.delete('session_b', { force = false })]]) end,
[[%(mini%.sessions%) Can't delete current session]]
)
eq(child.fn.filereadable(path), 1)
end
T['delete()']['respects hooks from `config` and `opts` argument'] = new_set({
parametrize = { { 'pre' }, { 'post' } },
}, {
test = function(pre_post)
local session_dir = populate_sessions()
local path
-- Should use `config`
local hook_string_config = make_hook_string(pre_post, 'delete', 'config')
reload_from_strconfig({ directory = vim.inspect(session_dir), hooks = hook_string_config })
child.lua([[MiniSessions.delete('session_a')]])
path = make_path(session_dir, 'session_a')
eq(child.fn.filereadable(path), 0)
validate_executed_hook(pre_post, 'delete', 'config')
-- Should prefer `opts` over `config`
local hook_string_opts = make_hook_string(pre_post, 'delete', 'opts')
child.lua(([[MiniSessions.delete('session_b', { hooks = %s })]]):format(hook_string_opts))
path = make_path(session_dir, 'session_b')
eq(child.fn.filereadable(path), 0)
validate_executed_hook(pre_post, 'delete', 'opts')
end,
})
T['delete()']['respects `verbose` from `config` and `opts` argument'] = function()
local session_dir = populate_sessions()
reload_module({ directory = session_dir, verbose = { delete = false } })
local msg_pattern = '%(mini%.sessions%) Deleted session.*'
local path
-- Should not give message about deleted session
child.lua([[MiniSessions.delete('session_a')]])
path = make_path(session_dir, 'session_a')
eq(child.fn.filereadable(path), 0)
expect.no_match(get_latest_message(), msg_pattern .. 'session_a')
-- Should prefer `opts` over `config`
child.lua([[MiniSessions.delete('session_b', { verbose = true })]])
path = make_path(session_dir, 'session_b')
eq(child.fn.filereadable(path), 0)
expect.match(get_latest_message(), msg_pattern .. 'session_b')
end
T['delete()']['respects `vim.{g,b}.minisessions_disable`'] = new_set({
parametrize = { { 'g' }, { 'b' } },
}, {
test = function(var_type)
local session_dir = populate_sessions()
reload_module({ directory = session_dir })
local path = make_path(session_dir, 'session_a')
child[var_type].minisessions_disable = true
if child.fn.filereadable(path) == 0 then populate_sessions() end
child.lua([[MiniSessions.delete('session_a')]])
eq(child.fn.filereadable(path), 1)
end,
})
T['restart()'] = new_set({
hooks = {
pre_case = function()
if child.fn.has('nvim-0.12') == 0 then
MiniTest.skip('`MiniSessions.restart()` requires `:restart` from Neovim>=0.12')
end
-- Attach a UI since it makes easier dealing with `:restart`
child.api.nvim_ui_attach(child.o.columns, child.o.lines, { rgb = true })
end,
post_case = function() pcall(vim.fn.delete, 'track-vim-cmd') end,
},
})
local restart = function(vimrc, restart_cmd)
-- Monkey-patch `vim.cmd` inside child process to intercept `:restart` args
child.lua([[
vim.fn.writefile({}, 'track-vim-cmd')
_G.cmd_orig = vim.cmd
vim.cmd = function(command)
-- Log into the file to be available even after child is stopped
vim.fn.writefile({ command }, 'track-vim-cmd', 'a')
_G.cmd_orig(command)
end
]])
-- Restart within the child. It disconnects with "ch xxx closed by the peer"
-- error, so gather the "aftercommand" passed to `:restart` to execute it by
-- hand after setting up new child. It might be improved on later versions.
local ok, msg = pcall(child.lua, restart_cmd or 'MiniSessions.restart()')
-- Propagate unexpected error after a cleanup
if not (ok or vim.endswith(msg, 'closed by the peer')) then
child.lua('vim.cmd = _G.cmd_orig')
child.fn.delete('track-vim-cmd')
error(msg)
end
vim.loop.sleep(10 * small_time)
local cmd_after_restart
for _, l in ipairs(vim.fn.readfile('track-vim-cmd')) do
cmd_after_restart = cmd_after_restart or l:match('^restart!? (.*)$')
end
if cmd_after_restart == nil then error('Could not detect restart "after" command') end
-- Mock `vim.notify` to test notification
local mock_notify_cmd = 'lua _G.notify_log={}; vim.notify=function(...) table.insert(_G.notify_log, {...}) end'
local args = { '-u', vimrc or 'scripts/minimal_init.lua', '-c', mock_notify_cmd, '-c', cmd_after_restart }
child.restart(args)
end
local setup_cur_session = function()
child.cmd('edit aaa | edit tests/dir-sessions/file')
local buf_names_expected = get_buf_names()
local lines_expected = child.get_lines()
child.set_cursor(2, 2)