First time here? Check out the FAQ!

Ask Your Question
0

How to doctest an exception ?

asked 7 years ago

Emmanuel Charpentier gravatar image

I'd like to doctest an exception, to show that some call is expected to fail (and, latter, to show how to cope with that). Something along the lines of:

sage: foo(x)
ValueError
... #Elided
ValueError: x is not palatable to foo

I haven't found any doctest directive allowing me to tell "This test is expected to raise an exception" ; so, when I run the doctest, I can't even compare what I get with the text of the expected traceback. The only solution I found so far is to wrap my test in a try:... except: ... construct, which is not very demonstrative.

Any idea ?

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
2

answered 7 years ago

B r u n o gravatar image

I don't know why, but the correct way is as follows:

sage: foo(x)
Traceback (most recent call last):
...
ValueError: x is not palatable to foo
Preview: (hide)
link

Comments

That doesn't solve the problem : I still get an uncatched exception, and the doctest fails (and I get a warning while building the docs).

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 7 years ago )

Bruno's answer should solve the problem, unless your call to foo(x) raises an exception different from ValueError. Note that the three dots in the second line should be typed as such. If the problem persists, can you tell which warning you get while building the docs.

eric_g gravatar imageeric_g ( 7 years ago )

That's weird, since such doctests already exist. See this example for instance.

B r u n o gravatar imageB r u n o ( 7 years ago )

@Bruno: sorry I was not clear: there is no problem at all; what I meant is that if foo(x) raises an exception different from ValueError, of course the doctest must be adapted to this.

eric_g gravatar imageeric_g ( 7 years ago )

I begin to see a (dim) light :

I had copied and pasted outpût from a sage process running in a terminal. This output was a bit fancier that what you usually get. It seems that what Sage displays by default in a terminal is an IPYthon console, whose display of Exceptions is a bit different. In fact, there is a magic %doctest_mode, that switches this :

sage: %doctest_mode
Exception reporting mode: Plain
Doctest mode is: ON
>>> %doctest_mode
Exception reporting mode: Context
Doctest mode is: OFF

Now, as you can see %doctest_mode also switches prompts to Python's >>>. What I'd like to do would be to be able to switch to Plain exception reporting mode, but keeping the sage prompts.

The docs gave me no answer. May some kind soul enlighten me ?

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 7 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 7 years ago

Seen: 1,799 times

Last updated: Oct 28 '17