关于LPTHW运动的困惑49

时间:2014-02-18 15:51:12

标签: python nosetests

我正在尝试为以下代码编写一个nosetest:

class ParserError(Exception):
    pass 

class Sentence(object):
    def __init__(self, subject, verb, object):
        self.subject = subject[1]
        self.verb = verb[1]
        self.object = object[1]

def peek(word_list):
    if word_list:
        word = word_list[0]
        return word[0]
    else:
        return None 

def match(word_list, expecting):
    if word_list:
        word = word_list.pop(0)

        if word[0] == expecting:
            return word
        else:
            return None 
    else:
        return None 

def skip(word_list, word_type):
    while peek(word_list) == word_type:
        match(word_list, word_type)

def parse_verb(word_list):
    skip(word_list, 'stop')
    first = peek(word_list)

    if first == 'verb':
        return match(word_list, 'verb')
    else:
        raise ParserError("Expected a verb next, not %s." % first)

def parse_object(word_list):
    skip(word_list, 'stop')
    next = peek(word_list)

    if next == 'noun':
        return match(word_list, 'noun')
    if next == 'direction':
        return match(word_list, 'direction')
    else:
        return ParserError("Expected a noun next.")

def parse_subject(word_list, subj):
    verb = parse_verb(word_list)
    obj = parse_object(word_list)

    return Sentence(subj, verb, obj)

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

    start = peek(word_list)

    if start == 'noun':
        subj = match(word_list, 'noun')
        return parse_subject(word_list, subj)
    elif start == 'verb':
        return parse_subject(word_list, ('noun', 'player'))
    else:
        raise ParserError("Must start with subject, object or verb, not %s." % start)

我试过这个并得到了ParserError: Expected a verb, not None,它引用了parse_verb方法:

from nose.tools import *
from ex49 import parser

def test_parse_subject():
    word_list = [('verb', 'catch'),
             ('noun', 'things')]
    subj = ('noun', 'player')
    verb = parser.parse_verb(word_list)
    obj = parser.parse_object(word_list)
    result = parser.Sentence(subj, verb, obj)
    assert_equal(parser.parse_subject(word_list, subj), result)

有什么想法吗?我希望我能发布的不仅仅是一个失败的代码,但是我现在已经在这个章节中苦苦挣扎了8个小时,而且我的大脑被枪杀了。

1 个答案:

答案 0 :(得分:0)

parse_verbword_list移除动词。 parse_subject尝试在那里找到动词并失败,因此是例外。

我认为在要求编写测试而不提供代码应该做的任何文档时,这个练习很愚蠢。

您可以像这样编写测试:

def test_parse_subject():
    word_list = [('verb', 'catch'),
             ('noun', 'things')]
    subj = ('noun', 'player')
    result = parser.Sentence('player', 'catch', 'things')
    assert_equal(parser.parse_subject(word_list, subj), result)

......但那应该仍然失败。由于Sentence未定义__eq__方法,因此会按身份对这两个实例进行比较。

请改为尝试:

def test_parse_subject():
    word_list = [('verb', 'catch'),
             ('noun', 'things')]
    subj = ('noun', 'player')
    result = parser.parse_subject(word_list, subj)
    assert_equal((result.subject, result.verb, result.object), 
                 ('player', 'catch', 'things'))