blob: 44b2a145678e54a4edd096e6a8cb4f3fd53de28f [file] [log] [blame]
Ali Afshar2dcc6522010-12-16 10:11:53 +01001#!/usr/bin/python2.4
2#
3# Copyright 2010 Google Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Tests for errors handling
18"""
19
20__author__ = 'afshar@google.com (Ali Afshar)'
21
22
23import unittest
24import httplib2
25
26
27from apiclient.errors import HttpError
28
29
30def fake_response(data, headers):
31 return httplib2.Response(headers), data
32
33
34class Error(unittest.TestCase):
Ali Afshar8da41862010-12-16 10:17:26 +010035 """Test handling of error bodies."""
Ali Afshar2dcc6522010-12-16 10:11:53 +010036
37 def test_json_body(self):
Ali Afshar8da41862010-12-16 10:17:26 +010038 """Test a nicely formed, expected error response."""
Ali Afshar2dcc6522010-12-16 10:11:53 +010039 resp, content = fake_response(json_error_content,
40 {'status':'400', 'content-type': 'application/json'})
41 error = HttpError(resp, content)
42 self.assertEqual(str(error), '<HttpError 400 "country is required">')
43
44 def test_bad_json_body(self):
Ali Afshar8da41862010-12-16 10:17:26 +010045 """Test handling of bodies with invalid json."""
Ali Afshar2dcc6522010-12-16 10:11:53 +010046 resp, content = fake_response('{',
47 {'status':'400', 'content-type': 'application/json'})
48 error = HttpError(resp, content)
49 self.assertEqual(str(error), '<HttpError 400 "{">')
50
51 def test_missing_message_json_body(self):
Ali Afshar8da41862010-12-16 10:17:26 +010052 """Test handling of bodies with missing expected 'message' element."""
Ali Afshar2dcc6522010-12-16 10:11:53 +010053 resp, content = fake_response('{}',
54 {'status':'400', 'content-type': 'application/json'})
55 error = HttpError(resp, content)
56 self.assertEqual(str(error), '<HttpError 400 "{}">')
57
58 def test_non_json(self):
Ali Afshar8da41862010-12-16 10:17:26 +010059 """Test handling of non-JSON bodies"""
Ali Afshar2dcc6522010-12-16 10:11:53 +010060 resp, content = fake_response('NOT OK', {'status':'400'})
61 error = HttpError(resp, content)
62 self.assertEqual(str(error), '<HttpError 400 "Ok">')
63
64
65json_error_content = """
66{
67 "error": {
68 "errors": [
69 {
70 "domain": "global",
71 "reason": "required",
72 "message": "country is required",
73 "locationType": "parameter",
74 "location": "country"
75 }
76 ],
77 "code": 400,
78 "message": "country is required"
79 }
80}
81"""
82