diff --git a/translate/google/cloud/translate/client.py b/translate/google/cloud/translate/client.py index c43acb80550b..b7fe9142d017 100644 --- a/translate/google/cloud/translate/client.py +++ b/translate/google/cloud/translate/client.py @@ -15,6 +15,7 @@ """Client for interacting with the Google Cloud Translate API.""" +import httplib2 import six from google.cloud._helpers import _to_bytes @@ -55,6 +56,12 @@ def __init__(self, target_language=ENGLISH_ISO_639, api_key=None, credentials=None, http=None): self.api_key = api_key self.target_language = target_language + + if api_key is not None: + # If API key auth is desired, make it so that no credentials + # will be auto-detected by the base class constructor. + if http is None: + http = httplib2.Http() super(Client, self).__init__(credentials=credentials, http=http) def get_languages(self, target_language=None): diff --git a/translate/tox.ini b/translate/tox.ini index f33c168d61c2..168559383e71 100644 --- a/translate/tox.ini +++ b/translate/tox.ini @@ -6,6 +6,7 @@ envlist = localdeps = pip install --quiet --upgrade {toxinidir}/../core deps = + mock pytest covercmd = py.test --quiet \ diff --git a/translate/unit_tests/test_client.py b/translate/unit_tests/test_client.py index 0fa04897af5f..2e9a23d6995e 100644 --- a/translate/unit_tests/test_client.py +++ b/translate/unit_tests/test_client.py @@ -27,7 +27,7 @@ def _get_target_class(): def _make_one(self, *args, **kw): return self._get_target_class()(*args, **kw) - def test_ctor(self): + def test_constructor(self): from google.cloud.translate.connection import Connection from google.cloud.translate.client import ENGLISH_ISO_639 @@ -39,7 +39,7 @@ def test_ctor(self): self.assertIsNone(client.api_key) self.assertEqual(client.target_language, ENGLISH_ISO_639) - def test_ctor_non_default(self): + def test_constructor_non_default(self): from google.cloud.translate.connection import Connection http = object() @@ -52,6 +52,22 @@ def test_ctor_non_default(self): self.assertEqual(self.KEY, client.api_key) self.assertEqual(client.target_language, target) + def test_constructor_api_key_override(self): + import mock + from google.cloud.translate.connection import Connection + + target = 'ru' + with mock.patch('httplib2.Http') as http_ctor: + client = self._make_one( + target_language=target, api_key=self.KEY) + + http_ctor.assert_called_once_with() + self.assertIsInstance(client._connection, Connection) + self.assertIsNone(client._connection.credentials) + self.assertIs(client._connection.http, http_ctor.return_value) + self.assertEqual(self.KEY, client.api_key) + self.assertEqual(client.target_language, target) + def test_get_languages(self): from google.cloud.translate.client import ENGLISH_ISO_639