Skip to content

Commit 282ff86

Browse files
authored
[test] Fix flaky test that occurs when 2 consecutive generated date are not in the same second (#1014)
1 parent 69b11fb commit 282ff86

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

tests/01-unit/utils/test_opencti_stix2.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,24 @@ def test_format_date_with_tz(opencti_stix2: OpenCTIStix2):
6767
my_date_str = "2021-03-05T00:00:00.000Z"
6868
assert my_date_str == opencti_stix2.format_date(my_date)
6969
assert my_datetime_str == opencti_stix2.format_date(my_datetime_str)
70-
assert (
71-
str(
72-
datetime.datetime.now(tz=datetime.timezone.utc)
73-
.isoformat(timespec="seconds")
74-
.replace("+00:00", "")
75-
)
76-
in opencti_stix2.format_date()
70+
71+
# Test the behavior of format_date() when called without arguments.
72+
# Since it relies on the current time, avoid flaky results by comparing only up to the seconds, using dates generated immediately before and after the function call.
73+
my_now_date_1 = (
74+
datetime.datetime.now(tz=datetime.timezone.utc)
75+
.isoformat(timespec="seconds")
76+
.replace("+00:00", "")
77+
)
78+
stix_now_date = opencti_stix2.format_date()
79+
my_now_date_2 = (
80+
datetime.datetime.now(tz=datetime.timezone.utc)
81+
.isoformat(timespec="seconds")
82+
.replace("+00:00", "")
7783
)
84+
assert (str(my_now_date_1) in stix_now_date) or (
85+
str(my_now_date_2) in stix_now_date
86+
)
87+
7888
with pytest.raises(ValueError):
7989
opencti_stix2.format_date("No time")
8090

0 commit comments

Comments
 (0)