diff --git a/kafka/sasl/msk.py b/kafka/sasl/msk.py index 7ec03215d..a0d306004 100644 --- a/kafka/sasl/msk.py +++ b/kafka/sasl/msk.py @@ -7,13 +7,6 @@ import logging import string -# needed for AWS_MSK_IAM authentication: -try: - from botocore.session import Session as BotoSession -except ImportError: - # no botocore available, will disable AWS_MSK_IAM mechanism - BotoSession = None - from kafka.errors import KafkaConfigurationError from kafka.sasl.abc import SaslMechanism from kafka.vendor.six.moves import urllib @@ -24,7 +17,12 @@ class SaslMechanismAwsMskIam(SaslMechanism): def __init__(self, **config): + try: + from botocore.session import Session as BotoSession + except ImportError: + BotoSession = None assert BotoSession is not None, 'AWS_MSK_IAM requires the "botocore" package' + self._boto_session_cls = BotoSession assert config.get('security_protocol', '') == 'SASL_SSL', 'AWS_MSK_IAM requires SASL_SSL' assert 'host' in config, 'AWS_MSK_IAM requires host configuration' self.host = config['host'] @@ -33,7 +31,7 @@ def __init__(self, **config): self._is_authenticated = False def _build_client(self): - session = BotoSession() + session = self._boto_session_cls() credentials = session.get_credentials().get_frozen_credentials() if not session.get_config_variable('region'): raise KafkaConfigurationError('Unable to determine region for AWS MSK cluster. Is AWS_DEFAULT_REGION set?') diff --git a/test/sasl/test_msk.py b/test/sasl/test_msk.py index f3cc46ce8..8b878904a 100644 --- a/test/sasl/test_msk.py +++ b/test/sasl/test_msk.py @@ -72,7 +72,7 @@ def test_aws_msk_iam_client_temporary_credentials(): def test_aws_msk_iam_sasl_mechanism(): - with mock.patch('kafka.sasl.msk.BotoSession'): + with mock.patch.dict(sys.modules, {'botocore': mock.MagicMock(), 'botocore.session': mock.MagicMock()}): sasl = SaslMechanismAwsMskIam(security_protocol='SASL_SSL', host='localhost') with mock.patch.object(sasl, '_build_client', return_value=client_factory(token=None)): assert sasl.auth_bytes() != b''