From 319b46230cd96fe22a7d95b931e90ccf09783e61 Mon Sep 17 00:00:00 2001 From: Timothee Cour Date: Fri, 4 Jan 2019 04:54:02 -0800 Subject: [PATCH] fix bug in doAssertRaises when exception==Exception (#10172) * fix bug in doAssertRaises when exception==Exception * add testcase for doAssertRaises --- lib/system.nim | 30 +++++++++++++++++++----------- tests/system/tsystem_misc.nim | 12 ++++++++++++ 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index 9fa889b117..d41953108d 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -4353,7 +4353,7 @@ else: template runnableExamples*(body: untyped) = discard -template doAssertRaises*(exception, code: untyped): typed = +template doAssertRaises*(exception: typedesc, code: untyped): typed = ## Raises ``AssertionError`` if specified ``code`` does not raise the ## specified exception. Example: ## @@ -4361,16 +4361,24 @@ template doAssertRaises*(exception, code: untyped): typed = ## doAssertRaises(ValueError): ## raise newException(ValueError, "Hello World") var wrong = false - try: - 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)) + when Exception is exception: + try: + if true: + code + wrong = true + except Exception: + discard + else: + try: + 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: raiseAssert(astToStr(exception) & " wasn't raised by:\n" & astToStr(code)) diff --git a/tests/system/tsystem_misc.nim b/tests/system/tsystem_misc.nim index 98bc3f4a32..f53a86e9a1 100644 --- a/tests/system/tsystem_misc.nim +++ b/tests/system/tsystem_misc.nim @@ -112,6 +112,18 @@ doAssertRaises(IndexError): foo(toOpenArray(arrNeg, -1, 0)) doAssertRaises(IndexError): 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] let qData = cast[seqqType](addr seqq[0])