1# Copyright 2015 Google Inc. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15import os 16import difflib 17import unittest 18 19import six 20 21from apitools.gen import gen_client 22from apitools.gen import test_utils 23 24 25def GetSampleClientPath(api_name, *path): 26 return os.path.join(os.path.dirname(__file__), api_name + '_sample', *path) 27 28 29def _GetContent(file_path): 30 with open(file_path) as f: 31 return f.read() 32 33 34class ClientGenCliTest(unittest.TestCase): 35 36 def AssertDiffEqual(self, expected, actual): 37 """Like unittest.assertEqual with a diff in the exception message.""" 38 if expected != actual: 39 unified_diff = difflib.unified_diff( 40 expected.splitlines(), actual.splitlines()) 41 raise AssertionError('\n'.join(unified_diff)) 42 43 def _CheckGeneratedFiles(self, api_name, api_version): 44 prefix = api_name + '_' + api_version 45 with test_utils.TempDir() as tmp_dir_path: 46 gen_client.main([ 47 gen_client.__file__, 48 '--init-file', 'empty', 49 '--infile', 50 GetSampleClientPath(api_name, prefix + '.json'), 51 '--outdir', tmp_dir_path, 52 '--overwrite', 53 '--root_package', 54 'samples.{0}_sample.{0}_{1}'.format(api_name, api_version), 55 'client' 56 ]) 57 expected_files = ( 58 set([prefix + '_client.py', 59 prefix + '_messages.py', 60 '__init__.py'])) 61 self.assertEquals(expected_files, set(os.listdir(tmp_dir_path))) 62 if six.PY3: 63 # The source files won't be identical under python3, 64 # so we exit early. 65 return 66 for expected_file in expected_files: 67 self.AssertDiffEqual( 68 _GetContent(GetSampleClientPath( 69 api_name, prefix, expected_file)), 70 _GetContent(os.path.join(tmp_dir_path, expected_file))) 71 72 def testGenClient_BigqueryDoc(self): 73 self._CheckGeneratedFiles('bigquery', 'v2') 74 75 def testGenClient_DnsDoc(self): 76 self._CheckGeneratedFiles('dns', 'v1') 77 78 def testGenClient_FusiontablesDoc(self): 79 self._CheckGeneratedFiles('fusiontables', 'v1') 80 81 def testGenClient_IamDoc(self): 82 self._CheckGeneratedFiles('iam', 'v1') 83 84 def testGenClient_ServicemanagementDoc(self): 85 self._CheckGeneratedFiles('servicemanagement', 'v1') 86 87 def testGenClient_StorageDoc(self): 88 self._CheckGeneratedFiles('storage', 'v1') 89