1#!/usr/bin/env python 2# -*- coding: utf-8 -*- 3# 4# Copyright 2015 Google Inc. 5# 6# Licensed under the Apache License, Version 2.0 (the "License"); 7# you may not use this file except in compliance with the License. 8# You may obtain a copy of the License at 9# 10# http://www.apache.org/licenses/LICENSE-2.0 11# 12# Unless required by applicable law or agreed to in writing, software 13# distributed under the License is distributed on an "AS IS" BASIS, 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15# See the License for the specific language governing permissions and 16# limitations under the License. 17 18"""Tests for util.""" 19import codecs 20import gzip 21import os 22import six.moves.urllib.request as urllib_request 23import tempfile 24import unittest 25 26from apitools.gen import util 27from mock import patch 28 29 30class NormalizeVersionTest(unittest.TestCase): 31 32 def testVersions(self): 33 already_valid = 'v1' 34 self.assertEqual(already_valid, util.NormalizeVersion(already_valid)) 35 to_clean = 'v0.1' 36 self.assertEqual('v0_1', util.NormalizeVersion(to_clean)) 37 38 39class NamesTest(unittest.TestCase): 40 41 def testKeywords(self): 42 names = util.Names(['']) 43 self.assertEqual('in_', names.CleanName('in')) 44 45 def testNormalizeEnumName(self): 46 names = util.Names(['']) 47 self.assertEqual('_0', names.NormalizeEnumName('0')) 48 49 50class MockRequestResponse(): 51 """Mocks the behavior of urllib.response.""" 52 53 class MockRequestEncoding(): 54 def __init__(self, encoding): 55 self.encoding = encoding 56 57 def get(self, _): 58 return self.encoding 59 60 def __init__(self, content, encoding): 61 self.content = content 62 self.encoding = MockRequestResponse.MockRequestEncoding(encoding) 63 64 def info(self): 65 return self.encoding 66 67 def read(self): 68 return self.content 69 70 71def _Gzip(raw_content): 72 """Returns gzipped content from any content.""" 73 f = tempfile.NamedTemporaryFile(suffix='gz', mode='wb', delete=False) 74 f.close() 75 try: 76 with gzip.open(f.name, 'wb') as h: 77 h.write(raw_content) 78 with open(f.name, 'rb') as h: 79 return h.read() 80 finally: 81 os.unlink(f.name) 82 83 84class GetURLContentTest(unittest.TestCase): 85 86 def testUnspecifiedContentEncoding(self): 87 data = 'regular non-gzipped content' 88 with patch.object(urllib_request, 'urlopen', 89 return_value=MockRequestResponse(data, '')): 90 self.assertEqual(data, util._GetURLContent('unused_url_parameter')) 91 92 def testGZippedContent(self): 93 data = u'¿Hola qué tal?' 94 compressed_data = _Gzip(data.encode('utf-8')) 95 with patch.object(urllib_request, 'urlopen', 96 return_value=MockRequestResponse( 97 compressed_data, 'gzip')): 98 self.assertEqual(data, util._GetURLContent( 99 'unused_url_parameter').decode('utf-8')) 100