python type_error ai_generated true

TypeError: assertRaises() 缺少 1 个必需的位置参数: 'callable'

TypeError: assertRaises() missing 1 required positional argument: 'callable'

ID: python/unittest-testcase-assertraises-no-context

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-04-22首次发现

版本兼容性

版本状态引入弃用备注
3.9 active — — —
3.12 active — — —

根因分析

测试调用 `self.assertRaises(SomeError)` 时未提供可调用对象,也未作为上下文管理器使用。assertRaises 需要第二个参数为可调用对象,或使用 `with self.assertRaises(SomeError):` 语法。

English

The test calls `self.assertRaises(SomeError)` without the callable or without using it as a context manager. assertRaises requires either a callable as the second argument or use as `with self.assertRaises(SomeError):`.

generic

解决方案

  1. 97% 成功率
    Use the context manager form:
    
    with self.assertRaises(ValueError):
        parse_bad_input()
  2. 95% 成功率
    Or pass the callable as the second argument:
    
    self.assertRaises(ValueError, parse_bad_input)

无效尝试

常见但无效的做法:

  1. 85% 失败

    assertRaises expects an exception class or tuple of classes; an instance raises TypeError about expected exceptions.

  2. 60% 失败

    Loses the assertRaises semantics and can silently pass if the wrong exception type is raised.