【发布时间】:2016-08-10 11:33:48
【问题描述】:
我正在使用 django sweetpie 来创建我的宁静端点。所以是时候制作登录端点了,(还没有完成)。
accounts/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)
accounts/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')
通过使用终端模拟器和 curl 使用 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
【问题讨论】:
标签: django tastypie restful-architecture django-testing