We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[BUG] Management API unit tests raise errors
Management API unit tests raise errors, but the tests pass. The errors need to be removed and the output needs to be clean.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `management_api_app/resources/strings.py`
Content:
```
1 PONG = "pong"
2 
3 # API Descriptions
4 API_GET_HEALTH_STATUS = "Get health status"
5 
6 API_GET_ALL_WORKSPACES = "Get all workspaces"
7 API_GET_WORKSPACE_BY_ID = "Get workspace by Id"
8 API_CREATE_WORKSPACE = "Create a workspace"
9 
10 API_GET_STATUS_OF_SERVICES = "Get status of services"
11 
12 API_GET_WORKSPACE_TEMPLATES = "Get workspace template names"
13 API_CREATE_WORKSPACE_TEMPLATES = "Create workspace template"
14 API_GET_WORKSPACE_TEMPLATE_BY_NAME = "Get workspace template by name"
15 
16 # State store status
17 OK = "OK"
18 NOT_OK = "Not OK"
19 COSMOS_DB = "Cosmos DB"
20 STATE_STORE_ENDPOINT_NOT_RESPONDING = "State Store endpoint is not responding"
21 UNSPECIFIED_ERROR = "Unspecified error"
22 
23 # Error strings
24 ACCESS_APP_IS_MISSING_ROLE = "The App is missing role"
25 ACCESS_PLEASE_SUPPLY_APP_ID = "Please supply the app_id for the AAD application"
26 ACCESS_UNABLE_TO_GET_INFO_FOR_APP = "Unable to get app info for app:"
27 AUTH_NOT_ASSIGNED_TO_ADMIN_ROLE = "Not assigned to admin role"
28 AUTH_COULD_NOT_VALIDATE_CREDENTIALS = "Could not validate credentials"
29 INVALID_AUTH_PROVIDER = "Invalid authentication provider"
30 UNABLE_TO_REPLACE_CURRENT_TEMPLATE = "Unable to replace the existing 'current' template with this name"
31 UNABLE_TO_PROCESS_REQUEST = "Unable to process request"
32 WORKSPACE_DOES_NOT_EXIST = "Workspace does not exist"
33 WORKSPACE_TEMPLATE_DOES_NOT_EXIST = "Could not retrieve the 'current' template with this name"
34 WORKSPACE_TEMPLATE_VERSION_EXISTS = "A template with this version already exists"
35 
36 
37 # Resource Status
38 RESOURCE_STATUS_NOT_DEPLOYED = "not_deployed"
39 RESOURCE_STATUS_DEPLOYING = "deploying"
40 RESOURCE_STATUS_DEPLOYED = "deployed"
41 RESOURCE_STATUS_DELETING = "deleting"
42 RESOURCE_STATUS_DELETED = "deleted"
43 RESOURCE_STATUS_FAILED = "failed"
44 
45 # Resource Type
46 RESOURCE_TYPE_WORKSPACE = "workspace"
47 RESOURCE_TYPE_SERVICE = "service"
48 
49 # Deployments
50 RESOURCE_STATUS_NOT_DEPLOYED_MESSAGE = "This resource has not yet been deployed"
51 
52 # Service bus
53 SERVICE_BUS_GENERAL_ERROR_MESSAGE = "Service bus failure"
54 DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT = "Service bus message is not formatted correctly."
55 DEPLOYMENT_STATUS_ID_NOT_FOUND = "Service bus message refers to resource id = {} which does not exist"
56 
57 # Workspace creation validation
58 MISSING_REQUIRED_PARAMETERS = "Missing required parameters"
59 INVALID_EXTRA_PARAMETER = "Invalid extra parameters"
60 PARAMETERS_WITH_WRONG_TYPE = "Parameters with wrong type"
61
```

Path: `management_api_app/service_bus/deployment_status_update.py`
Content:
```
1 import json
2 import logging
3 from contextlib import asynccontextmanager
4 
5 from fastapi import FastAPI
6 from pydantic import ValidationError, parse_obj_as
7 
8 from azure.servicebus.aio import ServiceBusClient
9 from azure.identity.aio import DefaultAzureCredential
10 
11 from core import config
12 from resources import strings
13 from db.errors import EntityDoesNotExist
14 from api.dependencies.database import get_db_client
15 from db.repositories.workspaces import WorkspaceRepository
16 from models.domain.workspace import DeploymentStatusUpdateMessage, Workspace
17 
18 
19 @asynccontextmanager
20 async def default_credentials():
21     """
22     Context manager which yields the default credentials.
23     """
24     credential = DefaultAzureCredential(managed_identity_client_id=config.MANAGED_IDENTITY_CLIENT_ID)
25     yield credential
26     await credential.close()
27 
28 
29 async def receive_message():
30     """
31     This method is an async generator which receives messages from service bus
32     and yields those messages. If the yielded function return True the message is
33     marked complete.
34     """
35     async with default_credentials() as credential:
36         service_bus_client = ServiceBusClient(config.SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE, credential)
37 
38         async with service_bus_client:
39             receiver = service_bus_client.get_queue_receiver(queue_name=config.SERVICE_BUS_DEPLOYMENT_STATUS_UPDATE_QUEUE)
40 
41             async with receiver:
42                 received_msgs = await receiver.receive_messages(max_message_count=10, max_wait_time=5)
43 
44                 for msg in received_msgs:
45                     result = True
46                     message = ""
47 
48                     try:
49                         message = json.loads(str(msg))
50                         result = (yield parse_obj_as(DeploymentStatusUpdateMessage, message))
51                     except (json.JSONDecodeError, ValidationError):
52                         logging.error(strings.DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT)
53 
54                     if result:
55                         logging.info(f"Received deployment status update message with correlation ID {msg.correlation_id}: {message}")
56                         await receiver.complete_message(msg)
57 
58 
59 def create_updated_deployment_document(workspace: Workspace, message: DeploymentStatusUpdateMessage):
60     """Take a workspace and a deployment status update message and updates workspace with the message contents
61 
62     Args:
63         workspace ([Workspace]): Workspace to update
64         message ([DeploymentStatusUpdateMessage]): Message which contains the updated information
65 
66     Returns:
67         [Workspace]: Workspace with the deployment sub doc updated
68     """
69     workspace.deployment.status = message.status
70     workspace.deployment.message = message.message
71     return workspace
72 
73 
74 def update_status_in_database(workspace_repo: WorkspaceRepository, message: DeploymentStatusUpdateMessage):
75     """Updates the deployment sub document with message content
76 
77     Args:
78         workspace_repo ([WorkspaceRepository]): Handle to the workspace repository
79         message ([DeploymentStatusUpdateMessage]): Message which contains the updated information
80 
81     Returns:
82         [bool]: True if document is updated, False otherwise.
83     """
84     result = False
85 
86     try:
87         workspace = workspace_repo.get_workspace_by_workspace_id(message.id)
88         workspace_repo.update_workspace(create_updated_deployment_document(workspace, message))
89         result = True
90     except EntityDoesNotExist:
91         # Marking as true as this message will never succeed anyways and should be removed from the queue.
92         result = True
93         error_string = strings.DEPLOYMENT_STATUS_ID_NOT_FOUND.format(message.id)
94         logging.error(error_string)
95     except Exception as e:
96         logging.error(strings.STATE_STORE_ENDPOINT_NOT_RESPONDING + " " + str(e))
97 
98     return result
99 
100 
101 async def receive_message_and_update_deployment(app: FastAPI) -> None:
102     """
103     Receives messages from the deployment status update queue and updates the status for
104     the associated resource in the state store.
105     Args:
106         app ([FastAPI]): Handle to the currently running app
107     """
108     receive_message_gen = receive_message()
109 
110     try:
111         async for message in receive_message_gen:
112             workspace_repo = WorkspaceRepository(get_db_client(app))
113             result = update_status_in_database(workspace_repo, message)
114             await receive_message_gen.asend(result)
115     except StopAsyncIteration:  # the async generator when finished signals end with this exception.
116         pass
117
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/management_api_app/resources/strings.py b/management_api_app/resources/strings.py
--- a/management_api_app/resources/strings.py
+++ b/management_api_app/resources/strings.py
@@ -51,7 +51,7 @@
 
 # Service bus
 SERVICE_BUS_GENERAL_ERROR_MESSAGE = "Service bus failure"
-DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT = "Service bus message is not formatted correctly."
+DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT = "Service bus message is not formatted correctly"
 DEPLOYMENT_STATUS_ID_NOT_FOUND = "Service bus message refers to resource id = {} which does not exist"
 
 # Workspace creation validation
diff --git a/management_api_app/service_bus/deployment_status_update.py b/management_api_app/service_bus/deployment_status_update.py
--- a/management_api_app/service_bus/deployment_status_update.py
+++ b/management_api_app/service_bus/deployment_status_update.py
@@ -48,8 +48,8 @@
                     try:
                         message = json.loads(str(msg))
                         result = (yield parse_obj_as(DeploymentStatusUpdateMessage, message))
-                    except (json.JSONDecodeError, ValidationError):
-                        logging.error(strings.DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT)
+                    except (json.JSONDecodeError, ValidationError) as e:
+                        logging.error(f"{strings.DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT}: {e}")
 
                     if result:
                         logging.info(f"Received deployment status update message with correlation ID {msg.correlation_id}: {message}")

{"golden_diff": "diff --git a/management_api_app/resources/strings.py b/management_api_app/resources/strings.py\n--- a/management_api_app/resources/strings.py\n+++ b/management_api_app/resources/strings.py\n@@ -51,7 +51,7 @@\n \n # Service bus\n SERVICE_BUS_GENERAL_ERROR_MESSAGE = \"Service bus failure\"\n-DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT = \"Service bus message is not formatted correctly.\"\n+DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT = \"Service bus message is not formatted correctly\"\n DEPLOYMENT_STATUS_ID_NOT_FOUND = \"Service bus message refers to resource id = {} which does not exist\"\n \n # Workspace creation validation\ndiff --git a/management_api_app/service_bus/deployment_status_update.py b/management_api_app/service_bus/deployment_status_update.py\n--- a/management_api_app/service_bus/deployment_status_update.py\n+++ b/management_api_app/service_bus/deployment_status_update.py\n@@ -48,8 +48,8 @@\n                     try:\n                         message = json.loads(str(msg))\n                         result = (yield parse_obj_as(DeploymentStatusUpdateMessage, message))\n-                    except (json.JSONDecodeError, ValidationError):\n-                        logging.error(strings.DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT)\n+                    except (json.JSONDecodeError, ValidationError) as e:\n+                        logging.error(f\"{strings.DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT}: {e}\")\n \n                     if result:\n                         logging.info(f\"Received deployment status update message with correlation ID {msg.correlation_id}: {message}\")\n", "issue": "[BUG] Management API unit tests raise errors\nManagement API unit tests raise errors, but the tests pass. The errors need to be removed and the output needs to be clean.\r\n\n", "before_files": [{"content": "PONG = \"pong\"\n\n# API Descriptions\nAPI_GET_HEALTH_STATUS = \"Get health status\"\n\nAPI_GET_ALL_WORKSPACES = \"Get all workspaces\"\nAPI_GET_WORKSPACE_BY_ID = \"Get workspace by Id\"\nAPI_CREATE_WORKSPACE = \"Create a workspace\"\n\nAPI_GET_STATUS_OF_SERVICES = \"Get status of services\"\n\nAPI_GET_WORKSPACE_TEMPLATES = \"Get workspace template names\"\nAPI_CREATE_WORKSPACE_TEMPLATES = \"Create workspace template\"\nAPI_GET_WORKSPACE_TEMPLATE_BY_NAME = \"Get workspace template by name\"\n\n# State store status\nOK = \"OK\"\nNOT_OK = \"Not OK\"\nCOSMOS_DB = \"Cosmos DB\"\nSTATE_STORE_ENDPOINT_NOT_RESPONDING = \"State Store endpoint is not responding\"\nUNSPECIFIED_ERROR = \"Unspecified error\"\n\n# Error strings\nACCESS_APP_IS_MISSING_ROLE = \"The App is missing role\"\nACCESS_PLEASE_SUPPLY_APP_ID = \"Please supply the app_id for the AAD application\"\nACCESS_UNABLE_TO_GET_INFO_FOR_APP = \"Unable to get app info for app:\"\nAUTH_NOT_ASSIGNED_TO_ADMIN_ROLE = \"Not assigned to admin role\"\nAUTH_COULD_NOT_VALIDATE_CREDENTIALS = \"Could not validate credentials\"\nINVALID_AUTH_PROVIDER = \"Invalid authentication provider\"\nUNABLE_TO_REPLACE_CURRENT_TEMPLATE = \"Unable to replace the existing 'current' template with this name\"\nUNABLE_TO_PROCESS_REQUEST = \"Unable to process request\"\nWORKSPACE_DOES_NOT_EXIST = \"Workspace does not exist\"\nWORKSPACE_TEMPLATE_DOES_NOT_EXIST = \"Could not retrieve the 'current' template with this name\"\nWORKSPACE_TEMPLATE_VERSION_EXISTS = \"A template with this version already exists\"\n\n\n# Resource Status\nRESOURCE_STATUS_NOT_DEPLOYED = \"not_deployed\"\nRESOURCE_STATUS_DEPLOYING = \"deploying\"\nRESOURCE_STATUS_DEPLOYED = \"deployed\"\nRESOURCE_STATUS_DELETING = \"deleting\"\nRESOURCE_STATUS_DELETED = \"deleted\"\nRESOURCE_STATUS_FAILED = \"failed\"\n\n# Resource Type\nRESOURCE_TYPE_WORKSPACE = \"workspace\"\nRESOURCE_TYPE_SERVICE = \"service\"\n\n# Deployments\nRESOURCE_STATUS_NOT_DEPLOYED_MESSAGE = \"This resource has not yet been deployed\"\n\n# Service bus\nSERVICE_BUS_GENERAL_ERROR_MESSAGE = \"Service bus failure\"\nDEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT = \"Service bus message is not formatted correctly.\"\nDEPLOYMENT_STATUS_ID_NOT_FOUND = \"Service bus message refers to resource id = {} which does not exist\"\n\n# Workspace creation validation\nMISSING_REQUIRED_PARAMETERS = \"Missing required parameters\"\nINVALID_EXTRA_PARAMETER = \"Invalid extra parameters\"\nPARAMETERS_WITH_WRONG_TYPE = \"Parameters with wrong type\"\n", "path": "management_api_app/resources/strings.py"}, {"content": "import json\nimport logging\nfrom contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom pydantic import ValidationError, parse_obj_as\n\nfrom azure.servicebus.aio import ServiceBusClient\nfrom azure.identity.aio import DefaultAzureCredential\n\nfrom core import config\nfrom resources import strings\nfrom db.errors import EntityDoesNotExist\nfrom api.dependencies.database import get_db_client\nfrom db.repositories.workspaces import WorkspaceRepository\nfrom models.domain.workspace import DeploymentStatusUpdateMessage, Workspace\n\n\n@asynccontextmanager\nasync def default_credentials():\n    \"\"\"\n    Context manager which yields the default credentials.\n    \"\"\"\n    credential = DefaultAzureCredential(managed_identity_client_id=config.MANAGED_IDENTITY_CLIENT_ID)\n    yield credential\n    await credential.close()\n\n\nasync def receive_message():\n    \"\"\"\n    This method is an async generator which receives messages from service bus\n    and yields those messages. If the yielded function return True the message is\n    marked complete.\n    \"\"\"\n    async with default_credentials() as credential:\n        service_bus_client = ServiceBusClient(config.SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE, credential)\n\n        async with service_bus_client:\n            receiver = service_bus_client.get_queue_receiver(queue_name=config.SERVICE_BUS_DEPLOYMENT_STATUS_UPDATE_QUEUE)\n\n            async with receiver:\n                received_msgs = await receiver.receive_messages(max_message_count=10, max_wait_time=5)\n\n                for msg in received_msgs:\n                    result = True\n                    message = \"\"\n\n                    try:\n                        message = json.loads(str(msg))\n                        result = (yield parse_obj_as(DeploymentStatusUpdateMessage, message))\n                    except (json.JSONDecodeError, ValidationError):\n                        logging.error(strings.DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT)\n\n                    if result:\n                        logging.info(f\"Received deployment status update message with correlation ID {msg.correlation_id}: {message}\")\n                        await receiver.complete_message(msg)\n\n\ndef create_updated_deployment_document(workspace: Workspace, message: DeploymentStatusUpdateMessage):\n    \"\"\"Take a workspace and a deployment status update message and updates workspace with the message contents\n\n    Args:\n        workspace ([Workspace]): Workspace to update\n        message ([DeploymentStatusUpdateMessage]): Message which contains the updated information\n\n    Returns:\n        [Workspace]: Workspace with the deployment sub doc updated\n    \"\"\"\n    workspace.deployment.status = message.status\n    workspace.deployment.message = message.message\n    return workspace\n\n\ndef update_status_in_database(workspace_repo: WorkspaceRepository, message: DeploymentStatusUpdateMessage):\n    \"\"\"Updates the deployment sub document with message content\n\n    Args:\n        workspace_repo ([WorkspaceRepository]): Handle to the workspace repository\n        message ([DeploymentStatusUpdateMessage]): Message which contains the updated information\n\n    Returns:\n        [bool]: True if document is updated, False otherwise.\n    \"\"\"\n    result = False\n\n    try:\n        workspace = workspace_repo.get_workspace_by_workspace_id(message.id)\n        workspace_repo.update_workspace(create_updated_deployment_document(workspace, message))\n        result = True\n    except EntityDoesNotExist:\n        # Marking as true as this message will never succeed anyways and should be removed from the queue.\n        result = True\n        error_string = strings.DEPLOYMENT_STATUS_ID_NOT_FOUND.format(message.id)\n        logging.error(error_string)\n    except Exception as e:\n        logging.error(strings.STATE_STORE_ENDPOINT_NOT_RESPONDING + \" \" + str(e))\n\n    return result\n\n\nasync def receive_message_and_update_deployment(app: FastAPI) -> None:\n    \"\"\"\n    Receives messages from the deployment status update queue and updates the status for\n    the associated resource in the state store.\n    Args:\n        app ([FastAPI]): Handle to the currently running app\n    \"\"\"\n    receive_message_gen = receive_message()\n\n    try:\n        async for message in receive_message_gen:\n            workspace_repo = WorkspaceRepository(get_db_client(app))\n            result = update_status_in_database(workspace_repo, message)\n            await receive_message_gen.asend(result)\n    except StopAsyncIteration:  # the async generator when finished signals end with this exception.\n        pass\n", "path": "management_api_app/service_bus/deployment_status_update.py"}], "after_files": [{"content": "PONG = \"pong\"\n\n# API Descriptions\nAPI_GET_HEALTH_STATUS = \"Get health status\"\n\nAPI_GET_ALL_WORKSPACES = \"Get all workspaces\"\nAPI_GET_WORKSPACE_BY_ID = \"Get workspace by Id\"\nAPI_CREATE_WORKSPACE = \"Create a workspace\"\n\nAPI_GET_STATUS_OF_SERVICES = \"Get status of services\"\n\nAPI_GET_WORKSPACE_TEMPLATES = \"Get workspace template names\"\nAPI_CREATE_WORKSPACE_TEMPLATES = \"Create workspace template\"\nAPI_GET_WORKSPACE_TEMPLATE_BY_NAME = \"Get workspace template by name\"\n\n# State store status\nOK = \"OK\"\nNOT_OK = \"Not OK\"\nCOSMOS_DB = \"Cosmos DB\"\nSTATE_STORE_ENDPOINT_NOT_RESPONDING = \"State Store endpoint is not responding\"\nUNSPECIFIED_ERROR = \"Unspecified error\"\n\n# Error strings\nACCESS_APP_IS_MISSING_ROLE = \"The App is missing role\"\nACCESS_PLEASE_SUPPLY_APP_ID = \"Please supply the app_id for the AAD application\"\nACCESS_UNABLE_TO_GET_INFO_FOR_APP = \"Unable to get app info for app:\"\nAUTH_NOT_ASSIGNED_TO_ADMIN_ROLE = \"Not assigned to admin role\"\nAUTH_COULD_NOT_VALIDATE_CREDENTIALS = \"Could not validate credentials\"\nINVALID_AUTH_PROVIDER = \"Invalid authentication provider\"\nUNABLE_TO_REPLACE_CURRENT_TEMPLATE = \"Unable to replace the existing 'current' template with this name\"\nUNABLE_TO_PROCESS_REQUEST = \"Unable to process request\"\nWORKSPACE_DOES_NOT_EXIST = \"Workspace does not exist\"\nWORKSPACE_TEMPLATE_DOES_NOT_EXIST = \"Could not retrieve the 'current' template with this name\"\nWORKSPACE_TEMPLATE_VERSION_EXISTS = \"A template with this version already exists\"\n\n\n# Resource Status\nRESOURCE_STATUS_NOT_DEPLOYED = \"not_deployed\"\nRESOURCE_STATUS_DEPLOYING = \"deploying\"\nRESOURCE_STATUS_DEPLOYED = \"deployed\"\nRESOURCE_STATUS_DELETING = \"deleting\"\nRESOURCE_STATUS_DELETED = \"deleted\"\nRESOURCE_STATUS_FAILED = \"failed\"\n\n# Resource Type\nRESOURCE_TYPE_WORKSPACE = \"workspace\"\nRESOURCE_TYPE_SERVICE = \"service\"\n\n# Deployments\nRESOURCE_STATUS_NOT_DEPLOYED_MESSAGE = \"This resource has not yet been deployed\"\n\n# Service bus\nSERVICE_BUS_GENERAL_ERROR_MESSAGE = \"Service bus failure\"\nDEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT = \"Service bus message is not formatted correctly\"\nDEPLOYMENT_STATUS_ID_NOT_FOUND = \"Service bus message refers to resource id = {} which does not exist\"\n\n# Workspace creation validation\nMISSING_REQUIRED_PARAMETERS = \"Missing required parameters\"\nINVALID_EXTRA_PARAMETER = \"Invalid extra parameters\"\nPARAMETERS_WITH_WRONG_TYPE = \"Parameters with wrong type\"\n", "path": "management_api_app/resources/strings.py"}, {"content": "import json\nimport logging\nfrom contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom pydantic import ValidationError, parse_obj_as\n\nfrom azure.servicebus.aio import ServiceBusClient\nfrom azure.identity.aio import DefaultAzureCredential\n\nfrom core import config\nfrom resources import strings\nfrom db.errors import EntityDoesNotExist\nfrom api.dependencies.database import get_db_client\nfrom db.repositories.workspaces import WorkspaceRepository\nfrom models.domain.workspace import DeploymentStatusUpdateMessage, Workspace\n\n\n@asynccontextmanager\nasync def default_credentials():\n    \"\"\"\n    Context manager which yields the default credentials.\n    \"\"\"\n    credential = DefaultAzureCredential(managed_identity_client_id=config.MANAGED_IDENTITY_CLIENT_ID)\n    yield credential\n    await credential.close()\n\n\nasync def receive_message():\n    \"\"\"\n    This method is an async generator which receives messages from service bus\n    and yields those messages. If the yielded function return True the message is\n    marked complete.\n    \"\"\"\n    async with default_credentials() as credential:\n        service_bus_client = ServiceBusClient(config.SERVICE_BUS_FULLY_QUALIFIED_NAMESPACE, credential)\n\n        async with service_bus_client:\n            receiver = service_bus_client.get_queue_receiver(queue_name=config.SERVICE_BUS_DEPLOYMENT_STATUS_UPDATE_QUEUE)\n\n            async with receiver:\n                received_msgs = await receiver.receive_messages(max_message_count=10, max_wait_time=5)\n\n                for msg in received_msgs:\n                    result = True\n                    message = \"\"\n\n                    try:\n                        message = json.loads(str(msg))\n                        result = (yield parse_obj_as(DeploymentStatusUpdateMessage, message))\n                    except (json.JSONDecodeError, ValidationError) as e:\n                        logging.error(f\"{strings.DEPLOYMENT_STATUS_MESSAGE_FORMAT_INCORRECT}: {e}\")\n\n                    if result:\n                        logging.info(f\"Received deployment status update message with correlation ID {msg.correlation_id}: {message}\")\n                        await receiver.complete_message(msg)\n\n\ndef create_updated_deployment_document(workspace: Workspace, message: DeploymentStatusUpdateMessage):\n    \"\"\"Take a workspace and a deployment status update message and updates workspace with the message contents\n\n    Args:\n        workspace ([Workspace]): Workspace to update\n        message ([DeploymentStatusUpdateMessage]): Message which contains the updated information\n\n    Returns:\n        [Workspace]: Workspace with the deployment sub doc updated\n    \"\"\"\n    workspace.deployment.status = message.status\n    workspace.deployment.message = message.message\n    return workspace\n\n\ndef update_status_in_database(workspace_repo: WorkspaceRepository, message: DeploymentStatusUpdateMessage):\n    \"\"\"Updates the deployment sub document with message content\n\n    Args:\n        workspace_repo ([WorkspaceRepository]): Handle to the workspace repository\n        message ([DeploymentStatusUpdateMessage]): Message which contains the updated information\n\n    Returns:\n        [bool]: True if document is updated, False otherwise.\n    \"\"\"\n    result = False\n\n    try:\n        workspace = workspace_repo.get_workspace_by_workspace_id(message.id)\n        workspace_repo.update_workspace(create_updated_deployment_document(workspace, message))\n        result = True\n    except EntityDoesNotExist:\n        # Marking as true as this message will never succeed anyways and should be removed from the queue.\n        result = True\n        error_string = strings.DEPLOYMENT_STATUS_ID_NOT_FOUND.format(message.id)\n        logging.error(error_string)\n    except Exception as e:\n        logging.error(strings.STATE_STORE_ENDPOINT_NOT_RESPONDING + \" \" + str(e))\n\n    return result\n\n\nasync def receive_message_and_update_deployment(app: FastAPI) -> None:\n    \"\"\"\n    Receives messages from the deployment status update queue and updates the status for\n    the associated resource in the state store.\n    Args:\n        app ([FastAPI]): Handle to the currently running app\n    \"\"\"\n    receive_message_gen = receive_message()\n\n    try:\n        async for message in receive_message_gen:\n            workspace_repo = WorkspaceRepository(get_db_client(app))\n            result = update_status_in_database(workspace_repo, message)\n            await receive_message_gen.asend(result)\n    except StopAsyncIteration:  # the async generator when finished signals end with this exception.\n        pass\n", "path": "management_api_app/service_bus/deployment_status_update.py"}]}