1#!/usr/bin/env python
2#
3# Copyright 2014 Google Inc. All Rights Reserved.
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"""Protocol Buffer Model tests
18
19Unit tests for the Protocol Buffer model.
20"""
21from __future__ import absolute_import
22
23__author__ = "[email protected] (Matt McDonald)"
24
25import unittest
26import httplib2
27
28from googleapiclient.model import ProtocolBufferModel
29
30
31class MockProtocolBuffer(object):
32    def __init__(self, data=None):
33        self.data = data
34
35    def __eq__(self, other):
36        return self.data == other.data
37
38    @classmethod
39    def FromString(cls, string):
40        return cls(string)
41
42    def SerializeToString(self):
43        return self.data
44
45
46class Model(unittest.TestCase):
47    def setUp(self):
48        self.model = ProtocolBufferModel(MockProtocolBuffer)
49
50    def test_no_body(self):
51        headers = {}
52        path_params = {}
53        query_params = {}
54        body = None
55
56        headers, params, query, body = self.model.request(
57            headers, path_params, query_params, body
58        )
59
60        self.assertEqual(headers["accept"], "application/x-protobuf")
61        self.assertTrue("content-type" not in headers)
62        self.assertNotEqual(query, "")
63        self.assertEqual(body, None)
64
65    def test_body(self):
66        headers = {}
67        path_params = {}
68        query_params = {}
69        body = MockProtocolBuffer("data")
70
71        headers, params, query, body = self.model.request(
72            headers, path_params, query_params, body
73        )
74
75        self.assertEqual(headers["accept"], "application/x-protobuf")
76        self.assertEqual(headers["content-type"], "application/x-protobuf")
77        self.assertNotEqual(query, "")
78        self.assertEqual(body, "data")
79
80    def test_good_response(self):
81        resp = httplib2.Response({"status": "200"})
82        resp.reason = "OK"
83        content = "data"
84
85        content = self.model.response(resp, content)
86        self.assertEqual(content, MockProtocolBuffer("data"))
87
88    def test_no_content_response(self):
89        resp = httplib2.Response({"status": "204"})
90        resp.reason = "No Content"
91        content = ""
92
93        content = self.model.response(resp, content)
94        self.assertEqual(content, MockProtocolBuffer())
95
96
97if __name__ == "__main__":
98    unittest.main()
99