I am a new learner in Python and here I have try-except to catch ValueErrors and conditional statements to catch the same error as well.
import re
def main():
print(convert(input("Hours: ")))
def convert(s):
try:
# matches := re.search(r"^(\d )\:?(. )? to (\d )\:?(. )?$", s)
if (matches := re.search(r"^(\d )\:?(. )? to (\d )\:?(. )?$", s)) and s.__contains__("AM"):
matchesGroup1 = matches.group(1)
matchesGroup2 = matches.group(2).split(" ")
matchesGroup3 = matches.group(3)
matchesGroup4 = matches.group(4).split(" ")
if 0 < int(matches.group(1)) <= 12 and 0 < int(matches.group(3)) <= 12:
if matchesGroup2[1] == "AM" and matchesGroup4[1] == "PM":
if matchesGroup1 == "12" and matchesGroup3 == "12":
matchesGroup1 = "00"
matchesGroup3 = "12"
else:
matchesGroup3 = int(matchesGroup3) 12
matchesGroup1 = "0" matchesGroup1
else:
if matchesGroup1 == "12" and matchesGroup3 == "12":
matchesGroup3 = "12"
matchesGroup1 = "00"
else:
matchesGroup1 = int(matchesGroup1) 12
matchesGroup3 = "0" matchesGroup3
if len(matchesGroup2[0]) == 0 and len(matchesGroup4[0]) == 0:
matchesGroup2[0] = "00"
matchesGroup4[0] = "00"
elif "00" <= matchesGroup2[0] <= "59" and "00" <= matchesGroup4[0] <= "59":
pass
else:
raise Exception
return f"{matchesGroup1}:{matchesGroup2[0]} to {matchesGroup3}:{matchesGroup4[0]}"
else:
raise Exception
except Exception:
raise ValueError
except ValueError:
raise ValueError
if __name__ == "__main__":
main()
And I am testing it with PyTest with help of assert. But, in the last line Pytest giving working.py:45: Exception
, test_working.py:9:
and working.py:48: ValueError
. Can anyone explain what it's so and how do i fix it?
import pytest
from working import convert
def test_convert():
assert convert("9 AM to 5 PM") == "09:00 to 17:00"
assert convert("9:00 AM to 5:00 PM") == "09:00 to 17:00"
assert convert("10 PM to 8 AM") == "22:00 to 08:00"
assert convert("10:30 PM to 8:50 AM") == "22:30 to 08:50"
assert convert("9:00 AM 5:00 PM") == ValueError
CodePudding user response:
Instead of assert convert("9:00 AM 5:00 PM") == ValueError
try using the following syntax:
with pytest.raises(ValueError):
convert("9:00 AM 5:00 PM")
The issue is that you need to tell the testing framework that you expect to raise an error. Otherwise it won't know whether the error it hits was deliberate or not. With the above code, pytest will now raise an error if that code fails to raise an exception. Not only that, it'll also ensure that the exception you were hoping to raise doesn't stop the execution of the rest of your tests.