簡體   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