tawaitsemantics.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. discard """
  2. output: '''
  3. Error can be caught using yield
  4. Infix `or` raises
  5. Infix `and` raises
  6. All() raises
  7. Awaiting a async procedure call raises
  8. Awaiting a future raises
  9. '''
  10. """
  11. import asyncdispatch
  12. # This tests the behaviour of 'await' under different circumstances.
  13. # Specifically, when an awaited future raises an exception then `await` should
  14. # also raise that exception by `read`'ing that future. In cases where you don't
  15. # want this behaviour, you can use `yield`.
  16. # https://github.com/nim-lang/Nim/issues/4170
  17. proc thrower(): Future[void] =
  18. result = newFuture[void]()
  19. result.fail(newException(Exception, "Test"))
  20. proc dummy: Future[void] =
  21. result = newFuture[void]()
  22. result.complete()
  23. proc testInfixOr() {.async.} =
  24. # Test the infix `or` operator semantics.
  25. var fut = thrower()
  26. var fut2 = dummy()
  27. await fut or fut2 # Should raise!
  28. proc testInfixAnd() {.async.} =
  29. # Test the infix `and` operator semantics.
  30. var fut = thrower()
  31. var fut2 = dummy()
  32. await fut and fut2 # Should raise!
  33. proc testAll() {.async.} =
  34. # Test the `all` semantics.
  35. var fut = thrower()
  36. var fut2 = dummy()
  37. await all(fut, fut2) # Should raise!
  38. proc testCall() {.async.} =
  39. await thrower()
  40. proc testAwaitFut() {.async.} =
  41. var fut = thrower()
  42. await fut # This should raise.
  43. proc tester() {.async.} =
  44. # Test that we can handle exceptions without 'try'
  45. var fut = thrower()
  46. doAssert fut.finished
  47. doAssert fut.failed
  48. doAssert fut.error.msg == "Test"
  49. yield fut # We are yielding a 'Future', so no `read` occurs.
  50. doAssert fut.finished
  51. doAssert fut.failed
  52. doAssert fut.error.msg == "Test"
  53. echo("Error can be caught using yield")
  54. fut = testInfixOr()
  55. yield fut
  56. doAssert fut.finished
  57. doAssert fut.failed
  58. echo("Infix `or` raises")
  59. fut = testInfixAnd()
  60. yield fut
  61. doAssert fut.finished
  62. doAssert fut.failed
  63. echo("Infix `and` raises")
  64. fut = testAll()
  65. yield fut
  66. doAssert fut.finished
  67. doAssert fut.failed
  68. echo("All() raises")
  69. fut = testCall()
  70. yield fut
  71. doAssert fut.failed
  72. echo("Awaiting a async procedure call raises")
  73. # Test that await will read the future and raise an exception.
  74. fut = testAwaitFut()
  75. yield fut
  76. doAssert fut.failed
  77. echo("Awaiting a future raises")
  78. waitFor(tester())