aboutsummaryrefslogtreecommitdiff
path: root/test/functional/core/job_spec.lua
blob: 618c2945665ceafc4ec2c536249289672b4227e4 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
local t = require('test.testutil')
local n = require('test.functional.testnvim')()
local Screen = require('test.functional.ui.screen')
local tt = require('test.functional.testterm')

local clear = n.clear
local eq = t.eq
local eval = n.eval
local exc_exec = n.exc_exec
local feed_command = n.feed_command
local feed = n.feed
local insert = n.insert
local neq = t.neq
local next_msg = n.next_msg
local testprg = n.testprg
local ok = t.ok
local source = n.source
local write_file = t.write_file
local mkdir = t.mkdir
local rmdir = n.rmdir
local assert_alive = n.assert_alive
local command = n.command
local fn = n.fn
local os_kill = n.os_kill
local retry = t.retry
local api = n.api
local NIL = vim.NIL
local poke_eventloop = n.poke_eventloop
local get_pathsep = n.get_pathsep
local pathroot = n.pathroot
local exec_lua = n.exec_lua
local nvim_set = n.nvim_set
local expect_twostreams = n.expect_twostreams
local expect_msg_seq = n.expect_msg_seq
local pcall_err = t.pcall_err
local matches = t.matches
local skip = t.skip
local is_os = t.is_os

describe('jobs', function()
  local channel

  before_each(function()
    clear()

    channel = api.nvim_get_chan_info(0).id
    api.nvim_set_var('channel', channel)
    source([[
    function! Normalize(data) abort
      " Windows: remove ^M and term escape sequences
      return type([]) == type(a:data)
        \ ? map(a:data, 'substitute(substitute(v:val, "\r", "", "g"), "\x1b\\%(\\]\\d\\+;.\\{-}\x07\\|\\[.\\{-}[\x40-\x7E]\\)", "", "g")')
        \ : a:data
    endfunction
    function! OnEvent(id, data, event) dict
      let userdata = get(self, 'user')
      let data     = Normalize(a:data)
      call rpcnotify(g:channel, a:event, userdata, data)
    endfunction
    let g:job_opts = {
    \ 'on_stdout': function('OnEvent'),
    \ 'on_exit': function('OnEvent'),
    \ 'user': 0
    \ }
    ]])
  end)

  it('must specify env option as a dict', function()
    command('let g:job_opts.env = v:true')
    local _, err = pcall(function()
      if is_os('win') then
        command("let j = jobstart('set', g:job_opts)")
      else
        command("let j = jobstart('env', g:job_opts)")
      end
    end)
    matches('E475: Invalid argument: env', err)
  end)

  it('append environment #env', function()
    command("let $VAR = 'abc'")
    command("let $TOTO = 'goodbye world'")
    command("let g:job_opts.env = {'TOTO': 'hello world'}")
    if is_os('win') then
      command([[call jobstart('echo %TOTO% %VAR%', g:job_opts)]])
    else
      command([[call jobstart('echo $TOTO $VAR', g:job_opts)]])
    end

    expect_msg_seq({
      { 'notification', 'stdout', { 0, { 'hello world abc' } } },
      { 'notification', 'stdout', { 0, { '', '' } } },
    }, {
      { 'notification', 'stdout', { 0, { 'hello world abc', '' } } },
      { 'notification', 'stdout', { 0, { '' } } },
    })
  end)

  it('append environment with pty #env', function()
    command("let $VAR = 'abc'")
    command("let $TOTO = 'goodbye world'")
    command('let g:job_opts.pty = v:true')
    command("let g:job_opts.env = {'TOTO': 'hello world'}")
    if is_os('win') then
      command([[call jobstart('echo %TOTO% %VAR%', g:job_opts)]])
    else
      command([[call jobstart('echo $TOTO $VAR', g:job_opts)]])
    end
    expect_msg_seq({
      { 'notification', 'stdout', { 0, { 'hello world abc' } } },
      { 'notification', 'stdout', { 0, { '', '' } } },
    }, {
      { 'notification', 'stdout', { 0, { 'hello world abc', '' } } },
      { 'notification', 'stdout', { 0, { '' } } },
    })
  end)

  it('replace environment #env', function()
    command("let $VAR = 'abc'")
    command("let $TOTO = 'goodbye world'")
    command("let g:job_opts.env = {'TOTO': 'hello world'}")
    command('let g:job_opts.clear_env = 1')

    -- libuv ensures that certain "required" environment variables are
    -- preserved if the user doesn't provide them in a custom environment
    -- https://github.com/libuv/libuv/blob/635e0ce6073c5fbc96040e336b364c061441b54b/src/win/process.c#L672
    -- https://github.com/libuv/libuv/blob/635e0ce6073c5fbc96040e336b364c061441b54b/src/win/process.c#L48-L60
    --
    -- Rather than expecting a completely empty environment, ensure that $VAR
    -- is *not* in the environment but $TOTO is.
    if is_os('win') then
      command([[call jobstart('echo %TOTO% %VAR%', g:job_opts)]])
      expect_msg_seq({
        { 'notification', 'stdout', { 0, { 'hello world %VAR%', '' } } },
      })
    else
      command('set shell=/bin/sh')
      command([[call jobstart('echo $TOTO $VAR', g:job_opts)]])
      expect_msg_seq({
        { 'notification', 'stdout', { 0, { 'hello world', '' } } },
      })
    end
  end)

  it('handles case-insensitively matching #env vars', function()
    command("let $TOTO = 'abc'")
    -- Since $Toto is being set in the job, it should take precedence over the
    -- global $TOTO on Windows
    command("let g:job_opts = {'env': {'Toto': 'def'}, 'stdout_buffered': v:true}")
    if is_os('win') then
      command([[let j = jobstart('set | find /I "toto="', g:job_opts)]])
    else
      command([[let j = jobstart('env | grep -i toto=', g:job_opts)]])
    end
    command('call jobwait([j])')
    command('let g:output = Normalize(g:job_opts.stdout)')
    local actual = eval('g:output')
    local expected
    if is_os('win') then
      -- Toto is normalized to TOTO so we can detect duplicates, and because
      -- Windows doesn't care about case
      expected = { 'TOTO=def', '' }
    else
      expected = { 'TOTO=abc', 'Toto=def', '' }
    end
    table.sort(actual)
    table.sort(expected)
    eq(expected, actual)
  end)

  it('uses &shell and &shellcmdflag if passed a string', function()
    command("let $VAR = 'abc'")
    if is_os('win') then
      command("let j = jobstart('echo %VAR%', g:job_opts)")
    else
      command("let j = jobstart('echo $VAR', g:job_opts)")
    end
    eq({ 'notification', 'stdout', { 0, { 'abc', '' } } }, next_msg())
    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
  end)

  it('changes to given / directory', function()
    command("let g:job_opts.cwd = '/'")
    if is_os('win') then
      command("let j = jobstart('cd', g:job_opts)")
    else
      command("let j = jobstart('pwd', g:job_opts)")
    end
    eq({ 'notification', 'stdout', { 0, { pathroot(), '' } } }, next_msg())
    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
  end)

  it('changes to given `cwd` directory', function()
    local dir = eval('resolve(tempname())'):gsub('/', get_pathsep())
    mkdir(dir)
    command("let g:job_opts.cwd = '" .. dir .. "'")
    if is_os('win') then
      command("let j = jobstart('cd', g:job_opts)")
    else
      command("let j = jobstart('pwd', g:job_opts)")
    end
    expect_msg_seq(
      {
        { 'notification', 'stdout', { 0, { dir, '' } } },
        { 'notification', 'stdout', { 0, { '' } } },
        { 'notification', 'exit', { 0, 0 } },
      },
      -- Alternative sequence:
      {
        { 'notification', 'stdout', { 0, { dir } } },
        { 'notification', 'stdout', { 0, { '', '' } } },
        { 'notification', 'stdout', { 0, { '' } } },
        { 'notification', 'exit', { 0, 0 } },
      }
    )
    rmdir(dir)
  end)

  it('fails to change to invalid `cwd`', function()
    local dir = eval('resolve(tempname())."-bogus"')
    local _, err = pcall(function()
      command("let g:job_opts.cwd = '" .. dir .. "'")
      if is_os('win') then
        command("let j = jobstart('cd', g:job_opts)")
      else
        command("let j = jobstart('pwd', g:job_opts)")
      end
    end)
    matches('E475: Invalid argument: expected valid directory$', err)
  end)

  it('error on non-executable `cwd`', function()
    skip(is_os('win'), 'Not applicable for Windows')

    local dir = 'Xtest_not_executable_dir'
    mkdir(dir)
    fn.setfperm(dir, 'rw-------')
    matches(
      '^Vim%(call%):E903: Process failed to start: permission denied: .*',
      pcall_err(command, "call jobstart(['pwd'], {'cwd': '" .. dir .. "'})")
    )
    rmdir(dir)
  end)

  it('returns 0 when it fails to start', function()
    eq('', eval('v:errmsg'))
    feed_command('let g:test_jobid = jobstart([])')
    eq(0, eval('g:test_jobid'))
    eq('E474:', string.match(eval('v:errmsg'), 'E%d*:'))
  end)

  it('returns -1 when target is not executable #5465', function()
    local function new_job()
      return eval([[jobstart('')]])
    end
    local executable_jobid = new_job()

    local exe = is_os('win') and './test/functional/fixtures'
      or './test/functional/fixtures/non_executable.txt'
    eq(
      "Vim:E475: Invalid value for argument cmd: '" .. exe .. "' is not executable",
      pcall_err(eval, "jobstart(['" .. exe .. "'])")
    )
    eq('', eval('v:errmsg'))
    -- Non-executable job should not increment the job ids. #5465
    eq(executable_jobid + 1, new_job())
  end)

  it('invokes callbacks when the job writes and exits', function()
    command("let g:job_opts.on_stderr  = function('OnEvent')")
    command([[call jobstart(has('win32') ? 'echo:' : 'echo', g:job_opts)]])
    expect_twostreams({
      { 'notification', 'stdout', { 0, { '', '' } } },
      { 'notification', 'stdout', { 0, { '' } } },
    }, { { 'notification', 'stderr', { 0, { '' } } } })
    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
  end)

  it('interactive commands', function()
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    neq(0, eval('j'))
    command('call jobsend(j, "abc\\n")')
    eq({ 'notification', 'stdout', { 0, { 'abc', '' } } }, next_msg())
    command('call jobsend(j, "123\\nxyz\\n")')
    expect_msg_seq(
      { { 'notification', 'stdout', { 0, { '123', 'xyz', '' } } } },
      -- Alternative sequence:
      {
        { 'notification', 'stdout', { 0, { '123', '' } } },
        { 'notification', 'stdout', { 0, { 'xyz', '' } } },
      }
    )
    command('call jobsend(j, [123, "xyz", ""])')
    expect_msg_seq(
      { { 'notification', 'stdout', { 0, { '123', 'xyz', '' } } } },
      -- Alternative sequence:
      {
        { 'notification', 'stdout', { 0, { '123', '' } } },
        { 'notification', 'stdout', { 0, { 'xyz', '' } } },
      }
    )
    command('call jobstop(j)')
    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
  end)

  it('preserves NULs', function()
    -- Make a file with NULs in it.
    local filename = t.tmpname()
    write_file(filename, 'abc\0def\n')

    command("let j = jobstart(['cat', '" .. filename .. "'], g:job_opts)")
    eq({ 'notification', 'stdout', { 0, { 'abc\ndef', '' } } }, next_msg())
    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
    os.remove(filename)

    -- jobsend() preserves NULs.
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    command([[call jobsend(j, ["123\n456",""])]])
    eq({ 'notification', 'stdout', { 0, { '123\n456', '' } } }, next_msg())
    command('call jobstop(j)')
  end)

  it('emits partial lines (does NOT buffer data lacking newlines)', function()
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    command('call jobsend(j, "abc\\nxyz")')
    eq({ 'notification', 'stdout', { 0, { 'abc', 'xyz' } } }, next_msg())
    command('call jobstop(j)')
    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
  end)

  it('preserves newlines', function()
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    command('call jobsend(j, "a\\n\\nc\\n\\n\\n\\nb\\n\\n")')
    eq({ 'notification', 'stdout', { 0, { 'a', '', 'c', '', '', '', 'b', '', '' } } }, next_msg())
  end)

  it('preserves NULs', function()
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    command('call jobsend(j, ["\n123\n", "abc\\nxyz\n", ""])')
    eq({ 'notification', 'stdout', { 0, { '\n123\n', 'abc\nxyz\n', '' } } }, next_msg())
    command('call jobstop(j)')
    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
  end)

  it('avoids sending final newline', function()
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    command('call jobsend(j, ["some data", "without\nfinal nl"])')
    eq({ 'notification', 'stdout', { 0, { 'some data', 'without\nfinal nl' } } }, next_msg())
    command('call jobstop(j)')
    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
  end)

  it('closes the job streams with jobclose', function()
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    command('call jobclose(j, "stdin")')
    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
  end)

  it('disallows jobsend on a job that closed stdin', function()
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    command('call jobclose(j, "stdin")')
    eq(
      false,
      pcall(function()
        command('call jobsend(j, ["some data"])')
      end)
    )

    command("let g:job_opts.stdin = 'null'")
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    eq(
      false,
      pcall(function()
        command('call jobsend(j, ["some data"])')
      end)
    )
  end)

  it('disallows jobsend on a non-existent job', function()
    eq(false, pcall(eval, "jobsend(-1, 'lol')"))
    eq(0, eval('jobstop(-1)'))
  end)

  it('jobstop twice on the stopped or exited job return 0', function()
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    neq(0, eval('j'))
    eq(1, eval('jobstop(j)'))
    eq(0, eval('jobstop(j)'))
  end)

  it('will not leak memory if we leave a job running', function()
    command("call jobstart(['cat', '-'], g:job_opts)")
  end)

  it('can get the pid value using getpid', function()
    command("let j =  jobstart(['cat', '-'], g:job_opts)")
    local pid = eval('jobpid(j)')
    neq(NIL, api.nvim_get_proc(pid))
    command('call jobstop(j)')
    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
    eq(NIL, api.nvim_get_proc(pid))
  end)

  it('disposed on Nvim exit', function()
    -- use sleep, which doesn't die on stdin close
    command(
      "let g:j =  jobstart(has('win32') ? ['ping', '-n', '1001', '127.0.0.1'] : ['sleep', '1000'], g:job_opts)"
    )
    local pid = eval('jobpid(g:j)')
    neq(NIL, api.nvim_get_proc(pid))
    clear()
    eq(NIL, api.nvim_get_proc(pid))
  end)

  it('can survive the exit of nvim with "detach"', function()
    command('let g:job_opts.detach = 1')
    command(
      "let g:j = jobstart(has('win32') ? ['ping', '-n', '1001', '127.0.0.1'] : ['sleep', '1000'], g:job_opts)"
    )
    local pid = eval('jobpid(g:j)')
    neq(NIL, api.nvim_get_proc(pid))
    clear()
    neq(NIL, api.nvim_get_proc(pid))
    -- clean up after ourselves
    eq(0, os_kill(pid))
  end)

  it('can pass user data to the callback', function()
    command('let g:job_opts.user = {"n": 5, "s": "str", "l": [1]}')
    command([[call jobstart('echo foo', g:job_opts)]])
    local data = { n = 5, s = 'str', l = { 1 } }
    expect_msg_seq(
      {
        { 'notification', 'stdout', { data, { 'foo', '' } } },
        { 'notification', 'stdout', { data, { '' } } },
      },
      -- Alternative sequence:
      {
        { 'notification', 'stdout', { data, { 'foo' } } },
        { 'notification', 'stdout', { data, { '', '' } } },
        { 'notification', 'stdout', { data, { '' } } },
      }
    )
    eq({ 'notification', 'exit', { data, 0 } }, next_msg())
  end)

  it('can omit data callbacks', function()
    command('unlet g:job_opts.on_stdout')
    command('let g:job_opts.user = 5')
    command([[call jobstart('echo foo', g:job_opts)]])
    eq({ 'notification', 'exit', { 5, 0 } }, next_msg())
  end)

  it('can omit exit callback', function()
    command('unlet g:job_opts.on_exit')
    command('let g:job_opts.user = 5')
    command([[call jobstart('echo foo', g:job_opts)]])
    expect_msg_seq(
      {
        { 'notification', 'stdout', { 5, { 'foo', '' } } },
        { 'notification', 'stdout', { 5, { '' } } },
      },
      -- Alternative sequence:
      {
        { 'notification', 'stdout', { 5, { 'foo' } } },
        { 'notification', 'stdout', { 5, { '', '' } } },
        { 'notification', 'stdout', { 5, { '' } } },
      }
    )
  end)

  it('will pass return code with the exit event', function()
    command('let g:job_opts.user = 5')
    command("call jobstart('exit 55', g:job_opts)")
    eq({ 'notification', 'stdout', { 5, { '' } } }, next_msg())
    eq({ 'notification', 'exit', { 5, 55 } }, next_msg())
  end)

  it('can receive dictionary functions', function()
    source([[
    let g:dict = {'id': 10}
    function g:dict.on_exit(id, code, event)
      call rpcnotify(g:channel, a:event, a:code, self.id)
    endfunction
    call jobstart('exit 45', g:dict)
    ]])
    eq({ 'notification', 'exit', { 45, 10 } }, next_msg())
  end)

  it('can redefine callbacks being used by a job', function()
    local screen = Screen.new()
    screen:set_default_attr_ids({
      [1] = { bold = true, foreground = Screen.colors.Blue },
    })
    source([[
      function! g:JobHandler(job_id, data, event)
      endfunction

      let g:callbacks = {
      \ 'on_stdout': function('g:JobHandler'),
      \ 'on_stderr': function('g:JobHandler'),
      \ 'on_exit': function('g:JobHandler')
      \ }
      let job = jobstart(['cat', '-'], g:callbacks)
    ]])
    poke_eventloop()
    source([[
      function! g:JobHandler(job_id, data, event)
      endfunction
    ]])

    eq('', eval('v:errmsg'))
  end)

  it('requires funcrefs for script-local (s:) functions', function()
    local screen = Screen.new(60, 5)
    screen:set_default_attr_ids({
      [1] = { bold = true, foreground = Screen.colors.Blue1 },
      [2] = { foreground = Screen.colors.Grey100, background = Screen.colors.Red },
      [3] = { bold = true, foreground = Screen.colors.SeaGreen4 },
    })

    -- Pass job callback names _without_ `function(...)`.
    source([[
      function! s:OnEvent(id, data, event) dict
        let g:job_result = get(self, 'user')
      endfunction
      let s:job = jobstart('echo "foo"', {
        \ 'on_stdout': 's:OnEvent',
        \ 'on_stderr': 's:OnEvent',
        \ 'on_exit':   's:OnEvent',
        \ })
    ]])

    screen:expect { any = '{2:E120: Using <SID> not in a script context: s:OnEvent}' }
  end)

  it('does not repeat output with slow output handlers', function()
    source([[
      let d = {'data': []}
      function! d.on_stdout(job, data, event) dict
        call add(self.data, Normalize(a:data))
        sleep 200m
      endfunction
      function! d.on_exit(job, data, event) dict
        let g:exit_data = copy(self.data)
      endfunction
      if has('win32')
        let cmd = 'for /L %I in (1,1,5) do @(echo %I& ping -n 2 127.0.0.1 > nul)'
      else
        let cmd = ['sh', '-c', 'for i in 1 2 3 4 5; do echo $i; sleep 0.1; done']
      endif
      let g:id = jobstart(cmd, d)
      sleep 1500m
      call jobwait([g:id])
    ]])

    local expected = { '1', '2', '3', '4', '5', '' }
    local chunks = eval('d.data')
    -- check nothing was received after exit, including EOF
    eq(eval('g:exit_data'), chunks)
    local received = { '' }
    for i, chunk in ipairs(chunks) do
      if i < #chunks then
        -- if chunks got joined, a spurious [''] callback was not sent
        neq({ '' }, chunk)
      else
        -- but EOF callback is still sent
        eq({ '' }, chunk)
      end
      received[#received] = received[#received] .. chunk[1]
      for j = 2, #chunk do
        received[#received + 1] = chunk[j]
      end
    end
    eq(expected, received)
  end)

  it('does not invoke callbacks recursively', function()
    source([[
      let d = {'data': []}
      function! d.on_stdout(job, data, event) dict
        " if callbacks were invoked recursively, this would cause on_stdout
        " to be invoked recursively and the data reversed on the call stack
        sleep 200m
        call add(self.data, Normalize(a:data))
      endfunction
      function! d.on_exit(job, data, event) dict
        let g:exit_data = copy(self.data)
      endfunction
      if has('win32')
        let cmd = 'for /L %I in (1,1,5) do @(echo %I& ping -n 2 127.0.0.1 > nul)'
      else
        let cmd = ['sh', '-c', 'for i in 1 2 3 4 5; do echo $i; sleep 0.1; done']
      endif
      let g:id = jobstart(cmd, d)
      sleep 1500m
      call jobwait([g:id])
    ]])

    local expected = { '1', '2', '3', '4', '5', '' }
    local chunks = eval('d.data')
    -- check nothing was received after exit, including EOF
    eq(eval('g:exit_data'), chunks)
    local received = { '' }
    for i, chunk in ipairs(chunks) do
      if i < #chunks then
        -- if chunks got joined, a spurious [''] callback was not sent
        neq({ '' }, chunk)
      else
        -- but EOF callback is still sent
        eq({ '' }, chunk)
      end
      received[#received] = received[#received] .. chunk[1]
      for j = 2, #chunk do
        received[#received + 1] = chunk[j]
      end
    end
    eq(expected, received)
  end)

  it('jobstart() works with partial functions', function()
    source([[
    function PrintArgs(a1, a2, id, data, event)
      " Windows: remove ^M
      let normalized = map(a:data, 'substitute(v:val, "\r", "", "g")')
      call rpcnotify(g:channel, '1', a:a1,  a:a2, normalized, a:event)
    endfunction
    let Callback = function('PrintArgs', ["foo", "bar"])
    let g:job_opts = {'on_stdout': Callback}
    call jobstart('echo some text', g:job_opts)
    ]])
    expect_msg_seq(
      { { 'notification', '1', { 'foo', 'bar', { 'some text', '' }, 'stdout' } } },
      -- Alternative sequence:
      {
        { 'notification', '1', { 'foo', 'bar', { 'some text' }, 'stdout' } },
        { 'notification', '1', { 'foo', 'bar', { '', '' }, 'stdout' } },
      }
    )
  end)

  it('jobstart() works with closures', function()
    source([[
      fun! MkFun()
          let a1 = 'foo'
          let a2 = 'bar'
          return {id, data, event -> rpcnotify(g:channel, '1', a1, a2, Normalize(data), event)}
      endfun
      let g:job_opts = {'on_stdout': MkFun()}
      call jobstart('echo some text', g:job_opts)
    ]])
    expect_msg_seq(
      { { 'notification', '1', { 'foo', 'bar', { 'some text', '' }, 'stdout' } } },
      -- Alternative sequence:
      {
        { 'notification', '1', { 'foo', 'bar', { 'some text' }, 'stdout' } },
        { 'notification', '1', { 'foo', 'bar', { '', '' }, 'stdout' } },
      }
    )
  end)

  it('jobstart() works when closure passed directly to `jobstart`', function()
    source([[
      let g:job_opts = {'on_stdout': {id, data, event -> rpcnotify(g:channel, '1', 'foo', 'bar', Normalize(data), event)}}
      call jobstart('echo some text', g:job_opts)
    ]])
    expect_msg_seq(
      { { 'notification', '1', { 'foo', 'bar', { 'some text', '' }, 'stdout' } } },
      -- Alternative sequence:
      {
        { 'notification', '1', { 'foo', 'bar', { 'some text' }, 'stdout' } },
        { 'notification', '1', { 'foo', 'bar', { '', '' }, 'stdout' } },
      }
    )
  end)

  it('jobstart() environment: $NVIM, $NVIM_LISTEN_ADDRESS #11009', function()
    local function get_env_in_child_job(envname, env)
      return exec_lua(
        [[
        local envname, env = ...
        local join = function(s) return vim.fn.join(s, '') end
        local stdout = {}
        local stderr = {}
        local opt = {
          env = env,
          stdout_buffered = true,
          stderr_buffered = true,
          on_stderr = function(chan, data, name) stderr = data end,
          on_stdout = function(chan, data, name) stdout = data end,
        }
        local j1 = vim.fn.jobstart({ vim.v.progpath, '-es', '-V1',('+echo "%s="..getenv("%s")'):format(envname, envname), '+qa!' }, opt)
        vim.fn.jobwait({ j1 }, 10000)
        return join({ join(stdout), join(stderr) })
      ]],
        envname,
        env
      )
    end

    local addr = eval('v:servername')
    ok((addr):len() > 0)
    -- $NVIM is _not_ defined in the top-level Nvim process.
    eq('', eval('$NVIM'))
    -- jobstart() shares its v:servername with the child via $NVIM.
    eq('NVIM=' .. addr, get_env_in_child_job('NVIM'))
    -- $NVIM_LISTEN_ADDRESS is unset by server_init in the child.
    eq('NVIM_LISTEN_ADDRESS=v:null', get_env_in_child_job('NVIM_LISTEN_ADDRESS'))
    eq(
      'NVIM_LISTEN_ADDRESS=v:null',
      get_env_in_child_job('NVIM_LISTEN_ADDRESS', { NVIM_LISTEN_ADDRESS = 'Xtest_jobstart_env' })
    )
    -- User can explicitly set $NVIM_LOG_FILE, $VIM, $VIMRUNTIME.
    eq(
      'NVIM_LOG_FILE=Xtest_jobstart_env',
      get_env_in_child_job('NVIM_LOG_FILE', { NVIM_LOG_FILE = 'Xtest_jobstart_env' })
    )
    os.remove('Xtest_jobstart_env')
  end)

  describe('jobwait()', function()
    before_each(function()
      if is_os('win') then
        n.set_shell_powershell()
      end
    end)

    it('returns a list of status codes', function()
      source([[
      call rpcnotify(g:channel, 'wait', jobwait(has('win32') ? [
      \  jobstart('Start-Sleep -Milliseconds 100; exit 4'),
      \  jobstart('Start-Sleep -Milliseconds 300; exit 5'),
      \  jobstart('Start-Sleep -Milliseconds 500; exit 6'),
      \  jobstart('Start-Sleep -Milliseconds 700; exit 7')
      \  ] : [
      \  jobstart('sleep 0.10; exit 4'),
      \  jobstart('sleep 0.110; exit 5'),
      \  jobstart('sleep 0.210; exit 6'),
      \  jobstart('sleep 0.310; exit 7')
      \  ]))
      ]])
      eq({ 'notification', 'wait', { { 4, 5, 6, 7 } } }, next_msg())
    end)

    it('will run callbacks while waiting', function()
      source([[
      let g:dict = {}
      let g:jobs = []
      let g:exits = []
      function g:dict.on_stdout(id, code, event) abort
        call add(g:jobs, a:id)
      endfunction
      function g:dict.on_exit(id, code, event) abort
        if a:code != 5
          throw 'Error!'
        endif
        call add(g:exits, a:id)
      endfunction
      call jobwait(has('win32') ? [
      \  jobstart('Start-Sleep -Milliseconds 100; exit 5', g:dict),
      \  jobstart('Start-Sleep -Milliseconds 300; exit 5', g:dict),
      \  jobstart('Start-Sleep -Milliseconds 500; exit 5', g:dict),
      \  jobstart('Start-Sleep -Milliseconds 700; exit 5', g:dict)
      \  ] : [
      \  jobstart('sleep 0.010; exit 5', g:dict),
      \  jobstart('sleep 0.030; exit 5', g:dict),
      \  jobstart('sleep 0.050; exit 5', g:dict),
      \  jobstart('sleep 0.070; exit 5', g:dict)
      \  ])
      call rpcnotify(g:channel, 'wait', sort(g:jobs), sort(g:exits))
      ]])
      eq({ 'notification', 'wait', { { 3, 4, 5, 6 }, { 3, 4, 5, 6 } } }, next_msg())
    end)

    it('will return status codes in the order of passed ids', function()
      source([[
      call rpcnotify(g:channel, 'wait', jobwait(has('win32') ? [
      \  jobstart('Start-Sleep -Milliseconds 700; exit 4'),
      \  jobstart('Start-Sleep -Milliseconds 500; exit 5'),
      \  jobstart('Start-Sleep -Milliseconds 300; exit 6'),
      \  jobstart('Start-Sleep -Milliseconds 100; exit 7')
      \  ] : [
      \  jobstart('sleep 0.070; exit 4'),
      \  jobstart('sleep 0.050; exit 5'),
      \  jobstart('sleep 0.030; exit 6'),
      \  jobstart('sleep 0.010; exit 7')
      \  ]))
      ]])
      eq({ 'notification', 'wait', { { 4, 5, 6, 7 } } }, next_msg())
    end)

    it('will return -3 for invalid job ids', function()
      source([[
      call rpcnotify(g:channel, 'wait', jobwait([
      \  -10,
      \  jobstart((has('win32') ? 'Start-Sleep -Milliseconds 100' : 'sleep 0.01').'; exit 5'),
      \  ]))
      ]])
      eq({ 'notification', 'wait', { { -3, 5 } } }, next_msg())
    end)

    it('will return -2 when interrupted without timeout', function()
      feed_command(
        'call rpcnotify(g:channel, "ready") | '
          .. 'call rpcnotify(g:channel, "wait", '
          .. 'jobwait([jobstart("'
          .. (is_os('win') and 'Start-Sleep 10' or 'sleep 10')
          .. '; exit 55")]))'
      )
      eq({ 'notification', 'ready', {} }, next_msg())
      feed('<c-c>')
      eq({ 'notification', 'wait', { { -2 } } }, next_msg())
    end)

    it('will return -2 when interrupted with timeout', function()
      feed_command(
        'call rpcnotify(g:channel, "ready") | '
          .. 'call rpcnotify(g:channel, "wait", '
          .. 'jobwait([jobstart("'
          .. (is_os('win') and 'Start-Sleep 10' or 'sleep 10')
          .. '; exit 55")], 10000))'
      )
      eq({ 'notification', 'ready', {} }, next_msg())
      feed('<c-c>')
      eq({ 'notification', 'wait', { { -2 } } }, next_msg())
    end)

    it('can be called recursively', function()
      source([[
      let g:opts = {}
      let g:counter = 0
      function g:opts.on_stdout(id, msg, _event)
        if self.state == 0
          if self.counter < 10
            call Run()
          endif
          let self.state = 1
          call jobsend(a:id, "line1\n")
        elseif self.state == 1
          let self.state = 2
          call jobsend(a:id, "line2\n")
        elseif self.state == 2
          let self.state = 3
          call jobsend(a:id, "line3\n")
        elseif self.state == 3
          let self.state = 4
          call rpcnotify(g:channel, 'w', printf('job %d closed', self.counter))
          call jobclose(a:id, 'stdin')
        endif
      endfunction
      function g:opts.on_exit(...)
        call rpcnotify(g:channel, 'w', printf('job %d exited', self.counter))
      endfunction
      function Run()
        let g:counter += 1
        let j = copy(g:opts)
        let j.state = 0
        let j.counter = g:counter
        call jobwait([
        \   jobstart('echo ready; cat -', j),
        \ ])
      endfunction
      ]])
      feed_command('call Run()')
      local r
      for i = 10, 1, -1 do
        r = next_msg()
        eq('job ' .. i .. ' closed', r[3][1])
        r = next_msg()
        eq('job ' .. i .. ' exited', r[3][1])
      end
      eq(10, api.nvim_eval('g:counter'))
    end)

    describe('with timeout argument', function()
      it('will return -1 if the wait timed out', function()
        source([[
        call rpcnotify(g:channel, 'wait', jobwait([
        \  jobstart((has('win32') ? 'Start-Sleep 10' : 'sleep 10').'; exit 5'),
        \  ], 100))
        ]])
        eq({ 'notification', 'wait', { { -1 } } }, next_msg())
      end)

      it('can pass 0 to check if a job exists', function()
        source([[
        call rpcnotify(g:channel, 'wait', jobwait(has('win32') ? [
        \  jobstart('Start-Sleep -Milliseconds 50; exit 4'),
        \  jobstart('Start-Sleep -Milliseconds 300; exit 5'),
        \  ] : [
        \  jobstart('sleep 0.05; exit 4'),
        \  jobstart('sleep 0.3; exit 5'),
        \  ], 0))
        ]])
        eq({ 'notification', 'wait', { { -1, -1 } } }, next_msg())
      end)
    end)

    it('hides cursor and flushes messages before blocking', function()
      local screen = Screen.new(50, 6)
      command([[let g:id = jobstart([v:progpath, '--clean', '--headless'])]])
      source([[
        func PrintAndWait()
          echon "aaa\nbbb"
          call jobwait([g:id], 300)
          echon "\nccc"
        endfunc
      ]])
      feed_command('call PrintAndWait()')
      screen:expect {
        grid = [[
                                                          |
        {1:~                                                 }|*2
        {3:                                                  }|
        aaa                                               |
        bbb                                               |
      ]],
        timeout = 100,
      }
      screen:expect {
        grid = [[
                                                          |
        {3:                                                  }|
        aaa                                               |
        bbb                                               |
        ccc                                               |
        {6:Press ENTER or type command to continue}^           |
      ]],
      }
      feed('<CR>')
      fn.jobstop(api.nvim_get_var('id'))
    end)
  end)

  pending('exit event follows stdout, stderr', function()
    command("let g:job_opts.on_stderr  = function('OnEvent')")
    command("let j = jobstart(['cat', '-'], g:job_opts)")
    api.nvim_eval('jobsend(j, "abcdef")')
    api.nvim_eval('jobstop(j)')
    expect_msg_seq(
      {
        { 'notification', 'stdout', { 0, { 'abcdef' } } },
        { 'notification', 'stdout', { 0, { '' } } },
        { 'notification', 'stderr', { 0, { '' } } },
      },
      -- Alternative sequence:
      {
        { 'notification', 'stderr', { 0, { '' } } },
        { 'notification', 'stdout', { 0, { 'abcdef' } } },
        { 'notification', 'stdout', { 0, { '' } } },
      },
      -- Alternative sequence:
      {
        { 'notification', 'stdout', { 0, { 'abcdef' } } },
        { 'notification', 'stderr', { 0, { '' } } },
        { 'notification', 'stdout', { 0, { '' } } },
      }
    )
    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
  end)

  it('cannot have both rpc and pty options', function()
    command('let g:job_opts.pty = v:true')
    command('let g:job_opts.rpc = v:true')
    local _, err = pcall(command, "let j = jobstart(['cat', '-'], g:job_opts)")
    matches("E475: Invalid argument: job cannot have both 'pty' and 'rpc' options set", err)
  end)

  it('does not crash when repeatedly failing to start shell', function()
    source([[
      set shell=nosuchshell
      func! DoIt()
        call jobstart('true')
        call jobstart('true')
      endfunc
    ]])
    -- The crash only triggered if both jobs are cleaned up on the same event
    -- loop tick. This is also prevented by try-block, so feed must be used.
    feed_command('call DoIt()')
    feed('<cr>') -- press RETURN
    assert_alive()
  end)

  it('jobstop() kills entire process tree #6530', function()
    -- XXX: Using `nvim` isn't a good test, it reaps its children on exit.
    -- local c = 'call jobstart([v:progpath, "-u", "NONE", "-i", "NONE", "--headless"])'
    -- local j = eval("jobstart([v:progpath, '-u', 'NONE', '-i', 'NONE', '--headless', '-c', '"
    --                ..c.."', '-c', '"..c.."'])")

    -- Create child with several descendants.
    if is_os('win') then
      source([[
      function! s:formatprocs(pid, prefix)
        let result = ''
        let result .= a:prefix . printf("%-24.24s%6s %12.12s %s\n",
              \                         s:procs[a:pid]['name'],
              \                         a:pid,
              \                         s:procs[a:pid]['Session Name'],
              \                         s:procs[a:pid]['Session'])
        if has_key(s:procs[a:pid], 'children')
          for pid in s:procs[a:pid]['children']
            let result .= s:formatprocs(pid, a:prefix . '  ')
          endfor
        endif
        return result
      endfunction

      function! PsTree() abort
        let s:procs = {}
        for proc in map(
              \       map(
              \         systemlist('tasklist /NH'),
              \         'substitute(v:val, "\r", "", "")'),
              \       'split(v:val, "\\s\\+")')
          if len(proc) == 6
            let s:procs[proc[1]] .. ']]' .. [[= {'name': proc[0],
                  \               'Session Name': proc[2],
                  \               'Session': proc[3]}
          endif
        endfor
        for pid in keys(s:procs)
          let children = nvim_get_proc_children(str2nr(pid))
          if !empty(children)
            let s:procs[pid]['children'] = children
            for cpid in children
              let s:procs[printf('%d', cpid)]['parent'] = str2nr(pid)
            endfor
          endif
        endfor
        let result = ''
        for pid in sort(keys(s:procs), {i1, i2 -> i1 - i2})
          if !has_key(s:procs[pid], 'parent')
            let result .= s:formatprocs(pid, '')
          endif
        endfor
        return result
      endfunction
      ]])
    end
    local sleep_cmd = (is_os('win') and 'ping -n 31 127.0.0.1' or 'sleep 30')
    local j = eval("jobstart('" .. sleep_cmd .. ' | ' .. sleep_cmd .. ' | ' .. sleep_cmd .. "')")
    local ppid = fn.jobpid(j)
    local children
    if is_os('win') then
      local status, result = pcall(retry, nil, nil, function()
        children = api.nvim_get_proc_children(ppid)
        -- On Windows conhost.exe may exist, and
        -- e.g. vctip.exe might appear.  #10783
        ok(#children >= 3 and #children <= 5)
      end)
      if not status then
        print('')
        print(eval('PsTree()'))
        error(result)
      end
    else
      retry(nil, nil, function()
        children = api.nvim_get_proc_children(ppid)
        eq(3, #children)
      end)
    end
    -- Assert that nvim_get_proc() sees the children.
    for _, child_pid in ipairs(children) do
      local info = api.nvim_get_proc(child_pid)
      -- eq((is_os('win') and 'nvim.exe' or 'nvim'), info.name)
      eq(ppid, info.ppid)
    end
    -- Kill the root of the tree.
    eq(1, fn.jobstop(j))
    -- Assert that the children were killed.
    retry(nil, nil, function()
      for _, child_pid in ipairs(children) do
        eq(NIL, api.nvim_get_proc(child_pid))
      end
    end)
  end)

  it('jobstop on same id before stopped', function()
    command('let j = jobstart(["cat", "-"], g:job_opts)')
    neq(0, eval('j'))

    eq({ 1, 0 }, eval('[jobstop(j), jobstop(j)]'))
  end)

  describe('running tty-test program', function()
    if skip(is_os('win')) then
      return
    end
    local function next_chunk()
      local rv
      while true do
        local msg = next_msg()
        local data = msg[3][2]
        for i = 1, #data do
          data[i] = data[i]:gsub('\n', '\000')
        end
        rv = table.concat(data, '\n')
        rv = rv:gsub('\r\n$', ''):gsub('^\r\n', '')
        if rv ~= '' then
          break
        end
      end
      return rv
    end

    local j
    local function send(str)
      -- check no nvim_chan_free double free with pty job (#14198)
      api.nvim_chan_send(j, str)
    end

    before_each(function()
      -- Redefine Normalize() so that TTY data is not munged.
      source([[
      function! Normalize(data) abort
        return a:data
      endfunction
      ]])
      insert(testprg('tty-test'))
      command('let g:job_opts.pty = 1')
      command('let exec = [expand("<cfile>:p")]')
      command('let j = jobstart(exec, g:job_opts)')
      j = eval 'j'
      eq('tty ready', next_chunk())
    end)

    it('echoing input', function()
      send('test')
      eq('test', next_chunk())
    end)

    it('resizing window', function()
      command('call jobresize(j, 40, 10)')
      eq('rows: 10, cols: 40', next_chunk())
      command('call jobresize(j, 10, 40)')
      eq('rows: 40, cols: 10', next_chunk())
    end)

    it('jobclose() sends SIGHUP', function()
      command('call jobclose(j)')
      local msg = next_msg()
      msg = (msg[2] == 'stdout') and next_msg() or msg -- Skip stdout, if any.
      eq({ 'notification', 'exit', { 0, 42 } }, msg)
    end)

    it('jobstart() does not keep ptmx file descriptor open', function()
      -- Start another job (using libuv)
      command('let g:job_opts.pty = 0')
      local other_jobid = eval("jobstart(['cat', '-'], g:job_opts)")
      local other_pid = eval('jobpid(' .. other_jobid .. ')')

      -- Other job doesn't block first job from receiving SIGHUP on jobclose()
      command('call jobclose(j)')
      -- Have to wait so that the SIGHUP can be processed by tty-test on time.
      -- Can't wait for the next message in case this test fails, if it fails
      -- there won't be any more messages, and the test would hang.
      vim.uv.sleep(100)
      local err = exc_exec('call jobpid(j)')
      eq('Vim(call):E900: Invalid channel id', err)

      -- cleanup
      eq(other_pid, eval('jobpid(' .. other_jobid .. ')'))
      command('call jobstop(' .. other_jobid .. ')')
    end)
  end)

  it('does not close the same handle twice on exit #25086', function()
    local filename = string.format('%s.lua', t.tmpname())
    write_file(
      filename,
      [[
      vim.api.nvim_create_autocmd('VimLeavePre', {
        callback = function()
          local id = vim.fn.jobstart('sleep 0')
          vim.fn.jobwait({id})
        end,
      })
    ]]
    )

    local screen = tt.setup_child_nvim({
      '--cmd',
      'set notermguicolors',
      '-i',
      'NONE',
      '-u',
      filename,
    })
    -- Wait for startup to complete, so that all terminal responses are received.
    screen:expect([[
      {1: }                                                 |
      ~                                                 |*3
      {1:[No Name]                       0,0-1          All}|
                                                        |
      {3:-- TERMINAL --}                                    |
    ]])

    feed(':q<CR>')
    screen:expect([[
                                                        |
      [Process exited 0]{1: }                               |
                                                        |*4
      {3:-- TERMINAL --}                                    |
    ]])
  end)
end)

describe('pty process teardown', function()
  local screen
  before_each(function()
    clear()
    screen = Screen.new(30, 6)
    screen:expect([[
      ^                              |
      {1:~                             }|*4
                                    |
    ]])
  end)

  it('does not prevent/delay exit. #4798 #4900', function()
    skip(fn.executable('sleep') == 0, 'missing "sleep" command')
    -- Use a nested nvim (in :term) to test without --headless.
    fn.termopen({
      n.nvim_prog,
      '-u',
      'NONE',
      '-i',
      'NONE',
      '--cmd',
      nvim_set,
      -- Use :term again in the _nested_ nvim to get a PTY process.
      -- Use `sleep` to simulate a long-running child of the PTY.
      '+terminal',
      '+!(sleep 300 &)',
      '+qa',
    }, { env = { VIMRUNTIME = os.getenv('VIMRUNTIME') } })

    -- Exiting should terminate all descendants (PTY, its children, ...).
    screen:expect([[
      ^                              |
      [Process exited 0]            |
                                    |*4
    ]])
  end)
end)