diff --git a/ibmcloudant/cloudant_base_service.py b/ibmcloudant/cloudant_base_service.py index 3884671b..a474893f 100644 --- a/ibmcloudant/cloudant_base_service.py +++ b/ibmcloudant/cloudant_base_service.py @@ -23,6 +23,8 @@ from json import dumps from json.decoder import JSONDecodeError from io import BytesIO +import logging +import os from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core.authenticators import Authenticator @@ -36,6 +38,12 @@ # Define timeout values CONNECT_TIMEOUT=60 READ_TIMEOUT=150 +gen2_known_issues_url = 'https://github.com/IBM/cloudant-python-sdk/blob/main/KNOWN_ISSUES.md#cloudant-gen-2-compatibility' +CLOUDANT_SDK_GEN1_ERRORS = 'CLOUDANT_SDK_GEN1_ERRORS' + +logger = logging.getLogger(__name__) +# Ensure warnings are emitted even if a parent logger is set to a higher level +logger.setLevel(logging.WARNING) # Define validations class ValidationRule(namedtuple('ValidationRule', ['path_segment_index', 'error_parameter_name', 'operation_ids'])): @@ -63,9 +71,25 @@ def __hash__(self): 'head_attachment', 'put_attachment' ]) +gen1_only_rule = ValidationRule(path_segment_index=0, error_parameter_name='', operation_ids= [ + 'get_activity_tracker_events', + 'get_capacity_databases_information', + 'get_capacity_throughput_information', + 'get_cors_information', + 'get_current_databases_information', + 'get_current_throughput_information', + 'post_activity_tracker_events', + 'post_api_keys', + 'put_capacity_throughput_configuration', + 'put_cloudant_security_configuration', + 'put_cors_configuration', +]) +def is_gen1_error_enabled() -> bool: + return os.environ.get(CLOUDANT_SDK_GEN1_ERRORS, '').lower() == 'true' + rules_by_operation = {} # Build the rules_by_operation dict of validation rules -for rule in [doc_id_rule, att_name_rule]: +for rule in [doc_id_rule, att_name_rule, gen1_only_rule]: for operation_id in rule.operation_ids: # Use a mapping of operation_id to an ordered set of rules # Since Py3.6 dict is ordered so use a key only dict for our set @@ -159,6 +183,15 @@ def prepare_request(self, request_url_path_segments = [] # Note the get returns a value-less dict, we are iterating only the keys for rule in rules_by_operation.get(operation_id, {}): + if rule == gen1_only_rule: + message = ( + f'The operation {operation_id} is unavailable for Gen 2 Cloudant plans. ' + f'See {gen2_known_issues_url} for more information.' + ) + logger.warning(message) + if is_gen1_error_enabled(): + raise TypeError(message) + continue if len(request_url_path_segments) > rule.path_segment_index: segment_to_validate = request_url_path_segments[rule.path_segment_index] if segment_to_validate.startswith('_'): diff --git a/test/unit/test_cloudant_base_validation.py b/test/unit/test_cloudant_base_validation.py index 629bf456..6e256fb5 100644 --- a/test/unit/test_cloudant_base_validation.py +++ b/test/unit/test_cloudant_base_validation.py @@ -14,8 +14,12 @@ # See the License for the specific language governing permissions and # limitations under the License. +import logging +import os import unittest +from unittest import mock from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibmcloudant.cloudant_base_service import CLOUDANT_SDK_GEN1_ERRORS, gen1_only_rule from ibmcloudant.cloudant_v1 import * class TestValidation(unittest.TestCase): @@ -61,3 +65,85 @@ def test_validates_strip_trailing_slash(self): ) service.set_service_url('https://cloudant.example/') self.assertEqual(service.service_url, 'https://cloudant.example') + + +def _operation_headers(operation_id): + return { + 'X-IBMCloud-SDK-Analytics': 'service_name=cloudant;service_version=V1;operation_id={0}'.format(operation_id) + } + + +class TestGen1OnlyOperations(unittest.TestCase): + + def setUp(self): + self.service = CloudantV1(authenticator=NoAuthAuthenticator()) + self.service.set_service_url('https://cloudant.example') + + def _set_env(self, value): + """Patch the environment for the test, unsetting the variable when value is None.""" + patcher = mock.patch.dict(os.environ) + patcher.start() + self.addCleanup(patcher.stop) + if value is None: + os.environ.pop(CLOUDANT_SDK_GEN1_ERRORS, None) + else: + os.environ[CLOUDANT_SDK_GEN1_ERRORS] = value + + def test_raises_for_every_gen1_only_operation_when_enabled(self): + self._set_env('true') + for operation_id in gen1_only_rule.operation_ids: + with self.subTest(operation_id=operation_id): + with self.assertRaisesRegex(TypeError, operation_id + '.+unavailable for Gen 2'): + self.service.prepare_request('GET', '/', headers=_operation_headers(operation_id)) + + def test_raises_from_public_operation_when_enabled(self): + self._set_env('true') + with self.assertRaisesRegex(TypeError, 'get_cors_information.+unavailable for Gen 2'): + self.service.get_cors_information() + + def test_enabled_value_is_case_insensitive(self): + for value in ('TRUE', 'True', 'tRuE'): + with self.subTest(value=value): + self._set_env(value) + with self.assertRaises(TypeError): + self.service.prepare_request('GET', '/', headers=_operation_headers('get_cors_information')) + + def test_does_not_raise_when_not_enabled(self): + for value in (None, '', 'false', '1', 'yes'): + with self.subTest(value=value): + self._set_env(value) + for operation_id in gen1_only_rule.operation_ids: + request = self.service.prepare_request('GET', '/', headers=_operation_headers(operation_id)) + self.assertIsNotNone(request) + + def test_warning_logged_even_when_root_logger_level_is_error(self): + self._set_env(None) + records = [] + + class ListHandler(logging.Handler): + def emit(self, record): + records.append(record) + + root = logging.getLogger() + handler = ListHandler() + original_level = root.level + root.addHandler(handler) + root.setLevel(logging.ERROR) + self.addCleanup(root.removeHandler, handler) + self.addCleanup(root.setLevel, original_level) + + self.service.prepare_request('GET', '/', headers=_operation_headers('get_cors_information')) + + self.assertEqual(1, len(records)) + self.assertEqual(logging.WARNING, records[0].levelno) + self.assertIn('get_cors_information', records[0].getMessage()) + + def test_other_operations_unaffected_when_enabled(self): + self._set_env('true') + request = self.service.prepare_request('GET', '/', headers=_operation_headers('get_server_information')) + self.assertIsNotNone(request) + + def test_doc_id_validation_still_applies_when_enabled(self): + self._set_env('true') + with self.assertRaisesRegex(ValueError, '.+_testDocument.+'): + self.service.get_document('testDatabase', '_testDocument')