Skip to content
Closed
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
13 changes: 5 additions & 8 deletions backend/apps/owasp/models/project_health_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models.functions import Coalesce, ExtractMonth, TruncDate
from django.db.models.functions import Coalesce, TruncDate, TruncMonth
from django.utils import timezone

from apps.common.models import BulkSaveModel, TimestampedModel
Expand Down Expand Up @@ -210,21 +210,18 @@ def get_stats() -> ProjectHealthStatsNode:
)
total = stats["projects_count_total"] or 1 # Avoid division by zero
monthly_overall_metrics = (
ProjectHealthMetrics.objects.annotate(month=ExtractMonth("nest_created_at"))
.filter(
nest_created_at__gte=timezone.now() - timezone.timedelta(days=365)
) # Last year data
.order_by("month")
ProjectHealthMetrics.objects.annotate(month=TruncMonth("nest_created_at"))
.filter(nest_created_at__gte=timezone.now() - timezone.timedelta(days=365))
.values("month")
.distinct()
.annotate(
score=models.Avg("score"),
)
.order_by("month")
)
months = []
scores = []
for entry in monthly_overall_metrics:
months.append(entry["month"])
months.append(entry["month"].strftime("%b %Y"))
scores.append(entry["score"])

return ProjectHealthStatsNode(
Expand Down
65 changes: 64 additions & 1 deletion backend/tests/apps/owasp/models/project_health_metrics_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,5 +114,68 @@ def test_handle_days_calculation(self, field_name, expected_days):
metrics.last_released_at = self.FIXED_DATE
metrics.owasp_page_last_updated_at = self.FIXED_DATE
metrics.pull_request_last_created_at = self.FIXED_DATE

assert getattr(metrics, field_name) == expected_days

def test_get_stats_monthly_grouping_logic(self, mocker):
"""Should correctly format month and year strings from metrics."""
from django.db.models import QuerySet

mock_entry_1 = {"month": timezone.datetime(2024, 1, 1), "score": 80.0}
mock_entry_2 = {"month": timezone.datetime(2025, 1, 1), "score": 90.0}

mock_query = mocker.Mock(spec=QuerySet)
mock_query.aggregate.return_value = {
"projects_count_healthy": 1,
"projects_count_need_attention": 0,
"projects_count_unhealthy": 0,
"projects_count_total": 1,
"average_score": 85.0,
"total_contributors": 10,
"total_forks": 5,
"total_stars": 20,
}

chain = mock_query.annotate.return_value.filter.return_value.values.return_value
chain.annotate.return_value.order_by.return_value = [mock_entry_1, mock_entry_2]

mocker.patch.object(
ProjectHealthMetrics, "get_latest_health_metrics", return_value=mock_query
)
mocker.patch.object(
ProjectHealthMetrics.objects, "annotate", return_value=mock_query.annotate.return_value
)

stats = ProjectHealthMetrics.get_stats()

assert stats.monthly_overall_scores_months == ["Jan 2024", "Jan 2025"]
assert stats.monthly_overall_scores == [80.0, 90.0]

def test_get_stats_empty_state(self, mocker):
"""Should return empty lists when no metrics exist."""
mock_query = mocker.Mock()
mock_query.aggregate.return_value = {
"projects_count_healthy": 0,
"projects_count_need_attention": 0,
"projects_count_unhealthy": 0,
"projects_count_total": 0,
"average_score": 0.0,
"total_contributors": 0,
"total_forks": 0,
"total_stars": 0,
}

chain = mock_query.annotate.return_value.filter.return_value.values.return_value
chain.annotate.return_value.order_by.return_value = []

mocker.patch.object(
ProjectHealthMetrics, "get_latest_health_metrics", return_value=mock_query
)
mocker.patch.object(
ProjectHealthMetrics.objects, "annotate", return_value=mock_query.annotate.return_value
)

stats = ProjectHealthMetrics.get_stats()

assert stats.monthly_overall_scores == []
assert stats.monthly_overall_scores_months == []