fix bug in doAssertRaises when exception==Exception (#10172)

* fix bug in doAssertRaises when exception==Exception
* add testcase for doAssertRaises
This commit is contained in:
Timothee Cour 2019-01-04 04:54:02 -08:00 • committed by Andreas Rumpf
commit 319b46230c
2 changed files with 31 additions and 11 deletions

View file

@ -4353,7 +4353,7 @@ else:
template runnableExamples*(body: untyped) = template runnableExamples*(body: untyped) =
discard discard
template doAssertRaises*(exception, code: untyped): typed = template doAssertRaises*(exception: typedesc, code: untyped): typed =
## Raises ``AssertionError`` if specified ``code`` does not raise the ## Raises ``AssertionError`` if specified ``code`` does not raise the
## specified exception. Example: ## specified exception. Example:
## ##
@ -4361,16 +4361,24 @@ template doAssertRaises*(exception, code: untyped): typed =
## doAssertRaises(ValueError): ## doAssertRaises(ValueError):
## raise newException(ValueError, "Hello World") ## raise newException(ValueError, "Hello World")
var wrong = false var wrong = false
try: when Exception is exception:
if true: try:
code if true:
wrong = true code
except exception: wrong = true
discard except Exception:
except Exception as exc: discard
raiseAssert(astToStr(exception) & else:
" wasn't raised, another error was raised instead by:\n"& try:
astToStr(code)) if true:
code
wrong = true
except exception:
discard
except Exception as exc:
raiseAssert(astToStr(exception) &
" wasn't raised, another error was raised instead by:\n"&
astToStr(code))
if wrong: if wrong:
raiseAssert(astToStr(exception) & " wasn't raised by:\n" & astToStr(code)) raiseAssert(astToStr(exception) & " wasn't raised by:\n" & astToStr(code))

View file

@ -112,6 +112,18 @@ doAssertRaises(IndexError):
foo(toOpenArray(arrNeg, -1, 0)) foo(toOpenArray(arrNeg, -1, 0))
doAssertRaises(IndexError): doAssertRaises(IndexError):
foo(toOpenArray(arrNeg, -1, -3)) foo(toOpenArray(arrNeg, -1, -3))
doAssertRaises(Exception):
raise newException(Exception, "foo")
block:
var didThrow = false
try:
doAssertRaises(IndexError): # should fail since it's wrong exception
raise newException(FieldError, "foo")
except AssertionError:
# ok, throwing was correct behavior
didThrow = true
doAssert didThrow
type seqqType = ptr UncheckedArray[int] type seqqType = ptr UncheckedArray[int]
let qData = cast[seqqType](addr seqq[0]) let qData = cast[seqqType](addr seqq[0])