Skip to content

Commit f1d8158

Browse files
committed
Add test coverage for __index__ and __int__ edge cases: incorrectly returning float
These tests ensure that: - Invalid return types (floats) are properly rejected - The fallback from __index__ to __int__ works correctly in convert mode - noconvert mode correctly prevents fallback when __index__ fails
1 parent 2a32770 commit f1d8158

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

tests/test_builtin_casters.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,50 @@ def cant_convert(v):
324324
assert convert(RaisingValueErrorOnIndex()) == 42
325325
requires_conversion(RaisingValueErrorOnIndex())
326326

327+
class IndexReturnsFloat:
328+
def __index__(self):
329+
return 3.14 # noqa: PLE0305 Wrong: should return int
330+
331+
class IntReturnsFloat:
332+
def __int__(self):
333+
return 3.14 # Wrong: should return int
334+
335+
class IndexFloatIntInt:
336+
def __index__(self):
337+
return 3.14 # noqa: PLE0305 Wrong: should return int
338+
339+
def __int__(self):
340+
return 42 # Correct: returns int
341+
342+
class IndexIntIntFloat:
343+
def __index__(self):
344+
return 42 # Correct: returns int
345+
346+
def __int__(self):
347+
return 3.14 # Wrong: should return int
348+
349+
class IndexFloatIntFloat:
350+
def __index__(self):
351+
return 3.14 # noqa: PLE0305 Wrong: should return int
352+
353+
def __int__(self):
354+
return 2.71 # Wrong: should return int
355+
356+
cant_convert(IndexReturnsFloat())
357+
requires_conversion(IndexReturnsFloat())
358+
359+
cant_convert(IntReturnsFloat())
360+
requires_conversion(IntReturnsFloat())
361+
362+
assert convert(IndexFloatIntInt()) == 42 # convert: __index__ fails, uses __int__
363+
requires_conversion(IndexFloatIntInt()) # noconvert: __index__ fails, no fallback
364+
365+
assert convert(IndexIntIntFloat()) == 42 # convert: __index__ succeeds
366+
assert noconvert(IndexIntIntFloat()) == 42 # noconvert: __index__ succeeds
367+
368+
cant_convert(IndexFloatIntFloat()) # convert mode rejects (both fail)
369+
requires_conversion(IndexFloatIntFloat()) # noconvert mode also rejects
370+
327371

328372
def test_float_convert(doc):
329373
class Int:

0 commit comments

Comments
 (0)