I want to test if a function raises a specific exception. For example, this silly example:
def myfun(a):
if a == 1:
raise TypeError("wrong")
if a == 2:
raise ValueError("wrong too")
Now I want to test if the correct Exception Type and message was thrown for different inputs.
My idea was to change the template to this:
{{ STUDENT_ANSWER }} __student_answer__ = """{{ STUDENT_ANSWER | e('py') }}""" SEPARATOR = "#<ab@17943918#@>#" {% for TEST in TESTCASES %} try: # ??? How to indent the code here correctly ??? {{ TEST.testcode }} except Exception as e: n = type(e).__name__ # Put here all Exception Names we expect to handle if n not in ['TypeError', 'ValueError']: raise e from None else: print(repr(e)) {% if not loop.last %} print(SEPARATOR) {% endif %} {% endfor %}
I.e., to check if a exception is thrown, which we want and then simply print repr of the exception and compare that.
I wondered, however, if this is a sane idea or would produce any problems? Is there any better way to do it?
One Problem I already found is, that the TEST.testcode must not have more than one line, because the indentation will be wrong... (Which is for this type of question not a big problem).
Another problem could be, that if the student uses the wrong type of exception, it will crash instead of showing the test as failed. I could change the code to always print repr of the exception, but that would mean that for example, certain exceptions where I want a detailed error log, would just print the exception name and message... But I guess that cannot be avoided?