为什么我在这个Python代码上遇到断言错误?

时间:2016-11-30 21:04:36

标签: python function python-3.x assert

我在这里写了一个函数:

def addItem(aBookcase, name, mediaType):
    """
    Returns False if aBookcase is full, otherwise returns True and 
    adds item of given name and mediaType to aBookcase.
    """
    pass
    emptySpacesBefore = aBookcase.getEmptySpaces()
    if aBookcase.getEmptySpaces() == 0:
        added = False
        return added
    else:
        position = findSpace(aBookcase)
        aBookcase.setName(*position, name=name)
        aBookcase.setType(*position, mediaType=mediaType)
        added = True
        emptySpacesAfter = aBookcase.getEmptySpaces()
    assert added is True, "No free positions"
    assert emptySpacesAfter < emptySpacesBefore, "Same amount of empty spaces"
    assert aBookcase.getName(*position) is name, "Error with name"
    assert aBookcase.getType(*position) is mediaType, "Error with media type"

然而,当我用这行代码测试函数时:

assert addItem(small, "Algorhythms, date structures and compatibility", BOOK)

我得到一个'AssertionError',如下所示:

Screenshot of 'AssertionError'

所以,如果我是对的,这意味着我没有处理它,但我不确定如何或为什么?我的代码有问题吗?有什么遗失?等。

1 个答案:

答案 0 :(得分:1)

当它正常工作时,addItem函数不返回任何内容,因此返回None,这被您插入的最后一个assert语句视为失败。您应该针对这两种情况(addedTrue

返回False

BTW,因为你到达那一行,这意味着所有以前的断言都没关系好消息:你的代码没问题。