1
0

shared.vim 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. " Functions shared by several tests.
  2. " Only load this script once.
  3. if exists('*WaitFor')
  4. finish
  5. endif
  6. " Run skip the current test if some expression returns true
  7. func SkipIf( expr, msg )
  8. if type(a:expr) == v:t_func
  9. let skip = a:expr()
  10. else
  11. let skip = eval(a:expr)
  12. endif
  13. if skip
  14. throw 'SKIPPED: ' . a:msg
  15. endif
  16. endfunction
  17. " Wait for up to five seconds for "expr" to become true. "expr" can be a
  18. " stringified expression to evaluate, or a funcref without arguments.
  19. " Using a lambda works best. Example:
  20. " call WaitFor({-> status == "ok"})
  21. "
  22. " A second argument can be used to specify a different timeout in msec.
  23. "
  24. " When successful the time slept is returned.
  25. " When running into the timeout an exception is thrown, thus the function does
  26. " not return.
  27. func WaitFor(expr, ...)
  28. let timeout = get(a:000, 0, 5000)
  29. let slept = s:WaitForCommon(a:expr, v:null, timeout)
  30. if slept < 0
  31. throw 'WaitFor() timed out after ' . timeout . ' msec'
  32. endif
  33. return slept
  34. endfunc
  35. " Wait for up to five seconds for "assert" to return zero. "assert" must be a
  36. " (lambda) function containing one assert function. Example:
  37. " call WaitForAssert({-> assert_equal("dead", job_status(job)})
  38. "
  39. " A second argument can be used to specify a different timeout in msec.
  40. "
  41. " Return zero for success, one for failure (like the assert function).
  42. func WaitForAssert(assert, ...)
  43. let timeout = get(a:000, 0, 5000)
  44. if s:WaitForCommon(v:null, a:assert, timeout) < 0
  45. return 1
  46. endif
  47. return 0
  48. endfunc
  49. " Common implementation of WaitFor() and WaitForAssert().
  50. " Either "expr" or "assert" is not v:null
  51. " Return the waiting time for success, -1 for failure.
  52. func s:WaitForCommon(expr, assert, timeout)
  53. " using reltime() is more accurate, but not always available
  54. let slept = 0
  55. if has('reltime')
  56. let start = reltime()
  57. endif
  58. while 1
  59. if type(a:expr) == v:t_func
  60. let success = a:expr()
  61. elseif type(a:assert) == v:t_func
  62. let success = a:assert() == 0
  63. else
  64. let success = eval(a:expr)
  65. endif
  66. if success
  67. return slept
  68. endif
  69. if slept >= a:timeout
  70. break
  71. endif
  72. if type(a:assert) == v:t_func
  73. " Remove the error added by the assert function.
  74. call remove(v:errors, -1)
  75. endif
  76. sleep 10m
  77. if has('reltime')
  78. let slept = float2nr(reltimefloat(reltime(start)) * 1000)
  79. else
  80. let slept += 10
  81. endif
  82. endwhile
  83. return -1 " timed out
  84. endfunc