Skip to content

Commit 59b5fc3

Browse files
authored
Fix leap year unittest failures. (#4953)
1 parent 9e11981 commit 59b5fc3

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

koku/koku/test_pg_partition.py

+22-3
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
# Copyright 2021 Red Hat Inc.
33
# SPDX-License-Identifier: Apache-2.0
44
#
5+
import calendar
56
import datetime
67
import json
78
import uuid
9+
from datetime import timedelta
810

911
from django.db import connection as conn
1012
from django_tenants.utils import schema_context
@@ -22,6 +24,15 @@ def _execute(sql, params=None):
2224
return cur
2325

2426

27+
def handle_leap_year_overflow(date, years):
28+
try:
29+
new_date = date.replace(year=(date.year + years))
30+
except ValueError:
31+
# If an error occurs, set the day to the last day of the month
32+
new_date = (date + timedelta(days=31)).replace(year=(date.year + years), day=1)
33+
return new_date
34+
35+
2536
def _get_table_partition_info(schema, table):
2637
sql = """
2738
select c.relkind,
@@ -909,7 +920,7 @@ def test_repartition_table(self):
909920
"""
910921
with schema_context(self.schema_name):
911922
aws_lids = AWSCostEntryLineItemDailySummary.objects.order_by("-usage_start")[0]
912-
year10_usage_start = aws_lids.usage_start.replace(year=(aws_lids.usage_start.year + 10))
923+
year10_usage_start = handle_leap_year_overflow(aws_lids.usage_start, 10)
913924
aws_lids.usage_start = year10_usage_start
914925
aws_lids.save()
915926
year10_count = 0
@@ -952,10 +963,11 @@ def test_repartition_all_tables(self):
952963
"""
953964
with schema_context(self.schema_name):
954965
aws_lids = AWSCostEntryLineItemDailySummary.objects.order_by("-usage_start")[0]
966+
aws_lids.usage_start = handle_leap_year_overflow(aws_lids.usage_start, 11)
955967
aws_lids.usage_start = aws_lids.usage_start.replace(year=(aws_lids.usage_start.year + 11))
956968
aws_lids.save()
957969
ocp_lids = OCPUsageLineItemDailySummary.objects.order_by("-usage_start")[0]
958-
ocp_lids.usage_start = ocp_lids.usage_start.replace(year=(aws_lids.usage_start.year + 11))
970+
ocp_lids.usage_start = handle_leap_year_overflow(aws_lids.usage_start, 11)
959971
ocp_lids.save()
960972
with conn.cursor() as cur:
961973
cur.execute(
@@ -1019,7 +1031,14 @@ def test_repartition_all_tables(self):
10191031
if new_ocp_lids.usage_start.day < 28
10201032
else new_ocp_lids.usage_start.day - 1
10211033
)
1022-
new_ocp_lids.usage_start = ocp_lids.usage_start.replace(day=new_day)
1034+
if (
1035+
ocp_lids.usage_start.month == 2
1036+
and ocp_lids.usage_start.day == 28
1037+
and calendar.isleap(ocp_lids.usage_start.year)
1038+
):
1039+
new_ocp_lids.usage_start = ocp_lids.usage_start.replace(day=29)
1040+
else:
1041+
new_ocp_lids.usage_start = ocp_lids.usage_start.replace(day=new_day)
10231042
new_ocp_lids.save()
10241043

10251044
with conn.cursor() as cur:

0 commit comments

Comments
 (0)