您好,我是 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/