Django视图测试失败。为什么?

时间:2012-04-09 03:03:41

标签: django unit-testing django-views

我无法跟踪此测试失败的原因:

def test_CreateViewPost(self):
    user = self.client.login(username="g",password="g")

    # this method creates a poi type and returns it for me
    poiType = self.stubPOIType()
    # this creates a point (django.contrib.gis.geos.Point)
    point = Point(10,10)

    response = self.client.post(reverse("createPOI"),{"name":"testPOI",
                                                      "description":"description",
                                                      "type":poiType,
                                                      "geometry":point})

    # the post is failing. I have errors in my form
    self.assertTemplateUsed(response,"gazetteer/detailPOI.html")
    self.assertEqual(response.status_code,302)

    self.assertEqual(POI.objects.count(),1)

这是模型:

class POI(models.Model):
    name = models.CharField(max_length=128,verbose_name=u"Nome")
    description = models.CharField(max_length=1024,verbose_name=u"Descrição",null=True,blank=True)
    type = models.ForeignKey(POIType,verbose_name=u"Tipo de Ponto")
    geometry = models.PointField(verbose_name=u"Geometria",srid=4291)
    geohash = models.CharField(max_length=64,verbose_name=u"GeoHash",editable=False)

    objects = models.GeoManager()

我从表单中找回了两个错误:分别为字段几何和类型的“无效几何值”和“无效选择”。我将这些传递给了帖子,但它失败了。

任何提示?

编辑:我跟踪“无效几何值”的失败是我的表单期望文本(WKT表单)而不是实际的GEOS点。我已经添加了实际的.wkt并且它有效。但外键怎么样?我应该通过PK吗?

为什么?

1 个答案:

答案 0 :(得分:0)

创建django单元测试时,无法将完整对象(foreigned key objects)传递给post数据。你应该传递基元(id / pk)。

对于几何形状,它是相同的。你应该传递它的WKT表示。

所以:

def test_CreateViewPost(self):
    user = self.client.login(username="g",password="g")

    # this method creates a poi type and returns it for me
    poiType = self.stubPOIType()
    # this creates a point (django.contrib.gis.geos.Point)
    point = Point(10,10)

    response = self.client.post(reverse("createPOI"),{"name":"testPOI",
                                                      "description":"description",
                                                      "type":poiType.pk,
                                                      "geometry":point.wkt})

    # the post is failing. I have errors in my form
    self.assertTemplateUsed(response,"gazetteer/detailPOI.html")
    self.assertEqual(response.status_code,302)

    self.assertEqual(POI.objects.count(),1)