Skip to content
136 changes: 136 additions & 0 deletions src/embed_tests/TestConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -809,6 +809,142 @@ public void FailedConversionOfNonClrValueManagedTypesOnlyLeavesErrorWhenSettingE
Exceptions.Clear();
}
}

[TestCase(typeof(decimal), true)]
[TestCase(typeof(decimal), false)]
[TestCase(typeof(DateTime), true)]
[TestCase(typeof(DateTime), false)]
[TestCase(typeof(TimeSpan), true)]
[TestCase(typeof(TimeSpan), false)]
public void ConversionFailsWhenStrRaises(Type type, bool setError)
{
using (Py.GIL())
{
using var scope = Py.CreateScope();
scope.Exec(@"
class BadStr:
def __str__(self):
raise ValueError('boom')
");
using var value = scope.Eval("BadStr()");

Assert.IsFalse(Converter.ToManaged(value, type, out var result, setError));
Assert.AreEqual(setError, Exceptions.ErrorOccurred());
if (setError)
{
Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.TypeError));
}
Exceptions.Clear();
}
}

[TestCase(typeof(decimal), true)]
[TestCase(typeof(decimal), false)]
[TestCase(typeof(DateTime), true)]
[TestCase(typeof(DateTime), false)]
[TestCase(typeof(TimeSpan), true)]
[TestCase(typeof(TimeSpan), false)]
public void ConversionFailsWhenStrCannotBeEncoded(Type type, bool setError)
{
using (Py.GIL())
{
using var scope = Py.CreateScope();
// a lone surrogate has no UTF-16 form
scope.Exec(@"
class Unreadable:
def __str__(self):
return chr(0xD800)
");
using var value = scope.Eval("Unreadable()");

Assert.IsFalse(Converter.ToManaged(value, type, out var result, setError));
Assert.AreEqual(setError, Exceptions.ErrorOccurred());
if (setError)
{
Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.TypeError));
}
Exceptions.Clear();
}
}

[Test]
[SetCulture("en-US")]
public void StrSubclassTextIsParsed()
{
using (Py.GIL())
{
using var scope = Py.CreateScope();
scope.Exec(@"
class Text(str):
pass

class Value:
def __init__(self, text):
self.text = text
def __str__(self):
return Text(self.text)
");
using var amount = scope.Eval("Value('1.5')");
using var duration = scope.Eval("Value('1:30:00')");
using var moment = scope.Eval("Value('2020-01-02 03:04:05')");

Assert.IsTrue(Converter.ToManaged(amount, typeof(decimal), out var result, false));
Assert.AreEqual(1.5m, result);
Assert.IsTrue(Converter.ToManaged(duration, typeof(TimeSpan), out result, false));
Assert.AreEqual(new TimeSpan(1, 30, 0), result);
Assert.IsTrue(Converter.ToManaged(moment, typeof(DateTime), out result, false));
Assert.AreEqual(new DateTime(2020, 1, 2, 3, 4, 5), result);
}
}

[Test]
public void FloatToDecimalAtTheRecursionLimitRaisesPythonError()
{
using (Py.GIL())
{
using var scope = Py.CreateScope();
scope.Set("target", new DecimalConsumer().ToPython());
// str(float) itself fails at the recursion limit, so sweep the depth to land exactly on it
scope.Exec(@"
import sys
limit = sys.getrecursionlimit()
sys.setrecursionlimit(200)
errors = set()

# a first failed call warms up the lazy state the mismatch diagnosis needs
try:
target.Take('not a number')
except TypeError:
pass

def call(depth):
if depth == 0:
target.Take(1.5)
else:
call(depth - 1)

try:
for depth in range(100, 260):
try:
call(depth)
except (RecursionError, TypeError) as e:
errors.add(type(e).__name__)
finally:
sys.setrecursionlimit(limit)
errors = sorted(errors)
");
var errors = scope.Get("errors").As<string[]>();
// str(float) only fails at the limit on some Python versions, so a TypeError is optional
CollectionAssert.Contains(errors, "RecursionError");
}
}
}

public class DecimalConsumer
{
public void Take(decimal value)
{
}
}

public interface IGetList
Expand Down
61 changes: 61 additions & 0 deletions src/embed_tests/TestImplicitNumericOperators.cs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,67 @@ public void UnsupportedOperandsRaisePythonsTypeError()
StringAssert.Contains("unsupported operand type(s) for -", messages[3]);
}

[Test]
public void IntOperandWhoseStrRaisesIsUnsupported()
{
using var _ = Py.GIL();
using var scope = Py.CreateScope();
scope.Set("count", new ConvertibleCount(1).ToPython());
// beyond long, the int is read through its str()
scope.Exec(@"
class BadInt(int):
def __str__(self):
raise ValueError('boom')

try:
count + BadInt(10 ** 25)
error = ''
except Exception as e:
error = type(e).__name__
");
Assert.AreEqual("TypeError", scope.Get<string>("error"));
}

[Test]
public void IntOperandWhoseStrCannotBeEncodedIsUnsupported()
{
using var _ = Py.GIL();
using var scope = Py.CreateScope();
scope.Set("count", new ConvertibleCount(1).ToPython());
// a lone surrogate has no UTF-16 form
scope.Exec(@"
class BadInt(int):
def __str__(self):
return chr(0xD800)

try:
count + BadInt(10 ** 25)
error = ''
except Exception as e:
error = type(e).__name__
");
Assert.AreEqual("TypeError", scope.Get<string>("error"));
}

[Test]
public void IntOperandWhoseStrIsAStrSubclassIsRead()
{
using var _ = Py.GIL();
using var scope = Py.CreateScope();
scope.Set("count", new ConvertibleCount(1).ToPython());
scope.Exec(@"
class Text(str):
pass

class BigInt(int):
def __str__(self):
return Text(int(self))

matches = count + BigInt(10 ** 25) == 10 ** 25 + 1
");
Assert.IsTrue(scope.Get<bool>("matches"));
}

[Test]
public void InheritedOperatorsKeepWinning()
{
Expand Down
109 changes: 109 additions & 0 deletions src/embed_tests/TestPythonException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,115 @@ def CallThrow():
}
}

[Test]
public void ErrorRaisedAtTheRecursionLimitReachesPython()
{
using var _ = Py.GIL();
using var scope = Py.CreateScope();
scope.Set("target", new ReentrantCaller().ToPython());
// managed code calls back into Python until the recursion limit, so the error is decoded right at it
scope.Exec(@"
import sys
limit = sys.getrecursionlimit()
sys.setrecursionlimit(200)

def handler():
target.Call(handler)

try:
target.Call(handler)
error = ''
except RecursionError as e:
error = str(e)
finally:
sys.setrecursionlimit(limit)
");
StringAssert.Contains("maximum recursion depth exceeded", scope.Get<string>("error"));
}

[Test]
public void DecodingKeepsARecursionLimitSetWhileItRuns()
{
using var _ = Py.GIL();
using var scope = Py.CreateScope();
// decoding reads attributes of the error, and this one changes the limit when it is read
scope.Exec(@"
import sys
limit = sys.getrecursionlimit()

class LimitError(Exception):
def __getattr__(self, name):
sys.setrecursionlimit(250)
raise AttributeError(name)
");
try
{
Assert.Throws<PythonException>(() => scope.Exec("raise LimitError('boom')"));
Assert.AreEqual(250, scope.Eval<int>("sys.getrecursionlimit()"));
}
finally
{
scope.Exec("sys.setrecursionlimit(limit)");
}
}

[Test]
public void ErrorIsDecodedAtTheHighestRecursionLimit()
{
using var _ = Py.GIL();
using var scope = Py.CreateScope();
scope.Exec(@"
import sys
limit = sys.getrecursionlimit()
sys.setrecursionlimit(2147483647)
");
try
{
var error = Assert.Throws<PythonException>(() => scope.Exec("raise ValueError('boom')"));
Assert.AreEqual("boom", error.Message);
Assert.AreEqual(2147483647, scope.Eval<int>("sys.getrecursionlimit()"));
}
finally
{
scope.Exec("sys.setrecursionlimit(limit)");
}
}

[Test]
public void ErrorWhoseStrRaisesArrivesAsItself()
{
using var _ = Py.GIL();
using var scope = Py.CreateScope();
scope.Exec(@"
class Unprintable(Exception):
def __str__(self):
raise KeyError('from str')
");
var error = Assert.Throws<PythonException>(() => scope.Exec("raise Unprintable('original')"));
Assert.AreEqual("Unprintable", error.Type.Name);
Assert.AreEqual("original", error.Message);
}

[Test]
public void ErrorWhoseStrRaisesIsNamedAfterItsTypeWithoutATextArgument()
{
using var _ = Py.GIL();
using var scope = Py.CreateScope();
// the type name is not ASCII
scope.Exec("class D\u00e9faut(Exception):\n def __str__(self):\n raise KeyError('from str')\n");
var error = Assert.Throws<PythonException>(() => scope.Exec("raise D\u00e9faut(1, 2)"));
Assert.AreEqual("D\u00e9faut", error.Message);
}

public class ReentrantCaller
{
public void Call(PyObject callback)
{
using var _ = Py.GIL();
callback.Invoke().Dispose();
}
}

public class TestClass
{
public void ThrowException()
Expand Down
15 changes: 14 additions & 1 deletion src/runtime/Converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1034,8 +1034,13 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec
if (obType == typeof(TimeSpan))
{
op = Runtime.PyObject_Str(value);
if (op.IsNull())
{
goto type_error;
}
TimeSpan ts;
var arr = Runtime.GetManagedString(op.Borrow()).Split(',');
var arr = Runtime.GetManagedSpan(op.Borrow(), out var timeSpanText).ToString().Split(',');
timeSpanText.Dispose();
op.Dispose();
string sts = arr.Length == 1 ? arr[0] : arr[1];
if (!TimeSpan.TryParse(sts, out ts))
Expand Down Expand Up @@ -1370,6 +1375,10 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec
}
case TypeCode.Decimal:
op = Runtime.PyObject_Str(value);
if (op.IsNull())
{
goto type_error;
}
decimal m;
var sm = Runtime.GetManagedSpan(op.Borrow(), out var newReference);
if (!Decimal.TryParse(sm, NumberStyles.Number | NumberStyles.AllowExponent, nfi, out m))
Expand All @@ -1391,6 +1400,10 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec

// fallback to string parsing for types such as numpy
op = Runtime.PyObject_Str(value);
if (op.IsNull())
{
goto type_error;
}
var sdt = Runtime.GetManagedSpan(op.Borrow(), out var reference);
if (!DateTime.TryParse(sdt, out var dt))
{
Expand Down
Loading
Loading