Python帮助无法弄清楚单元测试失败的原因

标签 python unit-testing

您好,我是 Python 的新手,我在弄清楚我的代码有什么问题以及为什么单元测试失败时遇到了问题?下面是运行测试时的代码、单元测试和错误信息:

legs = []
stomach = []
class Centipede(object):
    def __init__(self):

    def __str__(self):       
        return ','.join(self.stomach)

    def __call__(self,*args):
        [self.stomach.append(arg) for arg in args]
        #self.stomach.append(args)

    def __repr__(self):
        return ','.join(self.legs)

    def __setattr__(self, key, value):
        print("setting %s to %s" % (key, repr(value)))
        if key in ([]):
            self.legs.append(key)
            #self.__dict__[key] = value
            object.__setattr__(self, key,value)

单元测试代码

import unittest
from centipede import Centipede

class TestBug(unittest.TestCase):

    def test_stomach(self):
        ralph = Centipede()
        ralph('chocolate')
        ralph('bbq')
        ralph('cookies')
        ralph('salad')
        self.assertEquals(ralph.__str__(), 'chocolate,bbq,cookies,salad')


    def test_legs(self):
        ralph = Centipede()
        ralph.friends = ['Steve', 'Daniel', 'Guido']
        ralph.favorite_show = "Monty Python's Flying Circus"
        ralph.age = '31'
        self.assertEquals(ralph.__repr__(),'<friends,favorite_show,age>' )

if __name__ == "__main__":
    unittest.main()

运行测试时产生的错误信息:

AttributeError: 'Centipede' object has no attribute 'legs'
AttributeError: 'Centipede' object has no attribute 'stomach'

最佳答案

将腿和腹部移入蜈蚣。 (我一直想这么说:))

class Centipede(object): 
    def init(self):
        self.stomach=[]
        self.legs=[]

关于Python帮助无法弄清楚单元测试失败的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7189585/

相关文章:

python - Plotly-Dash:如何在 plotly dash 中为悬停功能编写交互式回调代码

python - 使用 Python 将大型 CSV 文件导入 MySQL

javascript - 使用 ng-html2js 进行 AngularJS 指令测试

unit-testing - polymer 单元测试 : dom-repeat is not rendered when "ready" is called

c# - 如何在单元测试中模拟 HttpRequest 的 UserAgent 属性?

python - 如何从正在运行的脚本中判断哪个 Python 解释器正在运行它?

python - 如何在Databricks中使用os.walk()来计算Azure datalake中的目录大小

Google App Engine shell 中的 Python raw_input

javascript - 有没有办法在自定义匹配器中使用 Jasmine 默认匹配器?

c# - OpenCover 用于 .Net Core 中的 xUnit 测试