Skip to content

Instantly share code, notes, and snippets.

@alessandrofelder
Last active November 2, 2022 19:37
Show Gist options
  • Save alessandrofelder/7b82bddae1776f8f1d31bf2efd1ad7f8 to your computer and use it in GitHub Desktop.
Save alessandrofelder/7b82bddae1776f8f1d31bf2efd1ad7f8 to your computer and use it in GitHub Desktop.
sample solution: write a negative test
import pytest
from times import compute_overlap_time, time_range
# two ways of doing the same negative test. Only one is needed.
def test_negative_time_range():
# first possible solution
with pytest.raises(ValueError) as e:
time_range("2010-01-12 10:00:00", "2010-01-12 09:30:00")
# lines after the error is raised are not executed in the pytest.raises context, so the assertion has to be outside the "with"
assert e.match('The end of the time range has to come strictly after its start.')
def test_negative_time_range_alternative():
# an alternative solution for using pytest.raises to check that the error message is as expected
expected_error_message = 'The end of the time range has to come strictly after its start.'
with pytest.raises(ValueError, match=expected_error_message):
time_range("2010-01-12 10:00:00", "2010-01-12 09:30:00")
import datetime
def time_range(start_time, end_time, number_of_intervals=1, gap_between_intervals_s=0):
start_time_s = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
end_time_s = datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
if(start_time_s>=end_time_s):
raise ValueError('The end of the time range has to come strictly after its start.')
d = (end_time_s - start_time_s).total_seconds() / number_of_intervals + gap_between_intervals_s * (1 / number_of_intervals - 1)
sec_range = [(start_time_s + datetime.timedelta(seconds=i * d + i * gap_between_intervals_s),
start_time_s + datetime.timedelta(seconds=(i + 1) * d + i * gap_between_intervals_s))
for i in range(number_of_intervals)]
return [(ta.strftime("%Y-%m-%d %H:%M:%S"), tb.strftime("%Y-%m-%d %H:%M:%S")) for ta, tb in sec_range]
def compute_overlap_time(range1, range2):
overlap_time = []
for start1, end1 in range1:
for start2, end2 in range2:
# both ranges need to start before the other ends, otherwise there is no overlap!
if start1 <= end2 and start2 <= end1:
low = max(start1, start2)
high = min(end1, end2)
if high == low:
continue
overlap_time.append((low, high))
return overlap_time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment