Skip to content

Test/location #78

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 72 additions & 60 deletions .github/workflows/unit-test.yml
Original file line number Diff line number Diff line change
@@ -1,71 +1,83 @@
name: Unit Tests
name: Unit Tests and SonarCloud Analysis

on:
workflow_dispatch:
pull_request:
branches:
- main
types: [reopened, synchronize, opened]

push:
branches:
- main

jobs:
unit-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0 # Ensure full history is available
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0 # Ensure full history is available

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3

- name: Verify Docker installation
run: |
docker --version
docker compose version
- name: Verify Docker installation
run: |
docker --version
docker compose version

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

MULTIPLE WHITESPACE ANOMALIES DETECTED: CODE CLEANLINESS SUBOPTIMAL.

TRAILING WHITESPACE EXISTS ON MULTIPLE LINES. WHITESPACE MUST BE ELIMINATED FOR OPTIMAL YAML PARSING AND HUMAN READABILITY.

-        
+
-          
+
-          
+
-          
+
-          
+
-          
+
-          
+
-          
+
-          
+
-            
+
-          
+

Also applies to: 34-34, 36-36, 41-41, 43-43, 49-49, 52-52, 56-56, 71-71, 76-76, 83-83

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 29-29: trailing spaces

(trailing-spaces)

- name: Determine changed services
id: check_changes
run: |
echo "Checking for changes in PR..."

- name: Determine changed service
id: check_changes
run: |
echo "Checking for changes in PR..."

CHANGED_FILES=$(git diff --name-only origin/main...HEAD)

echo "Changed files:"
echo "$CHANGED_FILES"

SERVICES=("auth-service" "location-service" "ambulance-finder-service" "trip-service")

SERVICE_CHANGED="none"

for SERVICE in "${SERVICES[@]}"; do
if echo "$CHANGED_FILES" | grep -q "^$SERVICE/"; then
SERVICE_CHANGED=$SERVICE
break
fi
done

echo "SERVICE_CHANGED=$SERVICE_CHANGED" >> $GITHUB_ENV

- name: Run unit tests
if: env.SERVICE_CHANGED != 'none'
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
RIDER_PASSWORD_1: ${{ secrets.RIDER_PASSWORD_1 }}
RIDER_PASSWORD_2: ${{ secrets.RIDER_PASSWORD_2 }}
DRIVER_PASSWORD_1: ${{ secrets.DRIVER_PASSWORD_1 }}
DRIVER_PASSWORD_2: ${{ secrets.DRIVER_PASSWORD_2 }}
CHANGED_FILES=$(git diff --name-only origin/main...HEAD)

echo "Changed files:"
echo "$CHANGED_FILES"

run: |
docker compose -f ${{ env.SERVICE_CHANGED }}/docker-compose.dev.yml up --build --abort-on-container-exit ${{ env.SERVICE_CHANGED }}-test

SERVICES=("auth-service" "location-service" "ambulance-finder-service" "trip-service")

CHANGED_SERVICES=()

for SERVICE in "${SERVICES[@]}"; do
if echo "$CHANGED_FILES" | grep -q "^$SERVICE/"; then
CHANGED_SERVICES+=("$SERVICE")
fi
done

# Convert array to comma-separated string
CHANGED_SERVICES_STR=$(IFS=,; echo "${CHANGED_SERVICES[*]}")

# Set environment variables
echo "CHANGED_SERVICES=$CHANGED_SERVICES_STR" >> $GITHUB_ENV
if [ -n "$CHANGED_SERVICES_STR" ]; then echo "HAS_CHANGES=true" >> $GITHUB_ENV; else echo "HAS_CHANGES=false" >> $GITHUB_ENV; fi

# For debugging
echo "CHANGED_SERVICES=$CHANGED_SERVICES_STR"

- name: Debug Coverage Report
if: env.SERVICE_CHANGED != 'none'
run: |
echo "Service Changed: ${{ env.SERVICE_CHANGED }}"
pwd
ls ${{ env.SERVICE_CHANGED }}
cat ${{ env.SERVICE_CHANGED }}/coverage.xml || echo "No coverage.xml found"

- name: Run unit tests for each changed service
if: env.HAS_CHANGES == 'true'
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
RIDER_PASSWORD_1: ${{ secrets.RIDER_PASSWORD_1 }}
RIDER_PASSWORD_2: ${{ secrets.RIDER_PASSWORD_2 }}
DRIVER_PASSWORD_1: ${{ secrets.DRIVER_PASSWORD_1 }}
DRIVER_PASSWORD_2: ${{ secrets.DRIVER_PASSWORD_2 }}
run: |
IFS=',' read -r -a SERVICES_ARRAY <<< "${{ env.CHANGED_SERVICES }}"

for SERVICE in "${SERVICES_ARRAY[@]}"; do
echo "Running tests for $SERVICE"
docker compose -f $SERVICE/docker-compose.dev.yml up --build --abort-on-container-exit $SERVICE-test
done

Comment on lines +61 to +76
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

ENHANCED TEST EXECUTION STRATEGY.

MULTI-SERVICE TEST EXECUTION STRATEGY IMPLEMENTED WITH DEPENDENCY INJECTION. THIS ALLOWS PARALLEL TESTING OF ALL CHANGED SERVICES.

FORMATTING ISSUE: TRAILING WHITESPACE DETECTED.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 71-71: trailing spaces

(trailing-spaces)


[error] 76-76: trailing spaces

(trailing-spaces)


- name: SonarQube Scan
if: env.SERVICE_CHANGED != 'none'
uses: SonarSource/sonarqube-scan-action@v5
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
- name: SonarCloud Scan
if: env.HAS_CHANGES == 'true'
uses: SonarSource/sonarqube-scan-action@v5
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}

3 changes: 1 addition & 2 deletions auth-service/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ FROM python:3.13.2-alpine AS base
RUN adduser -D myuser

# Set the working directory in the container
WORKDIR /app
WORKDIR /auth-service

# Copy the virtual environment from the build stage
COPY --from=build /opt/venv /opt/venv
Expand All @@ -48,7 +48,6 @@ EXPOSE 8000
FROM base AS test
COPY ./pytest.ini .
COPY ./auth-service/tests ./tests
COPY ./auth-service/coverage-reports ./coverage-reports
COPY ./conftest.py ./tests

ENV PYTHONPATH=.
Expand Down
74 changes: 35 additions & 39 deletions auth-service/app/services/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,36 +48,37 @@ def create_user(session: Session, user_data: dict):
user_data["mobile"],
)

if email_exists:
raise HTTPException(
status_code=409,
detail="This email is already registered. Use a different email."
)
if mobile_exists:
raise HTTPException(
status_code=409,
detail="This mobile number is already registered. Use a different mobile."
)

hashed_password = hash_password(user_data["password"])

if user_data["user_type"] == "driver":
new_user = Driver(
name=user_data["name"],
mobile=user_data["mobile"],
email=user_data["email"],
password=hashed_password,
)
elif user_data["user_type"] == "rider":
new_user = Rider(
name=user_data["name"],
mobile=user_data["mobile"],
email=user_data["email"],
password=hashed_password,
)
else:
raise HTTPException(status_code=400, detail="Invalid user type")
try:
if email_exists:
raise HTTPException(
status_code=409,
detail="This email is already registered. Use a different email."
)
if mobile_exists:
raise HTTPException(
status_code=409,
detail="This mobile number is already registered. Use a different mobile."
)

hashed_password = hash_password(user_data["password"])

if user_data["user_type"] == "driver":
new_user = Driver(
name=user_data["name"],
mobile=user_data["mobile"],
email=user_data["email"],
password=hashed_password,
)
elif user_data["user_type"] == "rider":
new_user = Rider(
name=user_data["name"],
mobile=user_data["mobile"],
email=user_data["email"],
password=hashed_password,
)
else:
raise HTTPException(status_code=400, detail="Invalid user type")

session.add(new_user)
session.commit()
session.refresh(new_user)
Expand All @@ -86,13 +87,10 @@ def create_user(session: Session, user_data: dict):
"message": f"{user_data["user_type"]} {new_user.name} registered successfully",
}

except HTTPException:
session.rollback()
raise

except Exception as exc:
print(exc)
session.rollback()
raise INTERNAL_SERVER_ERROR from exc
raise


def authenticate_user(
Expand Down Expand Up @@ -127,8 +125,10 @@ def authenticate_user(
)
else:
raise HTTPException(status_code=400, detail="Invalid user type")

if not user or not verify_password(password, user.password):
raise HTTPException(status_code=401, detail="Invalid credentials")

return {
"success": True,
"name": user.name,
Expand All @@ -142,12 +142,8 @@ def authenticate_user(
"email": user.email,
}

except HTTPException:
session.rollback()
raise

except Exception as exc:
print(exc)
session.rollback()
raise INTERNAL_SERVER_ERROR from exc
raise

14 changes: 8 additions & 6 deletions auth-service/docker-compose.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ services:
environment:
DATABASE_URL: ${DATABASE_URL}
volumes:
- .:/app
- /app/app/models
- .:/auth-service
- /auth-service/app/models
command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]

auth-service-test:
Expand All @@ -28,7 +28,9 @@ services:
DRIVER_PASSWORD_2: ${DRIVER_PASSWORD_2}

volumes:
- /app/app/models
- /app/tests
- ./:/app/ # Mount the whole current directory to /app in the container
command: ["pytest", "-v", "--cov=app", "--cov-report=xml:/app/coverage-reports/coverage.xml", "tests/unittest"]
- /auth-service/app/models
- /auth-service/tests
- ./:/auth-service
command: >
sh -c "pytest -v --cov=app --cov-report=xml:coverage.xml tests/unittest &&
sed -i 's|/auth-service/app|auth-service/app|g' coverage.xml"
Comment on lines +31 to +36
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

COMMAND FORMAT AND VOLUME PATHS UPDATED.

NEW SHELL COMMAND FORMAT IMPLEMENTS BETTER TEST COVERAGE REPORTING. VOLUME PATHS UPDATED TO MATCH NEW DIRECTORY STRUCTURE.

FORMATTING ISSUES DETECTED:

  1. TRAILING SPACES ON LINE 33
  2. MISSING NEWLINE AT END OF FILE
-      - ./:/auth-service 
+      - ./:/auth-service

RECOMMEND ADDING NEWLINE AT END OF FILE.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- /auth-service/app/models
- /auth-service/tests
- ./:/auth-service
command: >
sh -c "pytest -v --cov=app --cov-report=xml:coverage.xml tests/unittest &&
sed -i 's|/auth-service/app|auth-service/app|g' coverage.xml"
- /auth-service/app/models
- /auth-service/tests
- ./:/auth-service
command: >
sh -c "pytest -v --cov=app --cov-report=xml:coverage.xml tests/unittest &&
sed -i 's|/auth-service/app|auth-service/app|g' coverage.xml"
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 33-33: trailing spaces

(trailing-spaces)


[error] 36-36: no new line character at the end of file

(new-line-at-end-of-file)

3 changes: 1 addition & 2 deletions location-service/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ FROM python:3.13.2-alpine AS base
RUN adduser -D myuser

# Set the working directory in the container
WORKDIR /app
WORKDIR /location-service

# Copy the virtual environment from the build stage
COPY --from=build /opt/venv /opt/venv
Expand All @@ -51,7 +51,6 @@ EXPOSE 8000
FROM base AS test
COPY ./pytest.ini .
COPY ./location-service/tests ./tests
COPY ./location-service/coverage-reports ./coverage-reports
COPY ./conftest.py ./tests

ENV PYTHONPATH=.
Expand Down
3 changes: 1 addition & 2 deletions location-service/app/db.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import os
from sqlmodel import create_engine, Session
# from app.core.config import settings

DATABASE_URL = os.getenv("DATABASE_URL")

Expand All @@ -15,4 +14,4 @@ def get_session():
Dependency function to get a new database session.
"""
with Session(engine) as session:
yield session
yield session
2 changes: 1 addition & 1 deletion location-service/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@

@app.get("/api", tags=["Root"])
def read_root():
return {"message": "Welcome to the location-service"}
return {"message": "Welcome to the location-service"}
Comment on lines 19 to +20
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

FUNCTION LACKS RETURN TYPE ANNOTATION.

STATIC ANALYSIS INDICATES MISSING RETURN TYPE FOR PUBLIC FUNCTION.

- def read_root():
+ def read_root() -> dict[str, str]:
    return {"message": "Welcome to the location-service"}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def read_root():
return {"message": "Welcome to the location-service"}
return {"message": "Welcome to the location-service"}
def read_root() -> dict[str, str]:
return {"message": "Welcome to the location-service"}
🧰 Tools
🪛 Ruff (0.8.2)

19-19: Missing return type annotation for public function read_root

(ANN201)

2 changes: 1 addition & 1 deletion location-service/app/schemas/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ class ErrorResponse(BaseModel):

class LocationRemoveResponse(BaseModel):
success: bool
message: Optional[str] = None
message: Optional[str] = None
20 changes: 5 additions & 15 deletions location-service/app/services/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,11 @@ def add_driver_location(
session.add(driver_location)
session.commit()
return {"success": True}

except HTTPException as e:
print(e)
session.rollback()
raise

except Exception as exc:
print(exc)
session.rollback()
raise INTERNAL_SERVER_ERROR_MSG from exc
raise

def update_driver_location(
session: Session,
Expand All @@ -59,14 +54,11 @@ def update_driver_location(
session.merge(driver_location)
session.commit()
return {"success": True}

except HTTPException:
session.rollback()
raise

except Exception as exc:
print(exc)
session.rollback()
raise INTERNAL_SERVER_ERROR from exc
raise

def remove_driver_location(
session: Session,
Expand All @@ -90,10 +82,8 @@ def remove_driver_location(
session.commit()
return {"success": True}

except HTTPException:
session.rollback()
raise

except Exception as exc:
print(exc)
session.rollback()
raise INTERNAL_SERVER_ERROR from exc
raise
Loading