2016-04-18 64 views
1

我使用django tastypie創建我的寧靜端點。所以是時候創建登錄端點了(尚未完成)。assertRaises BadRequest不起作用

賬戶/ API/resources.py

class UserResource(ModelResource): 
    class Meta: 
     queryset = User.objects.all() 
     allowed_methods = ['post'] 
     serializer = Serializer(formats=['json']) 

    def prepend_urls(self, *args, **kwargs): 
     return [ 
      url(r'^(?P<resource_name>%s)/login/$' % self._meta.resource_name, 
       self.wrap_view('dispatch_login'), name='api_dispatch_login') 
     ] 

    def dispatch_login(self, request, **kwargs): 
     self.method_check(request, allowed=['post']) 

     data = self._meta.serializer.from_json(request.body) # This raises the exception. 

     return self.create_response(request, {}, status=200) 

賬戶/ tests.py

class UserApiTestCase(TestCase): 
    def setUp(self): 
     self.uri = reverse('api_dispatch_login', kwargs={'api_name': 'v1', 
          'resource_name': 'user'}) 

    def test_login_user_credentials_sent_in_body_request(self): 
     with self.assertRaises(BadRequest): 
      self.client.post(self.uri, content_type='application/json') 

通過消耗使用終端仿真器和捲曲的web服務,我可以看到引發異常。

$ curl localhost:8000/api/v1/user/login/ --request POST 
{"error": "Request is not valid JSON."} 

但是在運行測試時,斷言失敗。

FAIL: test_login_user_credentials_sent_in_body_request (accounts.tests.UserApiTestCase) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "/home/slackmart/code/superproject/accounts/tests.py", line 29, in test_login_user_credentials_sent_in_body_request 
    self.client.post(self.uri, content_type='application/json') 
AssertionError: BadRequest not raised 

回答

0

https://github.com/django-tastypie/django-tastypie/blob/master/docs/release_notes/dev.rst

新增UnsupportedSerializationFormat和 UnsupportedDeserializationFormat例外,這是捕獲並 結果HttpNotAcceptable(406個狀態)和HttpUnsupportedMediaType (415狀態)的響應,分別。以前,這些相同類型的 錯誤會出現爲400個錯誤請求錯誤。

最近對Tastypie所作的更改已使其更符合HTTP並且錯誤代碼更具體。您需要查找406或415狀態碼而不是400.