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