You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python unittest中assertRaises()检测负数回合ValueError失败求助

Fixing ValueError Assertion in unittest's assertRaises

Let's break down what's going wrong in your code and how to fix it step by step.

First, Understand How assertRaises Works

The assertRaises context manager exists to verify that a specific piece of code triggers the expected exception. For it to work, you need to put the exact operation that should throw the exception inside the with block. If you don't run that code, assertRaises will fail because no exception was raised.

Issues in Your Current Code

Let's go through the problems one by one:

  1. You Overwrote Your Game Object
    In setUp, you have this line:

    self.game_turn_negative = -2
    

    This replaces your Game instance with an integer -2—so when you try to call get_turn() on it later, it would throw an AttributeError (since integers don't have that method). You meant to set the turn attribute of the existing Game object:

    self.game_turn_negative.turn = -2
    
  2. You Didn't Trigger the Exception in the assertRaises Block
    Your with self.assertRaises(ValueError) block only contains a print statement. You never actually call the method that's supposed to throw the exception (get_turn() on the negative-turn game instance). That's why the test fails: no exception was raised during the block's execution.

  3. (Likely) Missing Validation in Game.get_turn()
    For the exception to be thrown at all, your Game class's get_turn() method needs to include logic to check if turn is negative and raise the error. If you haven't implemented that yet, add it:

    # In canvas.py
    class Game:
        def __init__(self):
            self.turn = 0  # Default value
    
        def get_turn(self):
            if self.turn < 0:
                raise ValueError('turn cannot be negative')
            return self.turn
    

Corrected Test Code

Here's the fixed version of your test class, with clear explanations:

import unittest
from canvas import Game

class TestPlayer1(unittest.TestCase):
    def setUp(self):
        # Initialize Game instances
        self.game_turn_0 = Game()
        self.game_turn_5 = Game()
        self.game_turn_negative = Game()
        
        # Set turn values correctly
        self.game_turn_0.turn = 0
        self.game_turn_5.turn = 5
        self.game_turn_negative.turn = -2  # Fixed: assign to the attribute, not the object

    def test_get_turn(self):
        # Test normal, non-negative cases
        self.assertEqual(self.game_turn_0.get_turn(), 0)
        self.assertEqual(self.game_turn_5.get_turn(), 5)
        
        # Test negative turn case: call get_turn() inside the assertRaises block
        with self.assertRaises(ValueError) as context:
            self.game_turn_negative.get_turn()
        
        # Optional: Verify the exception message is correct (makes test more robust)
        self.assertEqual(str(context.exception), 'turn cannot be negative')

if __name__ == '__main__':
    unittest.main()

How This Works

  • The with self.assertRaises(ValueError) block wraps the call to get_turn() on the negative-turn game. When that method runs, it will throw the ValueError, which assertRaises catches and validates.
  • Using context.exception lets you check that the error message matches exactly what you expect, ensuring your validation logic is working as intended.

内容的提问来源于stack exchange,提问作者Techoplite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:32:05