Skip to content

Commit 88f2cfa

Browse files
committed
Refactor Converter.ToPrimitive
1 parent 950676f commit 88f2cfa

File tree

2 files changed

+236
-219
lines changed

2 files changed

+236
-219
lines changed

src/embed_tests/TestConverter.cs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,25 @@
11
using System;
22
using System.Collections.Generic;
33
using NUnit.Framework;
4+
45
using Python.Runtime;
56

7+
using PyRuntime = Python.Runtime.Runtime;
8+
69
namespace Python.EmbeddingTest
710
{
811
public class TestConverter
912
{
13+
static readonly Type[] _numTypes = new Type[]
14+
{
15+
typeof(short),
16+
typeof(ushort),
17+
typeof(int),
18+
typeof(uint),
19+
typeof(long),
20+
typeof(ulong)
21+
};
22+
1023
[OneTimeSetUp]
1124
public void SetUp()
1225
{
@@ -47,6 +60,55 @@ public void TestConvertDoubleToManaged(
4760
Assert.IsTrue(((double) convertedValue).Equals(testValue));
4861
}
4962

63+
[Test]
64+
public void CovertTypeError()
65+
{
66+
using (var s = new PyString("abc"))
67+
{
68+
foreach (var type in _numTypes)
69+
{
70+
object value;
71+
try
72+
{
73+
bool res = Converter.ToManaged(s.Handle, type, out value, true);
74+
Assert.IsFalse(res);
75+
var bo = Exceptions.ExceptionMatches(Exceptions.TypeError);
76+
Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.TypeError)
77+
|| Exceptions.ExceptionMatches(Exceptions.ValueError));
78+
}
79+
finally
80+
{
81+
Exceptions.Clear();
82+
}
83+
}
84+
}
85+
}
86+
87+
[Test]
88+
public void ConvertOverflow()
89+
{
90+
using (var num = new PyLong(ulong.MaxValue))
91+
{
92+
IntPtr largeNum = PyRuntime.PyNumber_Add(num.Handle, num.Handle);
93+
try
94+
{
95+
object value;
96+
foreach (var type in _numTypes)
97+
{
98+
bool res = Converter.ToManaged(largeNum, type, out value, true);
99+
Assert.IsFalse(res);
100+
Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.OverflowError));
101+
Exceptions.Clear();
102+
}
103+
}
104+
finally
105+
{
106+
Exceptions.Clear();
107+
PyRuntime.XDecref(largeNum);
108+
}
109+
}
110+
}
111+
50112
[Test]
51113
public void RawListProxy()
52114
{

0 commit comments

Comments
 (0)