首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >开始日期大于日历期间的结束日期。

开始日期大于日历期间的结束日期。
EN

Stack Overflow用户
提问于 2021-10-17 12:20:47
回答 1查看 103关注 0票数 0

我试图编写一个函数来验证包含两个日期(开始和结束)、目的地和价格的包。

最初,我尝试编写一个函数“创建”日期,并将它们放在列表中,然后比较它们以确定结束日期是否低于开始日期,但我认为这太复杂了,所以我求助于datetime内置模块。

但是,当我尝试运行测试函数时,它会失败,并输出此错误消息。

代码语言:javascript
复制
File "C:\Users\Anon\Desktop\Fac\FP\pythonProject\main.py", line 65, in valideaza_pachet
    raise Exception(err)
Exception: wrong dates!

我想我一定是在valideaza_pachet()函数中搞砸了一个条件,但我不明白我做错了什么

守则:

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-17 13:57:17

这更像是一次代码评审,有点离题,但是.第一,

删除所有calendar

  • you --这些都不会做任何有用的

  • 删除getter函数,这只会使事情变得复杂(只要在代码中使用dict[key],只要您不使用自定义类),

  • 也可能希望删除run和< code >D12函数(同样是卷积的)--只需调用所需的函数(H 213f 214)

然后可以更改valideaza_pachet以引发特定的值错误:

代码语言:javascript
复制
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

现在,要测试一个有效的包,只需

代码语言:javascript
复制
valideaza_pachet(pachet) # no exception expected

如果没有一个可以进行单元测试的类(例如,here),测试一个无效的包会稍微复杂一些--但是您可以捕获异常并使用try/ but的use子句来引发一个AssertionError,该AssertionError表示您需要一个异常:

代码语言:javascript
复制
try:
    valideaza_pachet(pachet_gresit)
except Exception as ex:
    print(f"successfully received exception: {ex}")
else:
    raise AssertionError("validation should have raised an Exception")

甚至是

代码语言:javascript
复制
assert str(ex) == "start date must be < end date", f"got '{ex}', expected 'start date must be < end date'"

代替print语句。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69604286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档