Skip to content

Commit

Permalink
Fix and add unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
jhonabreul committed Oct 26, 2023
1 parent 54ea2ad commit 34fa470
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 2 deletions.
69 changes: 69 additions & 0 deletions src/embed_tests/TestPythonException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,12 +265,81 @@ def CallThrow(self):
}
}

[Test]
public void TestGetsPythonCodeInfoInStackTraceForNestedInterop()
{
using (Py.GIL())
{
dynamic testClassModule = PyModule.FromString("TestGetsPythonCodeInfoInStackTraceForNestedInterop_Module", @"
from clr import AddReference
AddReference(""Python.EmbeddingTest"")
AddReference(""System"")
from Python.EmbeddingTest import *
from System import Action
class TestPythonClass(TestPythonException.TestClass):
def CallThrow(self):
super().ThrowExceptionNested()
def GetThrowAction():
return Action(CallThrow)
def CallThrow():
TestPythonClass().CallThrow()
");

try
{
var action = testClassModule.GetThrowAction();
action();
}
catch (ClrBubbledException ex)
{
Assert.AreEqual("Test Exception Message", ex.InnerException.Message);

var pythonTracebackLines = ex.PythonTraceback.TrimEnd('\n').Split('\n').Select(x => x.Trim()).ToList();
Assert.AreEqual(4, pythonTracebackLines.Count);

Assert.IsTrue(new[]
{
"File ",
"fixtures\\PyImportTest\\SampleScript.py",
"line 5",
"in invokeMethodImpl"
}.All(x => pythonTracebackLines[0].Contains(x)));
Assert.AreEqual("getattr(instance, method_name)()", pythonTracebackLines[1]);

Assert.IsTrue(new[]
{
"File ",
"fixtures\\PyImportTest\\SampleScript.py",
"line 2",
"in invokeMethod"
}.All(x => pythonTracebackLines[2].Contains(x)));
Assert.AreEqual("invokeMethodImpl(instance, method_name)", pythonTracebackLines[3]);
}
catch (Exception ex)
{
Assert.Fail($"Unexpected exception: {ex}");
}
}
}

public class TestClass
{
public void ThrowException()
{
throw new ArgumentException("Test Exception Message");
}

public void ThrowExceptionNested()
{
using var _ = Py.GIL();

dynamic module = Py.Import("PyImportTest.SampleScript");
module.invokeMethod(this, "ThrowException");
}
}
}
}
9 changes: 7 additions & 2 deletions src/runtime/PythonException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,15 @@ private static Exception FromPyErr(BorrowedReference typeRef, BorrowedReference
exception = decodedException;
}

if (!(exception is null))
if (exception is not null)
{
if (exception is ClrBubbledException)
{
return exception;
}

using var _ = new Py.GILState();
return new ClrBubbledException(exception, !(traceback is null) ? TracebackToString(traceback) : "");
return new ClrBubbledException(exception, TracebackToString(traceback));
}

using var cause = Runtime.PyException_GetCause(nValRef);
Expand Down

0 comments on commit 34fa470

Please sign in to comment.