blob: ab0be287ec6b108950a954838ff1a2d0a00157bd [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
Joe Gregorio49396552011-03-08 10:39:00 -050030JSON_ERROR_CONTENT = """
Ali Afshar2dcc6522010-12-16 10:11:53 +010031{
32 "error": {
33 "errors": [
34 {
35 "domain": "global",
36 "reason": "required",
37 "message": "country is required",
38 "locationType": "parameter",
39 "location": "country"
40 }
41 ],
42 "code": 400,
43 "message": "country is required"
44 }
45}
46"""
47
Joe Gregorio49396552011-03-08 10:39:00 -050048def fake_response(data, headers):
49 return httplib2.Response(headers), data
50
51
52class Error(unittest.TestCase):
53 """Test handling of error bodies."""
54
55 def test_json_body(self):
56 """Test a nicely formed, expected error response."""
57 resp, content = fake_response(JSON_ERROR_CONTENT,
58 {'status':'400', 'content-type': 'application/json'})
59 error = HttpError(resp, content)
60 self.assertEqual(str(error), '<HttpError 400 "country is required">')
61
62 def test_bad_json_body(self):
63 """Test handling of bodies with invalid json."""
64 resp, content = fake_response('{',
65 {'status':'400', 'content-type': 'application/json'})
66 error = HttpError(resp, content)
67 self.assertEqual(str(error), '<HttpError 400 "{">')
68
69 def test_with_uri(self):
70 """Test handling of passing in the request uri."""
71 resp, content = fake_response('{',
72 {'status':'400', 'content-type': 'application/json'})
73 error = HttpError(resp, content, 'http://example.org')
74 self.assertEqual(str(error), '<HttpError 400 when requesting http://example.org returned "{">')
75
76 def test_missing_message_json_body(self):
77 """Test handling of bodies with missing expected 'message' element."""
78 resp, content = fake_response('{}',
79 {'status':'400', 'content-type': 'application/json'})
80 error = HttpError(resp, content)
81 self.assertEqual(str(error), '<HttpError 400 "{}">')
82
83 def test_non_json(self):
84 """Test handling of non-JSON bodies"""
85 resp, content = fake_response('NOT OK', {'status':'400'})
86 error = HttpError(resp, content)
87 self.assertEqual(str(error), '<HttpError 400 "Ok">')