繁体   English   中英

Python:AssertionError

[英]Python: AssertionError

首先,这是我需要测试的代码:

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')

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


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:
        raise ParserError('Expected a noun or direction next.')

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

    return Sentence(subj, verb, obj) # 执行 class Sentence

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

    start = peek(word_list)

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

我输入的列表是[('verb','taste'),('direction','good'),('noun','pizza')]此列表中的第一个值是('verbs,' ”,其word_type为“动词”,适合我在编码中给出的word_type,但出现错误AssertionError:None!='动词'我认为这是不合理的。

def test_skip():
    skipA = skip([('verb','taste'),('direction','good'),('noun','pizza')], 'verb')
    assert_equal(skipA, 'verb')
#    assert_equal(skipA, None)

函数skip不返回任何值(这意味着它返回None )。

因此skipANone ,断言失败。

使用“跳过”方法可能会出现问题,因为“跳过”未返回任何值,这意味着“跳过”将返回None

您需要在跳过功能中返回。 您将返回查看和匹配,但是您调用skip并希望从那里获取值的范围意味着您也需要从那里返回。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM