Skip to content

Commit cb898a8

Browse files
authored
Merge pull request #146 from QuanMPhm/bug/tz
Fix bug with timezone-aware datetimes in billing.py
2 parents 737b77f + 17f95e9 commit cb898a8

2 files changed

Lines changed: 46 additions & 3 deletions

File tree

src/openstack_billing_db/billing.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,8 @@ def get_runtime_for_instance(
9494
runtime = instance.get_runtime_during(start, end)
9595
for interval_start, interval_end in excluded_intervals:
9696
excluded_runtime = instance.get_runtime_during(
97-
start_time=interval_start,
98-
end_time=interval_end,
97+
start_time=interval_start.replace(tzinfo=None),
98+
end_time=interval_end.replace(tzinfo=None),
9999
)
100100
runtime = runtime - excluded_runtime
101101

src/openstack_billing_db/tests/unit/test_billing.py

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import uuid
2-
from datetime import datetime, timedelta
2+
from datetime import datetime, timedelta, timezone
33
import pytest
44

55
from openstack_billing_db import billing
@@ -36,6 +36,49 @@ def test_instance_simple_runtime():
3636
assert r.total_seconds_stopped == 0
3737

3838

39+
def test_instance_runtime_timezone_mismatch():
40+
"""Test that mismatched timezones between start/end and excluded_intervals raises an error."""
41+
time = datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0)
42+
events = [
43+
InstanceEvent(time=time, name="create", message=""),
44+
InstanceEvent(time=time + timedelta(days=15), name="delete", message=""),
45+
]
46+
i = Instance(
47+
uuid=uuid.uuid4().hex, name=uuid.uuid4().hex, flavor=FLAVORS[1], events=events
48+
)
49+
50+
# Start and end are timezone-naive
51+
start = datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0)
52+
end = datetime(year=2000, month=2, day=1, hour=0, minute=0, second=0)
53+
54+
# excluded_intervals are timezone-aware
55+
excluded_intervals = [
56+
(
57+
datetime(
58+
year=2000,
59+
month=1,
60+
day=7,
61+
hour=0,
62+
minute=0,
63+
second=0,
64+
tzinfo=timezone.utc,
65+
),
66+
datetime(
67+
year=2000,
68+
month=1,
69+
day=8,
70+
hour=0,
71+
minute=0,
72+
second=0,
73+
tzinfo=timezone.utc,
74+
),
75+
),
76+
]
77+
78+
# Runs without error
79+
billing.get_runtime_for_instance(i, start, end, excluded_intervals)
80+
81+
3982
def test_billing_add_su_hours():
4083
invoice = billing.ProjectInvoice(
4184
project_name="foo",

0 commit comments

Comments
 (0)