1+ from collections .abc import Iterable
2+
13import pytest
2- from moto .ec2 .exceptions import InvalidKeyPairNameError
3- from moto .ses .exceptions import MessageRejectedError
4+ from moto .core .exceptions import RESTError , ServiceException
5+ from moto .ec2 .exceptions import EC2_ERROR_RESPONSE
46
57from localstack .aws .api import CommonServiceException , RequestContext
68from localstack .aws .chain import HandlerChain
@@ -202,6 +204,10 @@ def capture_original_exception_handler(
202204 assert err_context .service_exception .status_code == 500
203205
204206 def test_moto_service_exception_is_translated (self , service_response_handler_chain ):
207+ # Redefine exception here but use the right base exc. This is to improve tolerance against Moto refactors.
208+ class MessageRejectedError (ServiceException ):
209+ code = "MessageRejected"
210+
205211 # Ensure ServiceExceptions are translated
206212 context = create_aws_request_context (
207213 "ses" ,
@@ -225,6 +231,20 @@ def test_moto_service_exception_is_translated(self, service_response_handler_cha
225231 assert context .service_exception .status_code == 400
226232
227233 def test_moto_rest_error_is_translated (self , service_response_handler_chain ):
234+ # Redefine exception here but use the right base exc. This is to improve tolerance against Moto refactors.
235+ class InvalidKeyPairNameError (RESTError ):
236+ code = 400
237+ request_id_tag_name = "RequestID"
238+ extended_templates = {"custom_response" : EC2_ERROR_RESPONSE }
239+ env = RESTError .extended_environment (extended_templates )
240+
241+ def __init__ (self , key : Iterable [str ]):
242+ super ().__init__ (
243+ "InvalidKeyPair.NotFound" ,
244+ f"The keypair '{ key } ' does not exist." ,
245+ template = "custom_response" ,
246+ )
247+
228248 # Ensure RESTErrors are translated
229249 context = create_aws_request_context (
230250 "ec2" ,
@@ -238,12 +258,13 @@ def test_moto_rest_error_is_translated(self, service_response_handler_chain):
238258 "MinCount" : 1 ,
239259 },
240260 )
241- msg = "The keypair 'some-key-pair' does not exist."
242- moto_exception = InvalidKeyPairNameError (msg )
261+ moto_exception = InvalidKeyPairNameError ({"some-key-pair" })
243262
244263 ServiceExceptionSerializer ().create_exception_response (moto_exception , context )
245264
246- assert msg in context .service_exception .message
265+ assert (
266+ "The keypair '{'some-key-pair'}' does not exist." in context .service_exception .message
267+ )
247268 assert context .service_exception .code == "InvalidKeyPair.NotFound"
248269 assert not context .service_exception .sender_fault
249270 assert context .service_exception .status_code == 400
0 commit comments