简体   繁体   中英

Python: AssertionError

First, that's the codes that I need test:

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)

The list I typed in is [('verb', 'taste'),('direction','good'),('noun','pizza')] The first value in this list is ('verb', 'taste') and its word_type is 'verb', it fits to the word_type I gave in my coding but I got error AssertionError: None != 'verb' I think it's unreasonable.

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

The function skip doesn't return any value (which means that it returns None ).

So skipA is None and the assertion fails.

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

You need a return in your skip function. You're returning in peek and match, but the scope of you calling skip and wanting a value from there means you need to return out of there, as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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