Skip to content

Commit

Permalink
add init healthcheck code (#40)
Browse files Browse the repository at this point in the history
Resolves DST-232: added health check code for get response and logging test
  • Loading branch information
ccheng26 authored Jun 11, 2024
1 parent 1f2e942 commit fb9ce50
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 8 deletions.
35 changes: 27 additions & 8 deletions 05-assistive-chatbot/chatbot_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
from typing import Dict

import dotenv
from fastapi import Body, FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi import Body, FastAPI, Request, status
from pydantic import BaseModel

import chatbot

Expand Down Expand Up @@ -52,19 +52,38 @@ def query(message: str | Dict):
return response


# Make sure to use async functions for faster responses
@app.get("/healthcheck")
async def healthcheck(request: Request):
class HealthCheck(BaseModel):
"""Response model to validate and return when performing a health check."""

status: str
build_date: str
git_sha: str
service_name: str
hostname: str


@app.get(
"/healthcheck",
tags=["healthcheck"],
summary="Perform a Health Check",
response_description="Return HTTP Status Code 200 (OK)",
status_code=status.HTTP_200_OK,
response_model=HealthCheck,
)
async def healthcheck(request: Request) -> HealthCheck:
# Make sure to use async functions for faster responses
logger.info(request.headers)
# TODO: Add a health check - https://pypi.org/project/fastapi-healthchecks/

git_sha = os.environ.get("GIT_SHA", "")
build_date = os.environ.get("BUILD_DATE", "")

service_name = os.environ.get("SERVICE_NAME", "")
hostname = f"{platform.node()} {socket.gethostname()}"

logger.info("Returning: Healthy %s %s", build_date, git_sha)
return HTMLResponse(f"Healthy {git_sha} built at {build_date}<br/>{service_name} {hostname}")
logger.info(f"Healthy {git_sha} built at {build_date}<br/>{service_name} {hostname}")
return HealthCheck(
build_date=build_date, git_sha=git_sha, status="OK", service_name=service_name, hostname=hostname
)


ALLOWED_ENV_VARS = [
Expand Down
Empty file.
22 changes: 22 additions & 0 deletions 05-assistive-chatbot/test/test_chatbot_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import json
import logging
import pytest

from fastapi.testclient import TestClient

from chatbot_api import app


@pytest.fixture(name="test_client")
def fixture_test_client():
return TestClient(app)


class TestAPI:
def test_read_healthcheck(self, caplog, test_client):
with caplog.at_level(logging.INFO, logger="chatbot.chatbot_api"):
response = test_client.get("/healthcheck")
response_data = json.loads(response.content)
assert response.status_code == 200
assert response_data["status"] == "OK"
assert "Healthy" in caplog.messages[1]

0 comments on commit fb9ce50

Please sign in to comment.