无法弄清楚为什么我的 PyTest 返回“ID not found”HTTPException?

问题描述 投票:0回答:1

我正在尝试实现一个更新计时器函数,但无法弄清楚为什么它没有注册字典中确实存在的id(我还应该注意,所有其他方法/变量的使用都是正确的,只有 update_timer() 和 test_update_timer () 可能不正确)。这是我的代码:

//in productivity service

def update_timer(self, timer: PomodoroTimer) -> PomodoroTimer:
        """Modifies one timer in the data store.

        Args:
            timer: Data for a timer with modified values.
        Returns:
            PomodoroTimer: Updated timer.
        Raises:
            HTTPException: Timer does not exist.
        """
        
        global _timers
        initial_timer= _timers[timer.id]
         if initial_timer not in _timers:
            raise HTTPException(
                status_code=404, detail=f"Invalid ID {timer.id}: Timer does not exist."
            )

        initial_timer.name = timer.name
        initial_timer.description = timer.description
        initial_timer.timer_length = timer.timer_length
        initial_timer.break_length = timer.break_length
        
        return initial_timer


// in productivity test

def test_update_timer(productivity_service: ProductivityService):
    timer = PomodoroTimer(
        id=1, name="Sample", description="Description", timer_length=10, break_length=5
    )
initial_timer = productivity_service.create_timer(timer)

timer2 = PomodoroTimer(
    id=1, name="USample", description="UDescription", timer_length=5, break_length=2
)
u_timer = productivity_service.update_timer(timer2)
length = len(productivity_service.get_timers())

assert length == 1
assert u_timer.id ==1
assert u_timer.name == "USample"
assert u_timer.description == "UDescription"
assert u_timer.timer_length == 5
assert u_timer.break_length == 2

收到错误 失败生产力_test.py::test_update_timer - fastapi.exceptions.HTTPException

angular typescript pytest
1个回答
0
投票

您能否尝试删除

_timers
的全局声明,也许它会重置最初设置的值?

def update_timer(self, timer: PomodoroTimer) -> PomodoroTimer:
        """Modifies one timer in the data store.

        Args:
            timer: Data for a timer with modified values.
        Returns:
            PomodoroTimer: Updated timer.
        Raises:
            HTTPException: Timer does not exist.
        """
        
        # global _timers # <-- changed here!
        initial_timer= _timers[timer.id]
         if initial_timer not in _timers:
            raise HTTPException(
                status_code=404, detail=f"Invalid ID {timer.id}: Timer does not exist."
            )

        initial_timer.name = timer.name
        initial_timer.description = timer.description
        initial_timer.timer_length = timer.timer_length
        initial_timer.break_length = timer.break_length
        
        return initial_timer
© www.soinside.com 2019 - 2024. All rights reserved.