Django REST API在保存模型时失败测试,​​但运行正常

时间:2015-03-20 12:19:16

标签: python django rest unit-testing

我很遗憾。我有一个来自Django的REST Framework的ModelViewSet,它通过覆盖perform_create方法对POST请求执行一些自定义功能。它看起来像这样:

class UserViewSet(viewsets.ModelViewSet):
    queryset         = User.objects.all()
    serializer_class = UserFlat

    def perform_create(self, serializer):
         serializer.save()

         try:
             profile_country = self.request.data['country']
             profile_phone = self.request.data['phone']

             profile = Profile.objects.get(user_id=serializer.data['id'])
             country = Country.objects.get(country_code=profile_country)

             # both of these return the object just fine
             # print profile
             # print country

             # Take the profile object and set these attributes. It has a ForeignKey relation with the country
             profile.phone  = profile_phone
             profile.origin = country

             # This is where Django's TestCase fails
             profile.save()

         except:
             print "Attributes not provided"

所以我在我的终端用httpie对上面的内容进行了测试,结果很好。当我去检查数据库时,每个信息都在那里。创建了User对象,并创建了一个新的Profile对象,其中ForeignKey为Country和电话号码(我使用post_save信号创建Profile对象)

当我运行测试时,它在profile.save()部分失败了。我已经确认Country对象是在测试之前在DB中创建的,如果我在运行测试时将其打印出来,我可以看到它清楚地获取了所有相关信息。

http POST :8000/api/v1/users/ username=test password=test last_name=test first_name=test email=test@test.com country=US phone=555

上面一行在我的终端帖子中成功运行到我的数据库

这里是失败的TestCase,但

class APITestCase(TransactionTestCase):
    def test_create_user_profile_through_api(self):
    url = '/api/v1/users/'

    # country = Country.objects.get(country_code='US')

    data = {
        'first_name':'Tom',
        'last_name':'Sawyer',
        'username':'tomsawyer',
        'password':'tomsawyer',
        'email':'tomsawyer@tomsawyer.com',
        'country': 'US',
        'phone':'5555555555'
    }

    # The test fails to save the additional profile information profile.save() within
    # the view's perform_create method. Why is that?
    post = self.client.post(url, data, format='json')

    # request = self.client.get('/api/v1/users/3')
    # Profile.objects.get(id=3) 
    # both lines above are me checking to see if the profile object showed
    # up with the relevant country and phone number fields. Fields are 
    # are empty although the profile object is there

    # I didn't write the assertion yet as the line above keeps coming up empty

当我运行测试时,我视图的除外块出现"Attributes not provided"

编辑: 另一方面,我已经检查过身份验证等问题,甚至将其关闭/强行通过REST框架,这一切都很好。我能够成功地从API发布和检索,并且没有API用于所有其他场景

编辑:追溯

  File "app/api/views.py", line 86, in perform_create
profile.save()

 File "venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
 return self.cursor.execute(sql, params)
DataError: integer out of range

0 个答案:

没有答案