I am writing a regex that validates timer input, timer only accepts 0 and between 5 and 120 min in both hour format (1:30) and min format (90).
It fails on "2:01", "2:59" and "0:01", "0:02", "0:03", "0:04", "0:1", "0:2", "0:3", "0:4"
import re
import pytest
pattern = re.compile("^(?:0|[5-9]|[1-9][0-9]|1[01][0-9]|120|[0-2]:[0-5]?[0-9])$")
@pytest.mark.parametrize("zeros", ("0", "0:0", "0:00"))
def test_valid_0_format(zeros):
assert pattern.match(zeros)
@pytest.mark.parametrize("zeros", ("0:", "0::", "0:::", "0::0"))
def test_invalid_0_format(zeros):
assert not pattern.match(zeros)
@pytest.mark.parametrize("minutes", range(5, 121))
def test_valid_min_format_from_5_to_120(minutes: int):
assert pattern.match(f"{minutes}")
@pytest.mark.parametrize("time", ("3", "4"))
def test_invalid_min_format(time: str):
assert not pattern.match(time)
@pytest.mark.parametrize("time", ("0:00", "1:00", "2:00"))
def test_valid_hour_min_format(time):
assert pattern.match(time)
@pytest.mark.parametrize("hour", ("1:", "2:"))
def test_invalid_hour(hour):
assert not pattern.match(hour)
@pytest.mark.parametrize("i", range(5, 121))
def test_valid_hour_format_from_5_to_120(i: int):
hour, min = divmod(i, 60)
assert pattern.match(f"{hour}:{min}")
@pytest.mark.parametrize("i", range(5, 121))
def test_valid_hour_format_from_5_to_120_leading_0(i: int):
hour, min = divmod(i, 60)
assert pattern.match(f"{hour}:{min:02}")
@pytest.mark.parametrize(
"time",
("0:01", "0:02", "0:03", "0:04", "0:1", "0:2", "0:3", "0:4")
)
def test_invalid_hour_format_from_1_to_4(time):
assert not pattern.match(time)
@pytest.mark.parametrize(
"time",
("0:60", "1:60", "1:61", "2:01", "2:59", "3:0", "3:01")
)
def test_invalid_hour_min_format(time: str):
assert not pattern.match(time)