我正在嘗試撰寫一個函式來驗證包含 2 個日期(開始和結束)、目的地和價格的包
最初,我嘗試撰寫一個函式來“創建”日期并將它們放在一個串列中,然后比較它們以找出結束日期是否低于開始日期,但我認為這太復雜了,所以我求助于datetime內置模塊
但是,當我嘗試運行測驗函式時,它失敗并輸出此錯誤訊息
File "C:\Users\Anon\Desktop\Fac\FP\pythonProject\main.py", line 65, in valideaza_pachet
raise Exception(err)
Exception: wrong dates!
我認為我一定搞砸了valideaza_pachet()函式中的一個條件,但我不明白我做錯了什么
編碼:
import time
import calendar
from datetime import date, datetime
def creeaza_pachet(data_i, data_s, dest, pret):
# function that creates a tourism package, data_i = beginning date, data_s = end date, dest = destination and pret = price
return {
"data_i": data_i,
"data_s": data_s,
"dest": dest,
"pret": pret
}
def get_data_i(pachet):
# functie that returns the beginning date of the package
return pachet["data_i"]
def get_data_s(pachet):
# functie that returns the end date of the package
return pachet["data_s"]
def get_destinatie(pachet):
# functie that returns the destination of the package
return pachet["dest"]
def get_pret(pachet):
# functie that returns the price of the package
# input: pachet - un pachet
# output: pretul float > 0 al pachetului
return pachet["pret"]
def valideaza_pachet(pachet):
#functie that validates if a package was correctly introduced or not
#it raises an Exception as ex if any of the conditions aren't met
err = ""
if get_data_i(pachet) < get_data_s(pachet):
err = "wrong dates!" # if the end date is lower than the beginning date
if get_destinatie(pachet) == " ":
err = "wrong destination!"
if get_pret(pachet) <= 0:
err = "wrong price!"
if len(err) > 0:
raise Exception(err)
def test_valideaza_pachet():
pachet = creeaza_pachet(datetime.strptime('24/08/2021',"%d/%m/%Y"), datetime.strptime('26/08/2021',"%d/%m/%Y"), "Galati", 9000.1)
valideaza_pachet(pachet)
pachet_gresit = creeaza_pachet(datetime.strptime('24/08/2021',"%d/%m/%Y"), datetime.strptime('22/08/2021',"%d/%m/%Y"), "Galati", 9000.1)
try:
valideaza_pachet(pachet_gresit)
assert False
except Exception as ex:
assert (str(ex) == "wrong dates!\n")
alt_pachet = creeaza_pachet(datetime.strptime('24/08/2021',"%d/%m/%Y"), datetime.strptime('22/08/2021',"%d/%m/%Y"), " ", -904)
try:
valideaza_pachet(alt_pachet)
assert False
except Exception as ex:
assert(str(ex) == "wrong dates!\nwrong destination!\nwrong price!\n")
def test_creeaza_pachet():
data_i_string = '24/08/2021'
data_i = datetime.strptime(data_i_string, "%d/%m/%Y")
data_s_string = '26/08/2021'
data_s = datetime.strptime(data_s_string, "%d/%m/%Y")
dest = "Galati"
pret = 9000.1
pachet = creeaza_pachet(data_i,data_s,dest,pret)
assert (get_data_i(pachet) == data_i)
assert (get_data_s(pachet) == data_s)
assert (get_destinatie(pachet) == dest)
assert (abs(get_pret(pachet) - pret) < 0.0001)
def run_teste():
test_creeaza_pachet()
test_valideaza_pachet()
def run():
pass
def main():
run()
run_teste()
main()
uj5u.com熱心網友回復:
這更像是一次代碼審查和一種題外話,但是......首先,
- 放棄所有
assert False- 這些不會做任何有用的事情 - 洗掉 getter 函式,這只會使事情變得復雜(只要
dict[key]不使用自定義類,只需在代碼中使用) - 洗掉不必要的進口,如
calendar - 您可能還想洗掉
run和main函式(再次令人費解) - 只需呼叫您需要的函式
然后您可以更改valideaza_pachet以引發特定值錯誤:
def valideaza_pachet(pachet):
if pachet["data_i"] >= pachet["data_s"]:
raise ValueError("start date must be < end date")
if pachet["dest"] == " ":
raise ValueError("destination must not be empty")
if pachet["pret"] <= 0:
raise ValueError("price must be >= 0")
# returns None if no exception was raised
現在要測驗一個有效的包,你只需要做
valideaza_pachet(pachet) # no exception expected
如果沒有可以進行單元測驗的類,測驗無效包會稍微復雜一些(請參見此處的示例)-但是您可以捕獲例外并使用 try/except 的 else 子句來引發 AssertionError 表示您想要一個例外:
try:
valideaza_pachet(pachet_gresit)
except Exception as ex:
print(f"successfully received exception: {ex}")
else:
raise AssertionError("validation should have raised an Exception")
甚至
assert str(ex) == "start date must be < end date", f"got '{ex}', expected 'start date must be < end date'"
代替print宣告。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/321362.html
