[英]Testing python methods that call class methods
I have a very simple method: 我有一个非常简单的方法:
Class Team(models.Model):
def sides(self):
return SideNames.objects.filter(team=self)
SideNames is another model defined in the same file as Team, SideNames是与Team在同一文件中定义的另一个模型,
Which when I try and test: 当我尝试测试时:
self.assertEquals(len(t.sides()), 2)
I get the following error: 我收到以下错误:
return SideNames.objects.filter(team=self)
AttributeError: 'NoneType' object has no attribute 'objects' AttributeError:'NoneType'对象没有属性'objects'
but if I change the test to be 但是如果我将测试更改为
self.assertEquals(len(SideNames.objects.filter(team=t)), 2)
Then I don't get the error. 然后我没有得到错误。 What's the difference between calling SideNames.objects.filter from the test itself and calling the actual method? 从测试本身调用SideNames.objects.filter和调用实际方法之间有什么区别?
For reference, here are the 2 classes in their entirety. 供参考,这里是全部2个类。
class Team(models.Model):
"""The model for a football team."""
class Admin:
pass
def __unicode__(self):
return u'%s' % self.name
def is_player(self, player):
"""Checks to see if 'player' is a member if this team. Returns True if they are, or False otherwise."""
try:
teamPlayer = TeamPlayers.objects.get(player=player, team=self)
return True
except ObjectDoesNotExist:
return False
def sides(self):
"""Return the side names for this team"""
return SideNames.objects.filter(team=self)
def updateSides(self, side_a, side_b):
"""Update the side names"""
names = SideNames.objects.filter(team=self);
a = SideNames.objects.get(name = names[0].name)
a.name = side_a
a.save()
b = SideNames.objects.get(name = names[1].name)
b.name = side_b
b.save()
name = models.CharField("Team Name", max_length=255)
organiser = models.ForeignKey(User)
class SideNames(models.Model):
"""Holds the names of the sides for each team"""
class Admin:
pass
def __unicode__(self):
"""Pretty print the SideNames object"""
return self.name
team = models.ForeignKey(Team)
name = models.CharField(max_length=128)
In the module that defines the test, you're importing the name SideNames
from some other module. 在定义测试的模块中,您将从其他模块中导入名称SideNames
。 In the module where that sides
method is defined, the name SideNames
is not defined or imported. 在该模块sides
定义的方法,该名称SideNames
没有定义或导入。
By any chance, does your test do something like this: 碰巧,您的测试是否执行以下操作:
from myapp import models
...
models.SideNames = None
since that's the only explanation I can think of for why SideNames should be None in the context of that method. 因为这是我能想到的唯一解释,为什么在该方法的上下文中SideNames应该为None。
As an aside, the method itself is pointless, as backwards relations are automatically provided by Django, so you could just call t.sidenames_set.all()
. t.sidenames_set.all()
,该方法本身是没有意义的,因为Django自动提供了向后关系,因此您只需调用t.sidenames_set.all()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.