0

I'm halfway through the book Learn Python the Hard Way by Zed Shaw. The book doesn't have any coverage or documentation for the function assert_raises().

So I tried to run this test:

from nose.tools import *
from ex48.parser import *

def test_except():
    raw_sentence = [('stop', 'the'), ('noun', 'bear'), ('verb', 'kill')]
    assert_raises(ParserError, parse_sentence(raw_sentence))

Here's the error when I tried to run nosetests:

======================================================================
ERROR: tests.parser_tests.test_except
----------------------------------------------------------------------
Traceback (most recent call last):
  File "####/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "####/ex48/tests/parser_tests.py", line 8, in test_except
    assert_raises(ParserError, parse_sentence(raw_sentence))
  File "####/ex48/ex48/parser.py", line 69, in parse_sentence
    obj = parse_object(word_list)
  File "####/ex48/ex48/parser.py", line 53, in parse_object
    raise ParserError("Expected a noun or direction next.")
 ParserError: Expected a noun or direction next.

 ----------------------------------------------------------------------
 Ran 8 tests in 0.008s

 FAILED (errors=1)

Here is where the exception is coming from:

def parse_verb(word_list):
    skip(word_list, 'stop')

    if peek(word_list) == 'verb':
       return match(word_list, 'verb')
    else:
       raise ParserError("Expected a verb next.")

The call to parse_sentence(raw_sentence) is expected to fail. The assert_raises() should work properly, but it doesn't catch the raised exception from parse_verb() yielding a failed test. What do you think is/are the problem/s?

2 Answers2

0

Do not call parse_sentence() directly. Instead, pass it as an argument.

assert_raises(ParserError, parse_sentence, raw_sentence)

Even better, use assert_raises() in a with block. See How to use nose's assert_raises?

Community
  • 1
  • 1
Jim K
  • 12,824
  • 2
  • 22
  • 51
0

This will work

assert_raises(ParserError, parse_verb, raw_sentence) 
Trent
  • 2,909
  • 1
  • 31
  • 46