tawaitsemantics.nim 2.3 KB

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