0

当我期望响应为 400 或 401 并且它总是返回200 响应时,我一直在使用版本Django和测试用例处理API。什么会导致这个问题?Tastypiedjango-tastypie==0.9.13-betabad requesthttp ok

用户资源

class UserAuthentication(ApiKeyAuthentication):
    def __init__(self, no_auth, full_auth, require_active=True):
        super(Authentication, self).__init__()
        self.no_auth = no_auth
        self.full_auth = full_auth

    def is_authenticated(self, request, **kwargs):
        if request.method not in self.no_auth:
            return super(UserAuthentication, self).is_authenticated(request, **kwargs)

        return True


class UsersResource(MyModelResource):
    class Meta:
        queryset = User.objects.all()
        allowed_methods = ['post']
        detail_allowed_methods = ['put']
        fields = ['id', 'first_name', 'last_name', 'email']
        validation = UserValidation()
        always_return_data = True
        authorization = UserAuthorization()
        authentication = UserAuthentication(no_auth=['GET', 'POST'], full_auth=['PUT'])

小部分测试

def test_login_unsuccessful_wrong_email(self):
    post_data = {
        "user": {
            "email": 'wrong@email.com',  # so email is wrong
            "password": self.user_password
        }
    }

    response = self.api_client.post('/api/v1/login/', data=post_data)

    self.assertHttpBadRequest(response)    # At this place I expect 400 status code

测试失败回溯

FAIL: test_login_unsuccessful_wrong_email (api.v1.tests.UsersLoginResourceTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/sultan/.virtualenvs/myenv/myproject/api/v1/tests.py", line 458, in test_login_unsuccessful_wrong_email
    self.assertHttpBadRequest(response)
  File "/Users/sultan/.virtualenvs/myenv/lib/python2.7/site-packages/django_tastypie-0.9.13_beta-py2.7.egg/tastypie/test.py", line 346, in assertHttpBadRequest
    return self.assertEqual(resp.status_code, 400)
AssertionError: 200 != 400

谢谢。

4

1 回答 1

1

我认为最好的方法是首先。

创建异常类:

class HTTPError(Exception):
    def __init__(self, code, msg):
        Exception.__init__(self, msg)
        self.code = code
        self.msg = msg

创建一个自定义页面“error.html”,仅显示 err_code err_msg 和 request 或 raison(如果需要)。“{{err_code}} {{err_msg}} {{request}}”

不要错过在模板中的 settings.py 中添加模板

创建中间件示例:

class JobMiddlewareException:
    def process_exception(self, request, e):
       if isinstance(e, HTTPError)
            render_to_response('error.html', {'err_code': e.code, 'err_msg': e.msg, 'request':request}, requestcontext(request))

示例:在您的代码中,当您需要引发错误时,您会这样做

引发 HTTPError(404, '未找到。该页面对用户 %s' % request.user 无效)

于 2013-09-17T14:37:31.760 回答