This repository has been archived by the owner on Jun 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
tests.py
633 lines (525 loc) · 15 KB
/
tests.py
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
import os
from os.path import join, dirname, abspath, exists
import tempfile
import sys
import unittest
import sh
import json
import codecs
import re
THIS_DIR = dirname(abspath(__file__))
SNAKE_DIR = join(THIS_DIR, "plugin")
# as distinguished from the python *vim* is running
TEST_IS_PY3 = sys.version_info[0] == 3
version_str = sh.vim(version=True).strip()
VIM_IS_PY3 = "+python3" in version_str
PYTHON_CMD = "python3" if VIM_IS_PY3 else "python"
def create_tmp_file(code, prefix="tmp", delete=True):
""" creates a temporary test file that lives on disk, on which we can run
python with sh """
py = tempfile.NamedTemporaryFile(prefix=prefix, delete=delete)
if TEST_IS_PY3:
code = bytes(code, "UTF-8")
py.write(code)
py.flush()
# we don't explicitly close, because close will remove the file, and we
# don't want that until the test case is done. so we let the gc close it
# when it goes out of scope
return py
VIMRC = create_tmp_file(r"""
let mapleader = ","
set clipboard=unnamed
set t_vb=ERROR
source {SNAKE_DIR}/prelude.vim
{PYTHON_CMD} << EOF
import sys
from os.path import expanduser
sys.path.insert(0, "{SNAKE_DIR}")
import snake
""".format(PYTHON_CMD=PYTHON_CMD, SNAKE_DIR=SNAKE_DIR))
def run_vim(script, input_str=None, vimrc=VIMRC.name, commands=None):
# we can't use a real fifo because it will block on opening, because one
# side will wait for the other side to open before unblocking
fifo = tempfile.NamedTemporaryFile(delete=True, mode="w+b")
# we do some super ugly stuff and wrap our script in some helpers, namely a
# helper to send output from our snake script to our test
script = """
{PYTHON_CMD} << EOF
import json
from snake import *
def send(stuff):
with open("{fifo_filename}", "w") as output:
json.dump(stuff, output)
{script}
EOF
""".format(PYTHON_CMD=PYTHON_CMD, script=script, fifo_filename=fifo.name)
script_file = create_tmp_file(script)
input_file = create_tmp_file(input_str or "")
# use our custom vimrc, use binary mode (dont add newlines automatically),
# and load script_file as our script to run
args = ["-N", "-n", "-i", "NONE", "-u", vimrc, "-S", script_file.name, "-b"]
# sometimes we need to specify our own commands, but most times not
if commands is None:
commands = []
#commands = ["exec 'silent !echo '. errmsg"]
# save and exit
commands.append("wqa!")
for command in commands:
args.extend(["-c", command])
args.append(input_file.name)
env = os.environ.copy()
env["LOAD_VIMPY"] = "0"
p = sh.vim(*args, _tty_in=True, _env=env)
err = output = p.stdout
input_file.seek(0)
changed = input_file.read().decode("utf8")
sent_data = fifo.read()
if sent_data:
output = json.loads(sent_data)
else:
output = None
return changed, output
class VimTests(unittest.TestCase):
def setUp(self):
self.sample_text = "The quick brown fox jumps over the lazy dog"
self.sample_block = """
Hail Mary, full of grace.
The Lord is with thee.
Blessed art thou amongst women,
and blessed is the fruit of thy womb, Jesus.
Holy Mary, Mother of God,
pray for us sinners,
now and at the hour of our death.
Amen.
""".strip()
class Tests(VimTests):
def test_replace_word(self):
script = """
replace_word("Test")
keys("3w")
replace_word("awesome")
"""
changed, output = run_vim(script, self.sample_text)
self.assertEqual(changed, "Test quick brown awesome jumps over the lazy dog")
def test_get_in_quotes(self):
script = r"""
keys("^4w")
double = get_in_quotes()
keys("$2b")
single = get_in_quotes()
send([double, single])
"""
changed, output = run_vim(script, """something in "double quotes" and \
something in 'single quotes'""")
self.assertEqual(output, ["double quotes", "single quotes"])
def test_get_word(self):
script = r"""
keys("^5w")
over = get_word()
send(over)
"""
changed, output = run_vim(script, self.sample_text)
self.assertEqual(output, "over")
def test_delete_word(self):
script = r"""
keys("^5w")
delete_word()
"""
changed, output = run_vim(script, self.sample_text)
self.assertEqual(changed, "The quick brown fox jumps the lazy dog")
def test_set_buffer_contents(self):
script = r"""
buf = get_current_buffer()
set_buffer_contents(buf, "new stuff")
"""
changed, output = run_vim(script, self.sample_text)
self.assertEqual(changed, "new stuff")
def test_abbrev(self):
script = r"""
abbrev("abc", "123")
keys("iabc\<C-]>")
"""
changed, output = run_vim(script)
self.assertEqual(changed, "123\n")
def test_abbrev_fn(self):
script = r"""
def create_inc():
i = [0]
def inc():
i[0] += 1
return i[0]
return inc
abbrev("abc", create_inc())
keys("iabc\<C-]> abc\<C-]>")
"""
changed, output = run_vim(script)
self.assertEqual(changed, "1 2\n")
def test_num_lines(self):
script = r"""
send(get_num_lines())
"""
_, output = run_vim(script, self.sample_block)
self.assertEqual(output, 8)
def test_last_line(self):
script = r"""
keys("gg")
test1 = is_last_line()
keys("G")
test2 = is_last_line()
send([test1, test2])
"""
_, output = run_vim(script, self.sample_block)
self.assertFalse(output[0])
self.assertTrue(output[1])
def test_preserve_cursor(self):
script = r"""
keys("gg^w")
with preserve_cursor():
keys("jj^w")
word1 = get_word()
word2 = get_word()
send([word1, word2])
"""
_, output = run_vim(script, self.sample_block)
self.assertEqual(output[0], "art")
self.assertEqual(output[1], "Mary")
def test_preserve_mode(self):
script = r"""
mode1 = get_mode()
with preserve_mode():
keys("v")
mode2 = get_mode()
mode3 = get_mode()
keys("V")
mode4 = get_mode()
with preserve_mode():
keys("\<esc>")
mode5 = get_mode()
mode6 = get_mode()
send([mode1, mode2, mode3, mode4, mode5, mode6])
"""
_, modes = run_vim(script, self.sample_block)
self.assertEqual(modes, ["n", "v", "n", "V", "n", "V"])
def test_search(self):
script = r"""
search("Mary")
word1 = get_word()
pos1 = get_cursor_position()
search("Mary")
word2 = get_word()
pos2 = get_cursor_position()
send([(word1, pos1), (word2, pos2)])
"""
_, output = run_vim(script, self.sample_block)
self.assertEqual(output, [["Mary", [1, 6]], ["Mary", [5, 6]]])
def test_search_double_quote(self):
script = r"""
keys("^")
search('"')
pos = get_cursor_position()
send(pos)
"""
_, output = run_vim(script, "once \"upon a ' time")
self.assertEqual(output, [1, 6])
def test_search_single_quote(self):
script = r"""
keys("^")
search("'")
pos = get_cursor_position()
send(pos)
"""
_, output = run_vim(script, "once \"upon a ' time")
self.assertEqual(output, [1, 14])
def test_filetype(self):
script = r"""
called = 0
@when_buffer_is("text")
def hooks(ctx):
global called
called += 1
count1 = called
set_option("filetype", "python")
count2 = called
set_option("filetype", "text")
count3 = called
send([count1, count2, count3])
"""
_, output = run_vim(script, self.sample_text)
self.assertEqual(output, [0, 0, 1])
def test_current_file(self):
script = r"""
send(get_current_file())
"""
_, output = run_vim(script)
self.assertEqual(tempfile.gettempdir(), dirname(output))
class VisualTests(VimTests):
def test_cursor_position(self):
script = r"""
data = []
keys("gg^")
data.append(get_cursor_position())
keys("llj")
data.append(get_cursor_position())
send(data)
"""
changed, output = run_vim(script, self.sample_block)
self.assertEqual(output, [[1,1], [2,3]])
def test_cursor_set_pos(self):
script = r"""
keys("gg^l")
p1 = get_cursor_position()
keys("G$")
eof = get_cursor_position()
set_cursor_position(p1)
p2 = get_cursor_position()
send(p1 == p2 and p1 != eof)
"""
changed, output = run_vim(script, self.sample_block)
self.assertTrue(output)
def test_get_visual_range(self):
script = r"""
keys("ggllvjjl")
keys("\<esc>")
pos = get_visual_range()
send([pos, get_mode()])
"""
changed, output = run_vim(script, self.sample_block)
((start_row, start_col), (end_row, end_col)), mode = output
self.assertEqual(start_row, 1)
self.assertEqual(start_col, 3)
self.assertEqual(end_row, 3)
self.assertEqual(end_col, 4)
self.assertEqual(mode, "n")
def test_get_visual_selection(self):
script = r"""
keys("ggllvjjl")
keys("\<esc>")
send([get_visual_selection(), get_mode()])
"""
changed, output = run_vim(script, self.sample_block)
output, mode = output
self.assertEqual(mode, "n")
self.assertEqual(output, "il Mary, full of grace.\nThe Lord is with \
thee.\nBles")
def test_replace_visual_selection(self):
script = r"""
keys("wwvee")
replace_visual_selection("awesome dude")
"""
changed, output = run_vim(script, self.sample_text)
self.assertEqual(changed, "The quick awesome dude jumps over the lazy \
dog")
class KeyMapTests(VimTests):
def test_leader(self):
script = r"""
def side_effect():
send(True)
key_map("<leader>a", side_effect)
keys("\<leader>a")
"""
changed, output = run_vim(script)
self.assertTrue(output)
def test_key_map_fn(self):
script = r"""
called = 0
def side_effect():
global called
called += 1
key_map("a", side_effect)
keys("aaa")
send(called)
"""
changed, output = run_vim(script)
self.assertEqual(output, 3)
def test_key_map_decorator(self):
script = r"""
called = 0
@key_map("a")
def side_effect():
global called
called += 1
keys("aaaa")
send(called)
"""
changed, output = run_vim(script)
self.assertEqual(output, 4)
def test_visual_key_map(self):
script = r"""
def process(stuff):
send(stuff)
return "really fast"
visual_key_map("a", process)
keys("Wviwa")
"""
changed, output = run_vim(script, self.sample_text)
self.assertEqual(output, "quick")
self.assertEqual(changed, "The really fast brown fox jumps over the lazy dog")
class OptionsTests(VimTests):
def test_get_set_value(self):
script = r"""
o1 = int(get_option("tw"))
set_option("tw", 80)
o2 = int(get_option("tw"))
send([o1, o2])
"""
_, output = run_vim(script)
self.assertEqual(output, [0, 80])
def test_get_set_flag(self):
script = r"""
o1 = int(get_option("tw"))
set_option("tw", 80)
o2 = int(get_option("tw"))
send([o1, o2])
"""
_, output = run_vim(script)
self.assertEqual(output, [0, 80])
class VariableTests(VimTests):
def test_let(self):
script = r"""
var_name = "some_var"
orig = get(var_name)
let(var_name, "testing")
new = get(var_name)
send({
"original": orig,
"new": new,
})
"""
_, output = run_vim(script)
self.assertEqual(output["original"], None)
self.assertEqual(output["new"], "testing")
def test_multi_let(self):
script = r"""
multi_let(
"test",
a="1",
b="2",
c="3"
)
send({
"a": get("a", "test"),
"b": get("b", "test"),
"c": get("c", "test"),
})
"""
_, output = run_vim(script)
self.assertEqual(output["a"], "1")
self.assertEqual(output["b"], "2")
self.assertEqual(output["c"], "3")
class RegisterTests(VimTests):
def test_get_set_register(self):
script = r"""
original = get_register("a")
set_register("a", "register a is set")
set_register("b", "register b is set")
new = get_register("a")
send({
"original": original,
"new": new,
})
"""
_, output = run_vim(script)
self.assertEqual(output["original"], None)
self.assertEqual(output["new"], "register a is set")
def test_clear_registers(self):
script = r"""
set_register("a", "register a is set")
set_register("b", "register b is set")
set_register("c", "register c is set")
a = get_register("a")
b = get_register("b")
c = get_register("c")
clear_register("a")
clear_register("b")
new_a = get_register("a")
new_b = get_register("b")
new_c = get_register("c")
send({
"a": a,
"b": b,
"c": c,
"new_a": new_a,
"new_b": new_b,
"new_c": new_c,
})
"""
_, output = run_vim(script)
self.assertEqual(output["a"], "register a is set")
self.assertEqual(output["b"], "register b is set")
self.assertEqual(output["c"], "register c is set")
self.assertEqual(output["new_a"], None)
self.assertEqual(output["new_b"], None)
self.assertEqual(output["new_c"], "register c is set")
def test_preserve_registers(self):
script = r"""
data = {}
with preserve_registers("a"):
set_register("a", "123")
data["preserved_a"] = get_register("a")
set_register("a", "not preserved")
set_register("b", "i'll be preserved tho")
with preserve_registers("b"):
set_register("a", "123")
set_register("b", "456")
data["not_preserved_a"] = get_register("a")
data["preserved_b"] = get_register("b")
send(data)
"""
_, output = run_vim(script)
self.assertEqual(output["preserved_a"], None)
self.assertEqual(output["not_preserved_a"], "123")
self.assertEqual(output["preserved_b"], "i'll be preserved tho")
class BufferTests(VimTests):
def test_new_buffer(self):
script = r"""
buf1 = get_current_buffer()
num1 = get_num_buffers()
n = new_buffer("test")
buf2 = get_current_buffer()
num2 = get_num_buffers()
set_buffer(n)
buf3 = get_current_buffer()
send([buf1, num1, buf2, num2, buf3])
"""
changed, output = run_vim(script, self.sample_text, commands=["qa!"])
self.assertEqual(output, [1, 1, 1, 2, 2])
def test_get_buffers(self):
script = r"""
new_buffer("test1")
new_buffer("test2")
send(get_buffers())
"""
changed, output = run_vim(script, self.sample_text, commands=["qa!"])
del output["1"]["name"]
self.assertDictEqual(output, {
"1": {'flags': {'active': True,
'alternate': False,
'current': True,
'errors': False,
'hidden': False,
'modified': False,
'readonly': False,
'unlisted': False},
},
"2": {'flags': {'active': False,
'alternate': False,
'current': False,
'errors': False,
'hidden': True,
'modified': False,
'readonly': False,
'unlisted': False},
'name': 'test1'},
"3": {'flags': {'active': False,
'alternate': True,
'current': False,
'errors': False,
'hidden': True,
'modified': False,
'readonly': False,
'unlisted': False},
'name': 'test2'}
})
if __name__ == "__main__":
print(sh.vim(version=True))
unittest.main(verbosity=2)