0

I have a code like:

class SqsClientWrapper:
  def __init__(self, sqs_client, queue_url):
    self.sqs_client = sqs_client
    self.queue_url = queue_url

  def receive_message(self):
    try:
      while True:
        response = self.sqs_client.receive_message(QueueUrl=self.queue_url, MaxNumberOfMessages=1)
        if len(response.get("Messages", [])) > 0:
          return response["Messages"][0]
    except ClientError as e:
      raise e

    def delete_message(self, receipt_handle):
        try:
            response = self.sqs_client.delete_message(
                QueueUrl=self.queue_url, ReceiptHandle=receipt_handle
            )
        except ClientError:
            self.__logger.exception(
                f"Could not delete the meessage from the - {self.__queue_url}."
            )
            raise
        else:
            return response

class Listener:
    def listen(self, queue_url):
        sqs_client = SqsClientWrapper(boto3.client("sqs"), queue_url)
        while True:
            try:
                message = sqs_client.receive_message()
                print(str(message))
                sqs_client.delete_message(message["ReceiptHandle"])
            except Exception as e:
              continue

I'm trying to test the Listener using moto, I have the following test code:

logger = logging.getLogger()

class ListenerTest(unittest.TestCase):
    def setUp(self) -> None:
        self.executor = ThreadPoolExecutor()
        self.futures = []

    def tearDown(self) -> None:
        for future in self.futures:
            future.cancel()
        self.executor.shutdown()

    @mock_sqs
    def test_simple(self):
        sqs = boto3.resource("sqs")
        queue = sqs.create_queue(QueueName="test-fake-queue")
        queue_url = queue.url
        listener = Listener()
        self.futures.append(
            self.executor.submit(listener.listen, queue_url)
        )
        sqs_client = boto3.client("sqs")
        sqs_client.send_message(
            QueueUrl=queue_url,
            MessageBody=json.dumps({"id": "1234"}),
        )

if __name__ == "__main__":
    unittest.main()

When I run this, it seems to have received the message okay, but when deleting it from the queue it fails with the following error:

botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the DeleteMessage operation: The security token included in the request is invalid.

Anyone know what might be going on here? Thanks!

de1337ed
  • 3,113
  • 12
  • 37
  • 55
  • It is saying that the AWS credentials used with `delete_message()` were invalid. That's odd because it calls `receive_message()` immediately before, and that would use the same credentials. – John Rotenstein Sep 03 '22 at 09:08
  • Ya - so that’s why I’m at a loss right now. Receive worked fine. – de1337ed Sep 03 '22 at 16:34

0 Answers0