diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 000000000..49d49f270 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,50 @@ +name: Linting + +on: + push: + branches: + - master + pull_request: + +jobs: + lint-dotnet: + name: Lint .NET + runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '7.0.x' + + - name: Lint + run: dotnet format -v diag --verify-no-changes --report=format.json + + - uses: actions/upload-artifact@v4 + with: + name: format-report + path: format.json + + lint-python: + name: Lint Python + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + + - name: Install Ruff + run: pip install ruff + + - name: Check formatting + run: ruff format --check + + - name: Check lints + run: ruff check diff --git a/clr.py b/clr.py index 20a975f96..cec7d7404 100644 --- a/clr.py +++ b/clr.py @@ -3,4 +3,5 @@ """ from pythonnet import load + load() diff --git a/demo/DynamicGrid.py b/demo/DynamicGrid.py index 951a6c248..1939ea45b 100644 --- a/demo/DynamicGrid.py +++ b/demo/DynamicGrid.py @@ -1,12 +1,14 @@ import clr import sys -if sys.platform.lower() not in ['cli','win32']: + +if sys.platform.lower() not in ["cli", "win32"]: print("only windows is supported for wpf") clr.AddReference(r"wpf\PresentationFramework") -from System.IO import StreamReader -from System.Windows.Markup import XamlReader -from System.Threading import Thread, ThreadStart, ApartmentState -from System.Windows import Application, Window + +from System.IO import StreamReader # noqa: E402 +from System.Windows.Markup import XamlReader # noqa: E402 +from System.Threading import Thread, ThreadStart, ApartmentState # noqa: E402 +from System.Windows import Application, Window # noqa: E402 class MyWindow(Window): @@ -14,9 +16,9 @@ def __init__(self): stream = StreamReader("DynamicGrid.xaml") window = XamlReader.Load(stream.BaseStream) Application().Run(window) - -if __name__ == '__main__': + +if __name__ == "__main__": thread = Thread(ThreadStart(MyWindow)) thread.SetApartmentState(ApartmentState.STA) thread.Start() diff --git a/demo/helloform.py b/demo/helloform.py index 503d1c8b5..326c292e9 100644 --- a/demo/helloform.py +++ b/demo/helloform.py @@ -4,13 +4,13 @@ import clr clr.AddReference("System.Windows.Forms") -import System.Windows.Forms as WinForms -from System.Drawing import Size, Point +import System.Windows.Forms as WinForms # noqa +from System.Drawing import Size, Point # noqa class HelloApp(WinForms.Form): """A simple hello world app that demonstrates the essentials of - winforms programming and event-based programming in Python.""" + winforms programming and event-based programming in Python.""" def __init__(self): super().__init__() @@ -44,7 +44,7 @@ def __init__(self): def button_Click(self, sender, args): """Button click event handler""" - print ("Click") + print("Click") WinForms.MessageBox.Show("Please do not press this button again.") def run(self): @@ -53,11 +53,11 @@ def run(self): def main(): form = HelloApp() - print ("form created") + print("form created") app = WinForms.Application - print ("app referenced") + print("app referenced") app.Run(form) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/demo/splitter.py b/demo/splitter.py index c209de6ab..86f71e7d1 100644 --- a/demo/splitter.py +++ b/demo/splitter.py @@ -4,15 +4,16 @@ import clr import System + clr.AddReference("System.Windows.Forms") -import System.Windows.Forms as WinForms +import System.Windows.Forms as WinForms # noqa -from System.Drawing import Color, Size, Point +from System.Drawing import Color # noqa class Splitter(WinForms.Form): """A WinForms example transcribed to Python from the MSDN article: - 'Creating a Multipane User Interface with Windows Forms'.""" + 'Creating a Multipane User Interface with Windows Forms'.""" def __init__(self): super().__init__() @@ -90,5 +91,5 @@ def main(): app.Dispose() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/demo/wordpad.py b/demo/wordpad.py index c7e998944..f12ffc779 100644 --- a/demo/wordpad.py +++ b/demo/wordpad.py @@ -3,13 +3,13 @@ import clr import System + clr.AddReference("System.Windows.Forms") -import System.Windows.Forms as WinForms +import System.Windows.Forms as WinForms # noqa -from System.IO import File -from System.Text import Encoding -from System.Drawing import Color, Point, Size -from System.Threading import ApartmentState, Thread, ThreadStart +from System.IO import File # noqa +from System.Text import Encoding # noqa +from System.Threading import ApartmentState, Thread, ThreadStart # noqa class Wordpad(WinForms.Form): @@ -17,7 +17,7 @@ class Wordpad(WinForms.Form): def __init__(self): super().__init__() - self.filename = '' + self.filename = "" self.word_wrap = True self.doctype = 1 self.InitializeComponent() @@ -101,9 +101,14 @@ def InitializeComponent(self): self.fileMenu.Text = "&File" self.fileMenu.Index = 0 - items = (self.menuFileNew, self.menuFileOpen, - self.menuFileSave, self.menuFileSaveAs, - self.menuFileSep_1, self.menuFileExit) + items = ( + self.menuFileNew, + self.menuFileOpen, + self.menuFileSave, + self.menuFileSaveAs, + self.menuFileSep_1, + self.menuFileExit, + ) self.fileMenu.MenuItems.AddRange(items) @@ -150,10 +155,16 @@ def InitializeComponent(self): self.editMenu.Text = "&Edit" self.editMenu.Index = 1 - items = (self.menuEditUndo, self.menuEditRedo, - self.menuEditSep_1, self.menuEditCut, - self.menuEditCopy, self.menuEditPaste, - self.menuEditSep_2, self.menuEditSelectAll) + items = ( + self.menuEditUndo, + self.menuEditRedo, + self.menuEditSep_1, + self.menuEditCut, + self.menuEditCopy, + self.menuEditPaste, + self.menuEditSep_2, + self.menuEditSelectAll, + ) self.editMenu.MenuItems.AddRange(items) @@ -215,8 +226,7 @@ def InitializeComponent(self): self.openFileDialog.Filter = "Text documents|*.txt|RTF document|*.rtf" self.openFileDialog.Title = "Open document" - self.saveFileDialog.Filter = "Text Documents|*.txt|" \ - "Rich Text Format|*.rtf" + self.saveFileDialog.Filter = "Text Documents|*.txt|" "Rich Text Format|*.rtf" self.saveFileDialog.Title = "Save document" self.saveFileDialog.FileName = "Untitled" @@ -245,7 +255,7 @@ def OnClickFileSave(self, sender, args): self.SaveDocument() def OnClickFileSaveAs(self, sender, args): - self.filename = '' + self.filename = "" self.SaveDocument() def OnClickFileExit(self, sender, args): @@ -285,10 +295,10 @@ def OnClickHelpAbout(self, sender, args): def NewDocument(self): self.doctype = 1 - self.richTextBox.Rtf = '' - self.richTextBox.Text = '' - self.Text = 'Python Wordpad - (New Document)' - self.filename = '' + self.richTextBox.Rtf = "" + self.richTextBox.Text = "" + self.Text = "Python Wordpad - (New Document)" + self.filename = "" def OpenDocument(self): if self.openFileDialog.ShowDialog() != WinForms.DialogResult.OK: @@ -308,19 +318,19 @@ def OpenDocument(self): temp = Encoding.ASCII.GetString(buff, 0, read) data.append(temp) - data = ''.join(data) + data = "".join(data) stream.Close() filename = self.filename = filename.lower() - if filename.endswith('.rtf'): + if filename.endswith(".rtf"): self.richTextBox.Rtf = data self.doctype = 2 else: self.richTextBox.Text = data self.doctype = 1 - self.Text = 'Python Wordpad - %s' % filename + self.Text = "Python Wordpad - %s" % filename self.richTextBox.Select(0, 0) def SaveDocument(self): @@ -332,13 +342,13 @@ def SaveDocument(self): filename = self.saveFileDialog.FileName filename = self.filename = filename.lower() - self.Text = 'Python Wordpad - %s' % filename + self.Text = "Python Wordpad - %s" % filename self.richTextBox.Select(0, 0) stream = File.OpenWrite(filename) - if filename.endswith('.rtf'): + if filename.endswith(".rtf"): data = self.richTextBox.Rtf else: data = self.richTextBox.Text @@ -350,11 +360,14 @@ def SaveDocument(self): def SaveChangesDialog(self): if self.richTextBox.Modified: - if WinForms.MessageBox.Show( - "Save changes?", "Word Pad", - WinForms.MessageBoxButtons.OK | - WinForms.MessageBoxButtons.YesNo - ) == WinForms.DialogResult.Yes: + if ( + WinForms.MessageBox.Show( + "Save changes?", + "Word Pad", + WinForms.MessageBoxButtons.OK | WinForms.MessageBoxButtons.YesNo, + ) + == WinForms.DialogResult.Yes + ): self.SaveDocument() return 1 return 0 @@ -384,8 +397,9 @@ def InitializeComponent(self): self.label1.Name = "label1" self.label1.Size = System.Drawing.Size(296, 140) self.label1.TabIndex = 2 - self.label1.Text = "Python Wordpad - an example winforms " \ - "application using Python.NET" + self.label1.Text = ( + "Python Wordpad - an example winforms " "application using Python.NET" + ) self.AutoScaleBaseSize = System.Drawing.Size(5, 13) self.ClientSize = System.Drawing.Size(300, 150) @@ -418,5 +432,5 @@ def main(): thread.Join() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/doc/source/conf.py b/doc/source/conf.py index f2e1ba4c1..001ff3f9a 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -10,8 +10,10 @@ # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # -import os, sys -sys.path.insert(0, os.path.abspath('../..')) +import os +import sys + +sys.path.insert(0, os.path.abspath("../..")) # -- Project information ----------------------------------------------------- diff --git a/pythonnet/__init__.py b/pythonnet/__init__.py index 5c1ca108a..491f6e185 100644 --- a/pythonnet/__init__.py +++ b/pythonnet/__init__.py @@ -144,7 +144,7 @@ def load(runtime: Union[clr_loader.Runtime, str, None] = None, **params: str) -> if func(b"") != 0: raise RuntimeError("Failed to initialize Python.Runtime.dll") - + _LOADED = True import atexit diff --git a/src/console/pythonconsole.cs b/src/console/pythonconsole.cs index bf17848f7..9e7cd924d 100644 --- a/src/console/pythonconsole.cs +++ b/src/console/pythonconsole.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Reflection; + using Python.Runtime; namespace Python.Runtime diff --git a/src/embed_tests/CodecGroups.cs b/src/embed_tests/CodecGroups.cs index 689e5b24c..fed0e7216 100644 --- a/src/embed_tests/CodecGroups.cs +++ b/src/embed_tests/CodecGroups.cs @@ -2,7 +2,9 @@ namespace Python.EmbeddingTest { using System; using System.Linq; + using NUnit.Framework; + using Python.Runtime; using Python.Runtime.Codecs; @@ -20,7 +22,7 @@ public void GetEncodersByType() }; var got = group.GetEncoders(typeof(Uri)).ToArray(); - CollectionAssert.AreEqual(new[]{encoder1, encoder2}, got); + CollectionAssert.AreEqual(new[] { encoder1, encoder2 }, got); } [Test] diff --git a/src/embed_tests/Codecs.cs b/src/embed_tests/Codecs.cs index c8b8ecb6e..242067903 100644 --- a/src/embed_tests/Codecs.cs +++ b/src/embed_tests/Codecs.cs @@ -1,8 +1,11 @@ -namespace Python.EmbeddingTest { +namespace Python.EmbeddingTest +{ using System; using System.Collections.Generic; using System.Linq; + using NUnit.Framework; + using Python.Runtime; using Python.Runtime.Codecs; @@ -169,7 +172,8 @@ public void SequenceDecoderTest() ICollection stringCollection = null; Assert.DoesNotThrow(() => { codec.TryDecode(pyList, out stringCollection); }); Assert.AreEqual(3, stringCollection.Count()); - Assert.Throws(typeof(InvalidCastException), () => { + Assert.Throws(typeof(InvalidCastException), () => + { string[] array = new string[3]; stringCollection.CopyTo(array, 0); }); @@ -206,7 +210,8 @@ public void SequenceDecoderTest() ICollection stringCollection2 = null; Assert.DoesNotThrow(() => { codec.TryDecode(pyTuple, out stringCollection2); }); Assert.AreEqual(3, stringCollection2.Count()); - Assert.Throws(typeof(InvalidCastException), () => { + Assert.Throws(typeof(InvalidCastException), () => + { string[] array = new string[3]; stringCollection2.CopyTo(array, 0); }); @@ -255,13 +260,15 @@ public void IterableDecoderTest() IEnumerable stringEnumerable = null; Assert.DoesNotThrow(() => { codec.TryDecode(pyList, out stringEnumerable); }); - Assert.Throws(typeof(InvalidCastException), () => { + Assert.Throws(typeof(InvalidCastException), () => + { foreach (string item in stringEnumerable) { var x = item; } }); - Assert.Throws(typeof(InvalidCastException), () => { + Assert.Throws(typeof(InvalidCastException), () => + { stringEnumerable.Count(); }); @@ -390,7 +397,7 @@ public void ExceptionDecodedNoInstance() } } - public static void AcceptsDateTime(DateTime v) {} + public static void AcceptsDateTime(DateTime v) { } [Test] public void As_Object_AffectedByDecoders() diff --git a/src/embed_tests/GlobalTestsSetup.cs b/src/embed_tests/GlobalTestsSetup.cs index dff58b978..382694c48 100644 --- a/src/embed_tests/GlobalTestsSetup.cs +++ b/src/embed_tests/GlobalTestsSetup.cs @@ -1,4 +1,5 @@ using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/Inheritance.cs b/src/embed_tests/Inheritance.cs index ebbc24dc4..5f954b24d 100644 --- a/src/embed_tests/Inheritance.cs +++ b/src/embed_tests/Inheritance.cs @@ -206,9 +206,9 @@ public class PropertyAccessorBase public virtual string VirtualProp { get; set; } } - public class PropertyAccessorIntermediate: PropertyAccessorBase { } + public class PropertyAccessorIntermediate : PropertyAccessorBase { } - public class PropertyAccessorDerived: PropertyAccessorIntermediate + public class PropertyAccessorDerived : PropertyAccessorIntermediate { public override string VirtualProp { set => base.VirtualProp = value.ToUpperInvariant(); } } @@ -217,7 +217,7 @@ public class ContainerClass { public void BaseMethod() { } - public class InnerClass: ContainerClass + public class InnerClass : ContainerClass { } diff --git a/src/embed_tests/Modules.cs b/src/embed_tests/Modules.cs index 6cab4dd07..544015b58 100644 --- a/src/embed_tests/Modules.cs +++ b/src/embed_tests/Modules.cs @@ -1,6 +1,8 @@ using System; using System.Threading; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest @@ -385,8 +387,8 @@ public void TestThread() //add function to the scope //can be call many times, more efficient than ast ps.Exec( - "import threading\n"+ - "lock = threading.Lock()\n"+ + "import threading\n" + + "lock = threading.Lock()\n" + "def update():\n" + " global res, th_cnt\n" + " with lock:\n" + diff --git a/src/embed_tests/NumPyTests.cs b/src/embed_tests/NumPyTests.cs index e102ddb99..424263052 100644 --- a/src/embed_tests/NumPyTests.cs +++ b/src/embed_tests/NumPyTests.cs @@ -68,7 +68,7 @@ public void VarArg() { dynamic zX = np.array(new[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 8, 9, 0 } }); dynamic grad = np.gradient(zX, 4.0, 5.0); - dynamic grad2 = np.InvokeMethod("gradient", new PyObject[] {zX, new PyFloat(4.0), new PyFloat(5.0)}); + dynamic grad2 = np.InvokeMethod("gradient", new PyObject[] { zX, new PyFloat(4.0), new PyFloat(5.0) }); Assert.AreEqual(4.125, grad[0].sum().__float__().As(), 0.001); Assert.AreEqual(-1.2, grad[1].sum().__float__().As(), 0.001); diff --git a/src/embed_tests/References.cs b/src/embed_tests/References.cs index c416c5ebe..900b70126 100644 --- a/src/embed_tests/References.cs +++ b/src/embed_tests/References.cs @@ -1,6 +1,7 @@ namespace Python.EmbeddingTest { using NUnit.Framework; + using Python.Runtime; public class References diff --git a/src/embed_tests/TestCallbacks.cs b/src/embed_tests/TestCallbacks.cs index 88b84d0c3..527730f07 100644 --- a/src/embed_tests/TestCallbacks.cs +++ b/src/embed_tests/TestCallbacks.cs @@ -1,28 +1,35 @@ using System; using NUnit.Framework; + using Python.Runtime; -namespace Python.EmbeddingTest { - public class TestCallbacks { +namespace Python.EmbeddingTest +{ + public class TestCallbacks + { [OneTimeSetUp] - public void SetUp() { + public void SetUp() + { PythonEngine.Initialize(); } [OneTimeTearDown] - public void Dispose() { + public void Dispose() + { PythonEngine.Shutdown(); } [Test] - public void TestNoOverloadException() { + public void TestNoOverloadException() + { int passed = 0; var aFunctionThatCallsIntoPython = new Action(value => passed = value); - using (Py.GIL()) { + using (Py.GIL()) + { using dynamic callWith42 = PythonEngine.Eval("lambda f: f([42])"); using var pyFunc = aFunctionThatCallsIntoPython.ToPython(); - var error = Assert.Throws(() => callWith42(pyFunc)); + var error = Assert.Throws(() => callWith42(pyFunc)); Assert.AreEqual("TypeError", error.Type.Name); string expectedArgTypes = "()"; StringAssert.EndsWith(expectedArgTypes, error.Message); diff --git a/src/embed_tests/TestConverter.cs b/src/embed_tests/TestConverter.cs index a59b9c97b..2190aab50 100644 --- a/src/embed_tests/TestConverter.cs +++ b/src/embed_tests/TestConverter.cs @@ -46,7 +46,7 @@ public void TestConvertSingleToManaged( var converted = Converter.ToManaged(pyFloat, typeof(float), out convertedValue, false); Assert.IsTrue(converted); - Assert.IsTrue(((float) convertedValue).Equals(testValue)); + Assert.IsTrue(((float)convertedValue).Equals(testValue)); } [Test] @@ -60,7 +60,7 @@ public void TestConvertDoubleToManaged( var converted = Converter.ToManaged(pyFloat, typeof(double), out convertedValue, false); Assert.IsTrue(converted); - Assert.IsTrue(((double) convertedValue).Equals(testValue)); + Assert.IsTrue(((double)convertedValue).Equals(testValue)); } [Test] @@ -164,7 +164,7 @@ public void ToPyList() [Test] public void RawListProxy() { - var list = new List {"hello", "world"}; + var list = new List { "hello", "world" }; var listProxy = PyObject.FromManagedObject(list); var clrObject = (CLRObject)ManagedType.GetManagedObject(listProxy); Assert.AreSame(list, clrObject.inst); diff --git a/src/embed_tests/TestCustomMarshal.cs b/src/embed_tests/TestCustomMarshal.cs index 312863d0c..35f018e96 100644 --- a/src/embed_tests/TestCustomMarshal.cs +++ b/src/embed_tests/TestCustomMarshal.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestDomainReload.cs b/src/embed_tests/TestDomainReload.cs index a0f9b63eb..befb40417 100644 --- a/src/embed_tests/TestDomainReload.cs +++ b/src/embed_tests/TestDomainReload.cs @@ -3,7 +3,9 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; + using NUnit.Framework; + using Python.Runtime; using PyRuntime = Python.Runtime.Runtime; diff --git a/src/embed_tests/TestFinalizer.cs b/src/embed_tests/TestFinalizer.cs index b748a2244..4c39b908b 100644 --- a/src/embed_tests/TestFinalizer.cs +++ b/src/embed_tests/TestFinalizer.cs @@ -1,5 +1,3 @@ -using NUnit.Framework; -using Python.Runtime; using System; using System.Collections.Generic; using System.Diagnostics; @@ -7,6 +5,10 @@ using System.Runtime.CompilerServices; using System.Threading; +using NUnit.Framework; + +using Python.Runtime; + namespace Python.EmbeddingTest { public class TestFinalizer @@ -237,7 +239,7 @@ private static IntPtr CreateStringGarbage() PyString s1 = new PyString("test_string"); // s2 steal a reference from s1 IntPtr address = s1.Reference.DangerousGetAddress(); - PyString s2 = new (StolenReference.DangerousFromPointer(address)); + PyString s2 = new(StolenReference.DangerousFromPointer(address)); return address; } } diff --git a/src/embed_tests/TestGILState.cs b/src/embed_tests/TestGILState.cs index bf6f02dc6..1129080dd 100644 --- a/src/embed_tests/TestGILState.cs +++ b/src/embed_tests/TestGILState.cs @@ -1,6 +1,7 @@ namespace Python.EmbeddingTest { using NUnit.Framework; + using Python.Runtime; public class TestGILState @@ -13,7 +14,7 @@ public void CanDisposeMultipleTimes() { using (var gilState = Py.GIL()) { - for(int i = 0; i < 50; i++) + for (int i = 0; i < 50; i++) gilState.Dispose(); } } diff --git a/src/embed_tests/TestInstanceWrapping.cs b/src/embed_tests/TestInstanceWrapping.cs index 0a441c823..855b70f29 100644 --- a/src/embed_tests/TestInstanceWrapping.cs +++ b/src/embed_tests/TestInstanceWrapping.cs @@ -1,6 +1,8 @@ using System; using System.Globalization; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest @@ -44,10 +46,10 @@ public void WeakRefIsNone_AfterObjectIsGone() Assert.IsTrue(weakref.Invoke().IsNone()); } - class Base {} - class Derived: Base { } + class Base { } + class Derived : Base { } - class Overloaded: Derived + class Overloaded : Derived { public int Value { get; set; } public void IntOrStr(int arg) => this.Value = arg; diff --git a/src/embed_tests/TestNamedArguments.cs b/src/embed_tests/TestNamedArguments.cs index c86302038..6edd88332 100644 --- a/src/embed_tests/TestNamedArguments.cs +++ b/src/embed_tests/TestNamedArguments.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestOperator.cs b/src/embed_tests/TestOperator.cs index 6bfb81bdb..b795a8076 100644 --- a/src/embed_tests/TestOperator.cs +++ b/src/embed_tests/TestOperator.cs @@ -1,12 +1,12 @@ +using System; +using System.Linq; +using System.Reflection; + using NUnit.Framework; using Python.Runtime; using Python.Runtime.Codecs; -using System; -using System.Linq; -using System.Reflection; - namespace Python.EmbeddingTest { public class TestOperator @@ -541,12 +541,12 @@ public void ForwardOperatorOverloads() [Test] public void TupleComparisonOperatorOverloads() { - TupleCodec.Register(); - string name = string.Format("{0}.{1}", - typeof(OperableObject).DeclaringType.Name, - typeof(OperableObject).Name); + TupleCodec.Register(); + string name = string.Format("{0}.{1}", + typeof(OperableObject).DeclaringType.Name, + typeof(OperableObject).Name); string module = MethodBase.GetCurrentMethod().DeclaringType.Namespace; - PythonEngine.Exec($@" + PythonEngine.Exec($@" from {module} import * cls = {name} a = cls(2) diff --git a/src/embed_tests/TestPyBuffer.cs b/src/embed_tests/TestPyBuffer.cs index 1b4e28d12..84edbe86a 100644 --- a/src/embed_tests/TestPyBuffer.cs +++ b/src/embed_tests/TestPyBuffer.cs @@ -1,11 +1,14 @@ using System; using System.Runtime.CompilerServices; using System.Text; + using NUnit.Framework; + using Python.Runtime; using Python.Runtime.Codecs; -namespace Python.EmbeddingTest { +namespace Python.EmbeddingTest +{ class TestPyBuffer { [OneTimeSetUp] @@ -64,11 +67,11 @@ public void TestBufferRead() [Test] public void ArrayHasBuffer() { - var array = new[,] {{1, 2}, {3,4}}; + var array = new[,] { { 1, 2 }, { 3, 4 } }; var memoryView = PythonEngine.Eval("memoryview"); var mem = memoryView.Invoke(array.ToPython()); Assert.AreEqual(1, mem[(0, 0).ToPython()].As()); - Assert.AreEqual(array[1,0], mem[(1, 0).ToPython()].As()); + Assert.AreEqual(array[1, 0], mem[(1, 0).ToPython()].As()); } [Test] @@ -113,7 +116,7 @@ public void Finalization() [Test] public void MultidimensionalNumPyArray() { - var ndarray = np.arange(24).reshape(1,2,3,4).T; + var ndarray = np.arange(24).reshape(1, 2, 3, 4).T; PyObject ndim = ndarray.ndim; PyObject shape = ndarray.shape; PyObject strides = ndarray.strides; diff --git a/src/embed_tests/TestPyFloat.cs b/src/embed_tests/TestPyFloat.cs index 89e29e5fd..df8a8f8bf 100644 --- a/src/embed_tests/TestPyFloat.cs +++ b/src/embed_tests/TestPyFloat.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestPyInt.cs b/src/embed_tests/TestPyInt.cs index d2767e664..a85cb1516 100644 --- a/src/embed_tests/TestPyInt.cs +++ b/src/embed_tests/TestPyInt.cs @@ -4,6 +4,7 @@ using System.Numerics; using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestPyList.cs b/src/embed_tests/TestPyList.cs index eee129f2d..a9ca1c62b 100644 --- a/src/embed_tests/TestPyList.cs +++ b/src/embed_tests/TestPyList.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest @@ -67,7 +69,7 @@ public void TestEmptyCtor() [Test] public void TestPyObjectArrayCtor() { - var ai = new PyObject[] {new PyInt(3), new PyInt(2), new PyInt(1) }; + var ai = new PyObject[] { new PyInt(3), new PyInt(2), new PyInt(1) }; var s = new PyList(ai); Assert.IsInstanceOf(typeof(PyList), s); diff --git a/src/embed_tests/TestPyNumber.cs b/src/embed_tests/TestPyNumber.cs index 0261c15c1..b79c121d7 100644 --- a/src/embed_tests/TestPyNumber.cs +++ b/src/embed_tests/TestPyNumber.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestPyObject.cs b/src/embed_tests/TestPyObject.cs index 2f27eba1b..02042c84e 100644 --- a/src/embed_tests/TestPyObject.cs +++ b/src/embed_tests/TestPyObject.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest @@ -62,7 +64,7 @@ def add(self, x, y): public void InvokeNull() { var list = PythonEngine.Eval("list"); - Assert.Throws(() => list.Invoke(new PyObject[] {null})); + Assert.Throws(() => list.Invoke(new PyObject[] { null })); } [Test] diff --git a/src/embed_tests/TestPySequence.cs b/src/embed_tests/TestPySequence.cs index dc35a2633..02055ab04 100644 --- a/src/embed_tests/TestPySequence.cs +++ b/src/embed_tests/TestPySequence.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestPyString.cs b/src/embed_tests/TestPyString.cs index 35c6339ee..26795309d 100644 --- a/src/embed_tests/TestPyString.cs +++ b/src/embed_tests/TestPyString.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestPyTuple.cs b/src/embed_tests/TestPyTuple.cs index 5d76116aa..36b0dfe57 100644 --- a/src/embed_tests/TestPyTuple.cs +++ b/src/embed_tests/TestPyTuple.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestPyWith.cs b/src/embed_tests/TestPyWith.cs index d1c9aac28..615b6712d 100644 --- a/src/embed_tests/TestPyWith.cs +++ b/src/embed_tests/TestPyWith.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestPythonEngineProperties.cs b/src/embed_tests/TestPythonEngineProperties.cs index be91d7f45..015c8bb02 100644 --- a/src/embed_tests/TestPythonEngineProperties.cs +++ b/src/embed_tests/TestPythonEngineProperties.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestPythonException.cs b/src/embed_tests/TestPythonException.cs index a248b6a1f..a604a9065 100644 --- a/src/embed_tests/TestPythonException.cs +++ b/src/embed_tests/TestPythonException.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/TestRuntime.cs b/src/embed_tests/TestRuntime.cs index 77696fd96..6413cc389 100644 --- a/src/embed_tests/TestRuntime.cs +++ b/src/embed_tests/TestRuntime.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/dynamic.cs b/src/embed_tests/dynamic.cs index 6e3bfc4cb..3e7802ecd 100644 --- a/src/embed_tests/dynamic.cs +++ b/src/embed_tests/dynamic.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Text; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/fixtures/PyImportTest/sysargv.py b/src/embed_tests/fixtures/PyImportTest/sysargv.py index 2e1508bff..0bd715c1b 100644 --- a/src/embed_tests/fixtures/PyImportTest/sysargv.py +++ b/src/embed_tests/fixtures/PyImportTest/sysargv.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import sys + # if argv is available, as expected, then no exception num_args = len(sys.argv) diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index b828d5315..fb36998a7 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -3,6 +3,7 @@ using System.Runtime.InteropServices; using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/embed_tests/pyinitialize.cs b/src/embed_tests/pyinitialize.cs index 25dafb686..7a2443a62 100644 --- a/src/embed_tests/pyinitialize.cs +++ b/src/embed_tests/pyinitialize.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest @@ -25,7 +27,7 @@ public static void LoadDefaultArgs() { using (new PythonEngine()) { - using(var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) + using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) { Assert.AreNotEqual(0, argv.Length()); } diff --git a/src/embed_tests/pyrunstring.cs b/src/embed_tests/pyrunstring.cs index 57c133c00..fe7a0bb6b 100644 --- a/src/embed_tests/pyrunstring.cs +++ b/src/embed_tests/pyrunstring.cs @@ -1,5 +1,7 @@ using System; + using NUnit.Framework; + using Python.Runtime; namespace Python.EmbeddingTest diff --git a/src/perf_tests/BaselineComparisonBenchmarkBase.cs b/src/perf_tests/BaselineComparisonBenchmarkBase.cs index 06adcbc67..936a20a00 100644 --- a/src/perf_tests/BaselineComparisonBenchmarkBase.cs +++ b/src/perf_tests/BaselineComparisonBenchmarkBase.cs @@ -15,13 +15,15 @@ public BaselineComparisonBenchmarkBase() Console.WriteLine($"CWD: {Environment.CurrentDirectory}"); Console.WriteLine($"Using Python.Runtime from {typeof(PythonEngine).Assembly.Location} {typeof(PythonEngine).Assembly.GetName()}"); - try { + try + { PythonEngine.Initialize(); Console.WriteLine("Python Initialized"); Trace.Assert(PythonEngine.BeginAllowThreads() != IntPtr.Zero); Console.WriteLine("Threading enabled"); } - catch (Exception e) { + catch (Exception e) + { Console.WriteLine(e); throw; } @@ -44,11 +46,13 @@ public static void SetupRuntimeResolve() Console.WriteLine("Preloading " + pythonRuntimeDll); Assembly.LoadFrom(pythonRuntimeDll); - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + { if (assembly.FullName.StartsWith("Python.Runtime")) Console.WriteLine(assembly.Location); - foreach(var dependency in assembly.GetReferencedAssemblies()) - if (dependency.FullName.Contains("Python.Runtime")) { + foreach (var dependency in assembly.GetReferencedAssemblies()) + if (dependency.FullName.Contains("Python.Runtime")) + { Console.WriteLine($"{assembly} -> {dependency}"); } } @@ -56,7 +60,8 @@ public static void SetupRuntimeResolve() AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve; } - static Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args) { + static Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args) + { if (!args.Name.StartsWith("Python.Runtime")) return null; diff --git a/src/perf_tests/BaselineComparisonConfig.cs b/src/perf_tests/BaselineComparisonConfig.cs index 3f6766554..f155980e6 100644 --- a/src/perf_tests/BaselineComparisonConfig.cs +++ b/src/perf_tests/BaselineComparisonConfig.cs @@ -36,11 +36,13 @@ public BaselineComparisonConfig() Path.Combine(deploymentRoot, "new", "Python.Runtime.dll"))); } - static BaselineComparisonConfig() { + static BaselineComparisonConfig() + { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve; } - static Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args) { + static Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args) + { Console.WriteLine(args.Name); if (!args.Name.StartsWith("Python.Runtime")) return null; diff --git a/src/perf_tests/BenchmarkTests.cs b/src/perf_tests/BenchmarkTests.cs index 9e033d11f..5ba5d5e3d 100644 --- a/src/perf_tests/BenchmarkTests.cs +++ b/src/perf_tests/BenchmarkTests.cs @@ -2,11 +2,12 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Runtime.CompilerServices; using System.Reflection; +using System.Runtime.CompilerServices; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; + using NUnit.Framework; namespace Python.PerformanceTests @@ -64,7 +65,8 @@ static double GetOptimisticPerfRatio( public static void AssertPerformanceIsBetterOrSame( double actual, double target, - double wiggleRoom = 1.1, [CallerMemberName] string testName = null) { + double wiggleRoom = 1.1, [CallerMemberName] string testName = null) + { double threshold = target * wiggleRoom; Assert.LessOrEqual(actual, threshold, $"{testName}: {actual:F3} > {threshold:F3} (target: {target:F3})" diff --git a/src/perf_tests/PythonCallingNetBenchmark.cs b/src/perf_tests/PythonCallingNetBenchmark.cs index d7edd4583..cd3c6abd7 100644 --- a/src/perf_tests/PythonCallingNetBenchmark.cs +++ b/src/perf_tests/PythonCallingNetBenchmark.cs @@ -4,12 +4,13 @@ using System.Text; using BenchmarkDotNet.Attributes; + using Python.Runtime; namespace Python.PerformanceTests { [Config(typeof(BaselineComparisonConfig))] - public class PythonCallingNetBenchmark: BaselineComparisonBenchmarkBase + public class PythonCallingNetBenchmark : BaselineComparisonBenchmarkBase { [Benchmark] public void ReadInt64Property() @@ -27,8 +28,10 @@ public void ReadInt64Property() } [Benchmark] - public void WriteInt64Property() { - using (Py.GIL()) { + public void WriteInt64Property() + { + using (Py.GIL()) + { var locals = new PyDict(); locals.SetItem("a", new NetObject().ToPython()); Exec($@" diff --git a/src/runtime/AssemblyManager.cs b/src/runtime/AssemblyManager.cs index a8bbd1f6c..c4dd22ed9 100644 --- a/src/runtime/AssemblyManager.cs +++ b/src/runtime/AssemblyManager.cs @@ -37,7 +37,7 @@ internal class AssemblyManager // modified from event handlers below, potentially triggered from different .NET threads private static readonly ConcurrentQueue assemblies = new(); - internal static readonly List pypath = new (capacity: 16); + internal static readonly List pypath = new(capacity: 16); private AssemblyManager() { } @@ -337,7 +337,7 @@ public static bool IsValidNamespace(string name) /// Returns an enumerable collection containing the namepsaces exported /// by loaded assemblies in the current app domain. /// - public static IEnumerable GetNamespaces () + public static IEnumerable GetNamespaces() { return namespaces.Keys; } diff --git a/src/runtime/ClassManager.cs b/src/runtime/ClassManager.cs index ecb6055a8..272dace7b 100644 --- a/src/runtime/ClassManager.cs +++ b/src/runtime/ClassManager.cs @@ -300,28 +300,28 @@ internal static bool ShouldBindField(FieldInfo fi) internal static bool ShouldBindProperty(PropertyInfo pi) { - MethodInfo? mm; - try - { - mm = pi.GetGetMethod(true); - if (mm == null) - { - mm = pi.GetSetMethod(true); - } - } - catch (SecurityException) - { - // GetGetMethod may try to get a method protected by - // StrongNameIdentityPermission - effectively private. - return false; - } - + MethodInfo? mm; + try + { + mm = pi.GetGetMethod(true); if (mm == null) { - return false; + mm = pi.GetSetMethod(true); } + } + catch (SecurityException) + { + // GetGetMethod may try to get a method protected by + // StrongNameIdentityPermission - effectively private. + return false; + } - return ShouldBindMethod(mm); + if (mm == null) + { + return false; + } + + return ShouldBindMethod(mm); } internal static bool ShouldBindEvent(EventInfo ei) @@ -469,7 +469,7 @@ private static ClassInfo GetClassInfo(Type type, ClassBase impl) case MemberTypes.Property: var pi = (PropertyInfo)mi; - if(!ShouldBindProperty(pi)) + if (!ShouldBindProperty(pi)) { continue; } @@ -556,7 +556,8 @@ private static ClassInfo GetClassInfo(Type type, ClassBase impl) var parent = type.BaseType; while (parent != null && ci.indexer == null) { - foreach (var prop in parent.GetProperties()) { + foreach (var prop in parent.GetProperties()) + { var args = prop.GetIndexParameters(); if (args.GetLength(0) > 0) { diff --git a/src/runtime/Codecs/DecoderGroup.cs b/src/runtime/Codecs/DecoderGroup.cs index 41e1f0494..1a75fac15 100644 --- a/src/runtime/Codecs/DecoderGroup.cs +++ b/src/runtime/Codecs/DecoderGroup.cs @@ -8,7 +8,7 @@ namespace Python.Runtime.Codecs /// /// Represents a group of s. Useful to group them by priority. /// - public sealed class DecoderGroup: IPyObjectDecoder, IEnumerable, IDisposable + public sealed class DecoderGroup : IPyObjectDecoder, IEnumerable, IDisposable { readonly List decoders = new(); diff --git a/src/runtime/Codecs/EncoderGroup.cs b/src/runtime/Codecs/EncoderGroup.cs index 63abf35a3..c1a608462 100644 --- a/src/runtime/Codecs/EncoderGroup.cs +++ b/src/runtime/Codecs/EncoderGroup.cs @@ -8,7 +8,7 @@ namespace Python.Runtime.Codecs /// /// Represents a group of s. Useful to group them by priority. /// - public sealed class EncoderGroup: IPyObjectEncoder, IEnumerable, IDisposable + public sealed class EncoderGroup : IPyObjectEncoder, IEnumerable, IDisposable { readonly List encoders = new(); @@ -72,11 +72,12 @@ public static IEnumerable GetEncoders(this IPyObjectEncoder de if (decoder is IEnumerable composite) { foreach (var nestedEncoder in composite) - foreach (var match in nestedEncoder.GetEncoders(type)) - { - yield return match; - } - } else if (decoder.CanEncode(type)) + foreach (var match in nestedEncoder.GetEncoders(type)) + { + yield return match; + } + } + else if (decoder.CanEncode(type)) { yield return decoder; } diff --git a/src/runtime/Codecs/IterableDecoder.cs b/src/runtime/Codecs/IterableDecoder.cs index bcc2eca01..b864850d5 100644 --- a/src/runtime/Codecs/IterableDecoder.cs +++ b/src/runtime/Codecs/IterableDecoder.cs @@ -1,55 +1,55 @@ -using System; -using System.Collections.Generic; - -namespace Python.Runtime.Codecs -{ - public class IterableDecoder : IPyObjectDecoder - { - internal static bool IsIterable(Type targetType) - { - //if it is a plain IEnumerable, we can decode it using sequence protocol. - if (targetType == typeof(System.Collections.IEnumerable)) - return true; - - if (!targetType.IsGenericType) - return false; - - return targetType.GetGenericTypeDefinition() == typeof(IEnumerable<>); - } - - internal static bool IsIterable(PyType objectType) - { - return objectType.HasAttr("__iter__"); - } - - public bool CanDecode(PyType objectType, Type targetType) - { - return IsIterable(objectType) && IsIterable(targetType); - } - - public bool TryDecode(PyObject pyObj, out T value) - { - //first see if T is a plan IEnumerable - if (typeof(T) == typeof(System.Collections.IEnumerable)) - { - object enumerable = new CollectionWrappers.IterableWrapper(pyObj); - value = (T)enumerable; - return true; - } - - var elementType = typeof(T).GetGenericArguments()[0]; - var collectionType = typeof(CollectionWrappers.IterableWrapper<>).MakeGenericType(elementType); - - var instance = Activator.CreateInstance(collectionType, new[] { pyObj }); - value = (T)instance; - return true; - } - - public static IterableDecoder Instance { get; } = new IterableDecoder(); - - public static void Register() - { - PyObjectConversions.RegisterDecoder(Instance); - } - } -} +using System; +using System.Collections.Generic; + +namespace Python.Runtime.Codecs +{ + public class IterableDecoder : IPyObjectDecoder + { + internal static bool IsIterable(Type targetType) + { + //if it is a plain IEnumerable, we can decode it using sequence protocol. + if (targetType == typeof(System.Collections.IEnumerable)) + return true; + + if (!targetType.IsGenericType) + return false; + + return targetType.GetGenericTypeDefinition() == typeof(IEnumerable<>); + } + + internal static bool IsIterable(PyType objectType) + { + return objectType.HasAttr("__iter__"); + } + + public bool CanDecode(PyType objectType, Type targetType) + { + return IsIterable(objectType) && IsIterable(targetType); + } + + public bool TryDecode(PyObject pyObj, out T value) + { + //first see if T is a plan IEnumerable + if (typeof(T) == typeof(System.Collections.IEnumerable)) + { + object enumerable = new CollectionWrappers.IterableWrapper(pyObj); + value = (T)enumerable; + return true; + } + + var elementType = typeof(T).GetGenericArguments()[0]; + var collectionType = typeof(CollectionWrappers.IterableWrapper<>).MakeGenericType(elementType); + + var instance = Activator.CreateInstance(collectionType, new[] { pyObj }); + value = (T)instance; + return true; + } + + public static IterableDecoder Instance { get; } = new IterableDecoder(); + + public static void Register() + { + PyObjectConversions.RegisterDecoder(Instance); + } + } +} diff --git a/src/runtime/Codecs/ListDecoder.cs b/src/runtime/Codecs/ListDecoder.cs index 70ff33aaa..5da82851f 100644 --- a/src/runtime/Codecs/ListDecoder.cs +++ b/src/runtime/Codecs/ListDecoder.cs @@ -1,50 +1,50 @@ -using System; -using System.Collections.Generic; - -namespace Python.Runtime.Codecs -{ - public class ListDecoder : IPyObjectDecoder - { - private static bool IsList(Type targetType) - { - if (!targetType.IsGenericType) - return false; - - return targetType.GetGenericTypeDefinition() == typeof(IList<>); - } - - private static bool IsList(PyType objectType) - { - //TODO accept any python object that implements the sequence and list protocols - //must implement sequence protocol to fully implement list protocol - //if (!SequenceDecoder.IsSequence(objectType)) return false; - - //returns wheter the type is a list. - return PythonReferenceComparer.Instance.Equals(objectType, Runtime.PyListType); - } - - public bool CanDecode(PyType objectType, Type targetType) - { - return IsList(objectType) && IsList(targetType); - } - - public bool TryDecode(PyObject pyObj, out T value) - { - if (pyObj == null) throw new ArgumentNullException(nameof(pyObj)); - - var elementType = typeof(T).GetGenericArguments()[0]; - Type collectionType = typeof(CollectionWrappers.ListWrapper<>).MakeGenericType(elementType); - - var instance = Activator.CreateInstance(collectionType, new[] { pyObj }); - value = (T)instance; - return true; - } - - public static ListDecoder Instance { get; } = new ListDecoder(); - - public static void Register() - { - PyObjectConversions.RegisterDecoder(Instance); - } - } -} +using System; +using System.Collections.Generic; + +namespace Python.Runtime.Codecs +{ + public class ListDecoder : IPyObjectDecoder + { + private static bool IsList(Type targetType) + { + if (!targetType.IsGenericType) + return false; + + return targetType.GetGenericTypeDefinition() == typeof(IList<>); + } + + private static bool IsList(PyType objectType) + { + //TODO accept any python object that implements the sequence and list protocols + //must implement sequence protocol to fully implement list protocol + //if (!SequenceDecoder.IsSequence(objectType)) return false; + + //returns wheter the type is a list. + return PythonReferenceComparer.Instance.Equals(objectType, Runtime.PyListType); + } + + public bool CanDecode(PyType objectType, Type targetType) + { + return IsList(objectType) && IsList(targetType); + } + + public bool TryDecode(PyObject pyObj, out T value) + { + if (pyObj == null) throw new ArgumentNullException(nameof(pyObj)); + + var elementType = typeof(T).GetGenericArguments()[0]; + Type collectionType = typeof(CollectionWrappers.ListWrapper<>).MakeGenericType(elementType); + + var instance = Activator.CreateInstance(collectionType, new[] { pyObj }); + value = (T)instance; + return true; + } + + public static ListDecoder Instance { get; } = new ListDecoder(); + + public static void Register() + { + PyObjectConversions.RegisterDecoder(Instance); + } + } +} diff --git a/src/runtime/Codecs/RawProxyEncoder.cs b/src/runtime/Codecs/RawProxyEncoder.cs index 37ad0487b..923633f79 100644 --- a/src/runtime/Codecs/RawProxyEncoder.cs +++ b/src/runtime/Codecs/RawProxyEncoder.cs @@ -6,7 +6,7 @@ namespace Python.Runtime.Codecs /// A .NET object encoder, that returns raw proxies (e.g. no conversion to Python types). /// You must inherit from this class and override . /// - public class RawProxyEncoder: IPyObjectEncoder + public class RawProxyEncoder : IPyObjectEncoder { public PyObject TryEncode(object value) { diff --git a/src/runtime/Codecs/SequenceDecoder.cs b/src/runtime/Codecs/SequenceDecoder.cs index a539297cd..c5ded4958 100644 --- a/src/runtime/Codecs/SequenceDecoder.cs +++ b/src/runtime/Codecs/SequenceDecoder.cs @@ -1,52 +1,52 @@ -using System; -using System.Collections.Generic; - -namespace Python.Runtime.Codecs -{ - public class SequenceDecoder : IPyObjectDecoder - { - internal static bool IsSequence(Type targetType) - { - if (!targetType.IsGenericType) - return false; - - return targetType.GetGenericTypeDefinition() == typeof(ICollection<>); - } - - internal static bool IsSequence(PyType objectType) - { - //must implement iterable protocol to fully implement sequence protocol - if (!IterableDecoder.IsIterable(objectType)) return false; - +using System; +using System.Collections.Generic; + +namespace Python.Runtime.Codecs +{ + public class SequenceDecoder : IPyObjectDecoder + { + internal static bool IsSequence(Type targetType) + { + if (!targetType.IsGenericType) + return false; + + return targetType.GetGenericTypeDefinition() == typeof(ICollection<>); + } + + internal static bool IsSequence(PyType objectType) + { + //must implement iterable protocol to fully implement sequence protocol + if (!IterableDecoder.IsIterable(objectType)) return false; + //returns wheter it implements the sequence protocol //according to python doc this needs to exclude dict subclasses //but I don't know how to look for that given the objectType //rather than the instance. - return objectType.HasAttr("__getitem__"); - } - - public bool CanDecode(PyType objectType, Type targetType) - { - return IsSequence(objectType) && IsSequence(targetType); - } - - public bool TryDecode(PyObject pyObj, out T value) - { - if (pyObj == null) throw new ArgumentNullException(nameof(pyObj)); - - var elementType = typeof(T).GetGenericArguments()[0]; - Type collectionType = typeof(CollectionWrappers.SequenceWrapper<>).MakeGenericType(elementType); - - var instance = Activator.CreateInstance(collectionType, new[] { pyObj }); - value = (T)instance; - return true; - } - - public static SequenceDecoder Instance { get; } = new SequenceDecoder(); - - public static void Register() - { - PyObjectConversions.RegisterDecoder(Instance); - } - } -} + return objectType.HasAttr("__getitem__"); + } + + public bool CanDecode(PyType objectType, Type targetType) + { + return IsSequence(objectType) && IsSequence(targetType); + } + + public bool TryDecode(PyObject pyObj, out T value) + { + if (pyObj == null) throw new ArgumentNullException(nameof(pyObj)); + + var elementType = typeof(T).GetGenericArguments()[0]; + Type collectionType = typeof(CollectionWrappers.SequenceWrapper<>).MakeGenericType(elementType); + + var instance = Activator.CreateInstance(collectionType, new[] { pyObj }); + value = (T)instance; + return true; + } + + public static SequenceDecoder Instance { get; } = new SequenceDecoder(); + + public static void Register() + { + PyObjectConversions.RegisterDecoder(Instance); + } + } +} diff --git a/src/runtime/CollectionWrappers/IterableWrapper.cs b/src/runtime/CollectionWrappers/IterableWrapper.cs index 849e3997b..4b17f08bf 100644 --- a/src/runtime/CollectionWrappers/IterableWrapper.cs +++ b/src/runtime/CollectionWrappers/IterableWrapper.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Collections; +using System.Collections.Generic; namespace Python.Runtime.CollectionWrappers { diff --git a/src/runtime/DefaultBaseTypeProvider.cs b/src/runtime/DefaultBaseTypeProvider.cs index 08702c80f..20aed3584 100644 --- a/src/runtime/DefaultBaseTypeProvider.cs +++ b/src/runtime/DefaultBaseTypeProvider.cs @@ -28,7 +28,7 @@ static BorrowedReference GetBaseType(Type type) : Runtime.PyBaseObjectType; } - DefaultBaseTypeProvider(){} + DefaultBaseTypeProvider() { } public static DefaultBaseTypeProvider Instance { get; } = new DefaultBaseTypeProvider(); } } diff --git a/src/runtime/DelegateManager.cs b/src/runtime/DelegateManager.cs index 4343b9ab7..ff107a876 100644 --- a/src/runtime/DelegateManager.cs +++ b/src/runtime/DelegateManager.cs @@ -15,7 +15,7 @@ namespace Python.Runtime /// internal class DelegateManager { - private readonly Dictionary cache = new(); + private readonly Dictionary cache = new(); private readonly Type basetype = typeof(Dispatcher); private readonly Type arrayType = typeof(object[]); private readonly Type voidtype = typeof(void); diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index da095e030..6a724177e 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -376,12 +376,12 @@ public static variables on the Exceptions class filled in from public static PyObject UnicodeTranslateError; public static PyObject ValueError; public static PyObject ZeroDivisionError; -//#ifdef MS_WINDOWS + //#ifdef MS_WINDOWS //public static IntPtr WindowsError; -//#endif -//#ifdef __VMS + //#endif + //#ifdef __VMS //public static IntPtr VMSError; -//#endif + //#endif //PyAPI_DATA(PyObject *) PyExc_BufferError; diff --git a/src/runtime/Finalizer.cs b/src/runtime/Finalizer.cs index 713564f08..819e63a99 100644 --- a/src/runtime/Finalizer.cs +++ b/src/runtime/Finalizer.cs @@ -27,7 +27,7 @@ public ErrorArgs(Exception error) public Exception Error { get; } } - public static Finalizer Instance { get; } = new (); + public static Finalizer Instance { get; } = new(); public event EventHandler? BeforeCollect; public event EventHandler? ErrorHandler; @@ -94,14 +94,14 @@ public override string Message internal IncorrectRefCountException(IntPtr ptr) { PyPtr = ptr; - + } } internal delegate bool IncorrectRefCntHandler(object sender, IncorrectFinalizeArgs e); - #pragma warning disable 414 +#pragma warning disable 414 internal event IncorrectRefCntHandler? IncorrectRefCntResolver = null; - #pragma warning restore 414 +#pragma warning restore 414 internal bool ThrowIfUnhandleIncorrectRefCount { get; set; } = true; #endregion @@ -142,8 +142,10 @@ internal void AddFinalizedObject(ref IntPtr obj, int run lock (_queueLock) #endif { - this._objQueue.Enqueue(new PendingFinalization { - PyObj = obj, RuntimeRun = run, + this._objQueue.Enqueue(new PendingFinalization + { + PyObj = obj, + RuntimeRun = run, #if TRACE_ALLOC StackTrace = stackTrace.ToString(), #endif diff --git a/src/runtime/ImportHook.cs b/src/runtime/ImportHook.cs index b82c503b5..f44ab2221 100644 --- a/src/runtime/ImportHook.cs +++ b/src/runtime/ImportHook.cs @@ -164,12 +164,12 @@ static void SetupImportHook() PythonException.ThrowIfIsNull(args); using var codeStr = Runtime.PyString_FromString(LoaderCode); Runtime.PyTuple_SetItem(args.Borrow(), 0, codeStr.StealOrThrow()); - + // reference not stolen due to overload incref'ing for us. Runtime.PyTuple_SetItem(args.Borrow(), 1, mod_dict); Runtime.PyObject_Call(exec, args.Borrow(), default).Dispose(); // Set as a sub-module of clr. - if(Runtime.PyModule_AddObject(ClrModuleReference, "loader", import_hook_module.Steal()) != 0) + if (Runtime.PyModule_AddObject(ClrModuleReference, "loader", import_hook_module.Steal()) != 0) { throw PythonException.ThrowLastAsClrException(); } @@ -232,7 +232,7 @@ internal static void AddNamespaceWithGIL(string name) { using var pyNs = Runtime.PyString_FromString(name); var nsSet = Runtime.PyDict_GetItemString(clrModule.dict, _available_namespaces); - if (!(nsSet.IsNull || nsSet == Runtime.PyNone)) + if (!(nsSet.IsNull || nsSet == Runtime.PyNone)) { if (Runtime.PySet_Add(nsSet, pyNs.BorrowOrThrow()) != 0) { diff --git a/src/runtime/Interop.cs b/src/runtime/Interop.cs index 4aa4aa09b..8ef1cf030 100644 --- a/src/runtime/Interop.cs +++ b/src/runtime/Interop.cs @@ -2,9 +2,10 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Reflection; using System.Runtime.InteropServices; + using Python.Runtime.Reflection; -using System.Reflection; namespace Python.Runtime { @@ -61,7 +62,7 @@ public ModulePropertyAttribute() /// // Py_TPFLAGS_* [Flags] - public enum TypeFlags: long + public enum TypeFlags : long { HeapType = (1 << 9), BaseType = (1 << 10), diff --git a/src/runtime/InteropConfiguration.cs b/src/runtime/InteropConfiguration.cs index 781d0d01f..ef6b9cc2e 100644 --- a/src/runtime/InteropConfiguration.cs +++ b/src/runtime/InteropConfiguration.cs @@ -6,7 +6,7 @@ namespace Python.Runtime using Python.Runtime.Mixins; - public sealed class InteropConfiguration: IDisposable + public sealed class InteropConfiguration : IDisposable { internal readonly PythonBaseTypeProviderGroup pythonBaseTypeProviders = new(); diff --git a/src/runtime/Loader.cs b/src/runtime/Loader.cs index 516b9ab9c..2591f9590 100644 --- a/src/runtime/Loader.cs +++ b/src/runtime/Loader.cs @@ -33,7 +33,7 @@ public unsafe static int Initialize(IntPtr data, int size) ); return 1; } - + return 0; } diff --git a/src/runtime/MethodBinder.cs b/src/runtime/MethodBinder.cs index 9a5515c8e..2bc15655d 100644 --- a/src/runtime/MethodBinder.cs +++ b/src/runtime/MethodBinder.cs @@ -1,10 +1,10 @@ using System; using System.Collections; -using System.Reflection; -using System.Text; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Reflection; +using System.Text; namespace Python.Runtime { @@ -621,7 +621,7 @@ static BorrowedReference HandleParamsArray(BorrowedReference args, int arrayStar } else { - if(arrayStart == paramIndex) + if (arrayStart == paramIndex) { op = HandleParamsArray(args, arrayStart, pyArgCount, out tempObject); } @@ -794,7 +794,8 @@ static bool MatchesArgumentCount(int positionalArgumentCount, ParameterInfo[] pa defaultArgList.Add(parameters[v].GetDefaultValue()); defaultsNeeded++; } - else if (parameters[v].IsOut) { + else if (parameters[v].IsOut) + { defaultArgList.Add(null); } else if (!paramsArray) diff --git a/src/runtime/Mixins/collections.py b/src/runtime/Mixins/collections.py index 95a6d8162..4e2693210 100644 --- a/src/runtime/Mixins/collections.py +++ b/src/runtime/Mixins/collections.py @@ -5,53 +5,76 @@ import collections.abc as col + class IteratorMixin(col.Iterator): def close(self): - if hasattr(self, 'Dispose'): + if hasattr(self, "Dispose"): self.Dispose() else: from System import IDisposable + IDisposable(self).Dispose() + class IterableMixin(col.Iterable): pass + class SizedMixin(col.Sized): - def __len__(self): return self.Count + def __len__(self): + return self.Count + class ContainerMixin(col.Container): def __contains__(self, item): - if hasattr('self', 'Contains'): + if hasattr("self", "Contains"): return self.Contains(item) else: from System.Collections.Generic import ICollection + return ICollection(self).Contains(item) + try: abc_Collection = col.Collection except AttributeError: # Python 3.5- does not have collections.abc.Collection abc_Collection = col.Container + class CollectionMixin(SizedMixin, IterableMixin, ContainerMixin, abc_Collection): pass + class SequenceMixin(CollectionMixin, col.Sequence): pass + class MutableSequenceMixin(SequenceMixin, col.MutableSequence): pass + class MappingMixin(CollectionMixin, col.Mapping): - def __contains__(self, item): return self.ContainsKey(item) - def keys(self): return self.Keys - def items(self): return [(k,self.get(k)) for k in self.Keys] - def values(self): return self.Values - def __iter__(self): return self.Keys.__iter__() + def __contains__(self, item): + return self.ContainsKey(item) + + def keys(self): + return self.Keys + + def items(self): + return [(k, self.get(k)) for k in self.Keys] + + def values(self): + return self.Values + + def __iter__(self): + return self.Keys.__iter__() + def get(self, key, default=None): existed, item = self.TryGetValue(key, None) return item if existed else default + class MutableMappingMixin(MappingMixin, col.MutableMapping): _UNSET_ = object() diff --git a/src/runtime/Native/ABI.cs b/src/runtime/Native/ABI.cs index c41b42f0a..78976dfd3 100644 --- a/src/runtime/Native/ABI.cs +++ b/src/runtime/Native/ABI.cs @@ -39,7 +39,7 @@ static unsafe int GetRefCountOffset() using var tempObject = Runtime.PyList_New(0); IntPtr* tempPtr = (IntPtr*)tempObject.DangerousGetAddress(); int offset = 0; - while(tempPtr[offset] != (IntPtr)1) + while (tempPtr[offset] != (IntPtr)1) { offset++; if (offset > 100) diff --git a/src/runtime/Native/BorrowedReference.cs b/src/runtime/Native/BorrowedReference.cs index fd1059a5f..ea820b4ea 100644 --- a/src/runtime/Native/BorrowedReference.cs +++ b/src/runtime/Native/BorrowedReference.cs @@ -42,7 +42,8 @@ public BorrowedReference(IntPtr pointer) public static bool operator !=(NullOnly? @null, BorrowedReference reference) => !reference.IsNull; - public override bool Equals(object obj) { + public override bool Equals(object obj) + { if (obj is IntPtr ptr) return ptr == pointer; diff --git a/src/runtime/Native/LibDL.cs b/src/runtime/Native/LibDL.cs index 3dad73735..1dce5131e 100644 --- a/src/runtime/Native/LibDL.cs +++ b/src/runtime/Native/LibDL.cs @@ -32,7 +32,8 @@ public static ILibDL GetInstance() // call dlerror to ensure library is resolved libdl2.dlerror(); return libdl2; - } catch (DllNotFoundException) + } + catch (DllNotFoundException) { return new LinuxLibDL(); } diff --git a/src/runtime/Native/LibraryLoader.cs b/src/runtime/Native/LibraryLoader.cs index 05f960481..78641d58f 100644 --- a/src/runtime/Native/LibraryLoader.cs +++ b/src/runtime/Native/LibraryLoader.cs @@ -120,7 +120,7 @@ public IntPtr GetFunction(IntPtr hModule, string procedureName) { if (hModule == IntPtr.Zero) { - foreach(var module in GetAllModules()) + foreach (var module in GetAllModules()) { var func = GetProcAddress(module, procedureName); if (func != IntPtr.Zero) return func; diff --git a/src/runtime/Native/NativeCall.cs b/src/runtime/Native/NativeCall.cs index 2ea7b344e..29065ffa2 100644 --- a/src/runtime/Native/NativeCall.cs +++ b/src/runtime/Native/NativeCall.cs @@ -14,13 +14,13 @@ internal unsafe class NativeCall public static void CallDealloc(IntPtr fp, StolenReference a1) { var d = (delegate* unmanaged[Cdecl])fp; - d(a1); + d(a1.AnalyzerWorkaround()); } public static NewReference Call_3(IntPtr fp, BorrowedReference a1, BorrowedReference a2, BorrowedReference a3) { var d = (delegate* unmanaged[Cdecl])fp; - return d(a1, a2, a3); + return d(a1, a2, a3).Move(); } diff --git a/src/runtime/Native/NewReference.cs b/src/runtime/Native/NewReference.cs index f7a030818..e2ec90c14 100644 --- a/src/runtime/Native/NewReference.cs +++ b/src/runtime/Native/NewReference.cs @@ -122,9 +122,11 @@ public void Dispose() /// /// Creates from a raw pointer /// +#pragma warning disable NoCopy05, NoCopy06 [Pure] public static NewReference DangerousFromPointer(IntPtr pointer) - => new() { pointer = pointer}; + => new() { pointer = pointer }; +#pragma warning restore [Pure] internal static IntPtr DangerousGetAddressOrNull(in NewReference reference) => reference.pointer; diff --git a/src/runtime/Native/PyBufferInterface.cs b/src/runtime/Native/PyBufferInterface.cs index 431d609f4..523d76f9a 100644 --- a/src/runtime/Native/PyBufferInterface.cs +++ b/src/runtime/Native/PyBufferInterface.cs @@ -5,7 +5,8 @@ namespace Python.Runtime { /* buffer interface */ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - internal struct Py_buffer { + internal struct Py_buffer + { public IntPtr buf; public IntPtr obj; /* owned reference */ /// Buffer size in bytes diff --git a/src/runtime/Native/PyGILState.cs b/src/runtime/Native/PyGILState.cs index 2e7f61029..dfd519a21 100644 --- a/src/runtime/Native/PyGILState.cs +++ b/src/runtime/Native/PyGILState.cs @@ -4,5 +4,5 @@ namespace Python.Runtime.Native; enum PyGILState { PyGILState_LOCKED, - PyGILState_UNLOCKED + PyGILState_UNLOCKED } diff --git a/src/runtime/Native/PyIdentifier_.cs b/src/runtime/Native/PyIdentifier_.cs index 1ea2b704c..ae0fa5615 100644 --- a/src/runtime/Native/PyIdentifier_.cs +++ b/src/runtime/Native/PyIdentifier_.cs @@ -5,40 +5,40 @@ namespace Python.Runtime static class PyIdentifier { #pragma warning disable CS0649 // indentifier is never assigned to (assigned with reflection) - static IntPtr f__name__; - public static BorrowedReference __name__ => new(f__name__); - static IntPtr f__dict__; - public static BorrowedReference __dict__ => new(f__dict__); - static IntPtr f__doc__; - public static BorrowedReference __doc__ => new(f__doc__); - static IntPtr f__class__; - public static BorrowedReference __class__ => new(f__class__); - static IntPtr f__clear_reentry_guard__; - public static BorrowedReference __clear_reentry_guard__ => new(f__clear_reentry_guard__); - static IntPtr f__module__; - public static BorrowedReference __module__ => new(f__module__); - static IntPtr f__file__; - public static BorrowedReference __file__ => new(f__file__); - static IntPtr f__slots__; - public static BorrowedReference __slots__ => new(f__slots__); - static IntPtr f__self__; - public static BorrowedReference __self__ => new(f__self__); - static IntPtr f__annotations__; - public static BorrowedReference __annotations__ => new(f__annotations__); - static IntPtr f__init__; - public static BorrowedReference __init__ => new(f__init__); - static IntPtr f__repr__; - public static BorrowedReference __repr__ => new(f__repr__); - static IntPtr f__import__; - public static BorrowedReference __import__ => new(f__import__); - static IntPtr f__builtins__; - public static BorrowedReference __builtins__ => new(f__builtins__); - static IntPtr fbuiltins; - public static BorrowedReference builtins => new(fbuiltins); - static IntPtr f__overloads__; - public static BorrowedReference __overloads__ => new(f__overloads__); - static IntPtr fOverloads; - public static BorrowedReference Overloads => new(fOverloads); + static IntPtr f__name__; + public static BorrowedReference __name__ => new(f__name__); + static IntPtr f__dict__; + public static BorrowedReference __dict__ => new(f__dict__); + static IntPtr f__doc__; + public static BorrowedReference __doc__ => new(f__doc__); + static IntPtr f__class__; + public static BorrowedReference __class__ => new(f__class__); + static IntPtr f__clear_reentry_guard__; + public static BorrowedReference __clear_reentry_guard__ => new(f__clear_reentry_guard__); + static IntPtr f__module__; + public static BorrowedReference __module__ => new(f__module__); + static IntPtr f__file__; + public static BorrowedReference __file__ => new(f__file__); + static IntPtr f__slots__; + public static BorrowedReference __slots__ => new(f__slots__); + static IntPtr f__self__; + public static BorrowedReference __self__ => new(f__self__); + static IntPtr f__annotations__; + public static BorrowedReference __annotations__ => new(f__annotations__); + static IntPtr f__init__; + public static BorrowedReference __init__ => new(f__init__); + static IntPtr f__repr__; + public static BorrowedReference __repr__ => new(f__repr__); + static IntPtr f__import__; + public static BorrowedReference __import__ => new(f__import__); + static IntPtr f__builtins__; + public static BorrowedReference __builtins__ => new(f__builtins__); + static IntPtr fbuiltins; + public static BorrowedReference builtins => new(fbuiltins); + static IntPtr f__overloads__; + public static BorrowedReference __overloads__ => new(f__overloads__); + static IntPtr fOverloads; + public static BorrowedReference Overloads => new(fOverloads); #pragma warning restore CS0649 // indentifier is never assigned to (assigned with reflection) } diff --git a/src/runtime/Native/PyMemberFlags.cs b/src/runtime/Native/PyMemberFlags.cs index 56ba8962b..ec51f6838 100644 --- a/src/runtime/Native/PyMemberFlags.cs +++ b/src/runtime/Native/PyMemberFlags.cs @@ -3,7 +3,7 @@ namespace Python.Runtime.Native; [Flags] -enum PyMemberFlags: int +enum PyMemberFlags : int { None = 0, ReadOnly = 1, diff --git a/src/runtime/Native/PyMemberType.cs b/src/runtime/Native/PyMemberType.cs index 261d552a5..d34c1c0f8 100644 --- a/src/runtime/Native/PyMemberType.cs +++ b/src/runtime/Native/PyMemberType.cs @@ -1,6 +1,6 @@ namespace Python.Runtime.Native; -enum PyMemberType: int +enum PyMemberType : int { Short = 0, Int = 1, diff --git a/src/runtime/Native/TypeOffset.cs b/src/runtime/Native/TypeOffset.cs index 803b86bfa..a6ae08def 100644 --- a/src/runtime/Native/TypeOffset.cs +++ b/src/runtime/Native/TypeOffset.cs @@ -152,7 +152,7 @@ static void ValidateRequiredOffsetsPresent(PropertyInfo[] offsetProperties) foreach (var managedType in managedTypes) { var slots = managedType.GetMethods(BindingFlags.Public | BindingFlags.Static); - foreach(var slot in slots) + foreach (var slot in slots) if (!present.Contains(slot.Name)) missing.Add(slot.Name); } diff --git a/src/runtime/Native/TypeOffset310.cs b/src/runtime/Native/TypeOffset310.cs index fc0ca1e8c..a84d8b76d 100644 --- a/src/runtime/Native/TypeOffset310.cs +++ b/src/runtime/Native/TypeOffset310.cs @@ -24,117 +24,117 @@ internal class TypeOffset310 : GeneratedTypeOffsets, ITypeOffsets { public TypeOffset310() { } // Auto-generated from PyHeapTypeObject in Python.h - public int ob_refcnt { get; private set; } - public int ob_type { get; private set; } - public int ob_size { get; private set; } - public int tp_name { get; private set; } - public int tp_basicsize { get; private set; } - public int tp_itemsize { get; private set; } - public int tp_dealloc { get; private set; } - public int tp_vectorcall_offset { get; private set; } - public int tp_getattr { get; private set; } - public int tp_setattr { get; private set; } - public int tp_as_async { get; private set; } - public int tp_repr { get; private set; } - public int tp_as_number { get; private set; } - public int tp_as_sequence { get; private set; } - public int tp_as_mapping { get; private set; } - public int tp_hash { get; private set; } - public int tp_call { get; private set; } - public int tp_str { get; private set; } - public int tp_getattro { get; private set; } - public int tp_setattro { get; private set; } - public int tp_as_buffer { get; private set; } - public int tp_flags { get; private set; } - public int tp_doc { get; private set; } - public int tp_traverse { get; private set; } - public int tp_clear { get; private set; } - public int tp_richcompare { get; private set; } - public int tp_weaklistoffset { get; private set; } - public int tp_iter { get; private set; } - public int tp_iternext { get; private set; } - public int tp_methods { get; private set; } - public int tp_members { get; private set; } - public int tp_getset { get; private set; } - public int tp_base { get; private set; } - public int tp_dict { get; private set; } - public int tp_descr_get { get; private set; } - public int tp_descr_set { get; private set; } - public int tp_dictoffset { get; private set; } - public int tp_init { get; private set; } - public int tp_alloc { get; private set; } - public int tp_new { get; private set; } - public int tp_free { get; private set; } - public int tp_is_gc { get; private set; } - public int tp_bases { get; private set; } - public int tp_mro { get; private set; } - public int tp_cache { get; private set; } - public int tp_subclasses { get; private set; } - public int tp_weaklist { get; private set; } - public int tp_del { get; private set; } - public int tp_version_tag { get; private set; } - public int tp_finalize { get; private set; } - public int tp_vectorcall { get; private set; } - public int am_await { get; private set; } - public int am_aiter { get; private set; } - public int am_anext { get; private set; } - public int am_send { get; private set; } - public int nb_add { get; private set; } - public int nb_subtract { get; private set; } - public int nb_multiply { get; private set; } - public int nb_remainder { get; private set; } - public int nb_divmod { get; private set; } - public int nb_power { get; private set; } - public int nb_negative { get; private set; } - public int nb_positive { get; private set; } - public int nb_absolute { get; private set; } - public int nb_bool { get; private set; } - public int nb_invert { get; private set; } - public int nb_lshift { get; private set; } - public int nb_rshift { get; private set; } - public int nb_and { get; private set; } - public int nb_xor { get; private set; } - public int nb_or { get; private set; } - public int nb_int { get; private set; } - public int nb_reserved { get; private set; } - public int nb_float { get; private set; } - public int nb_inplace_add { get; private set; } - public int nb_inplace_subtract { get; private set; } - public int nb_inplace_multiply { get; private set; } - public int nb_inplace_remainder { get; private set; } - public int nb_inplace_power { get; private set; } - public int nb_inplace_lshift { get; private set; } - public int nb_inplace_rshift { get; private set; } - public int nb_inplace_and { get; private set; } - public int nb_inplace_xor { get; private set; } - public int nb_inplace_or { get; private set; } - public int nb_floor_divide { get; private set; } - public int nb_true_divide { get; private set; } - public int nb_inplace_floor_divide { get; private set; } - public int nb_inplace_true_divide { get; private set; } - public int nb_index { get; private set; } - public int nb_matrix_multiply { get; private set; } - public int nb_inplace_matrix_multiply { get; private set; } - public int mp_length { get; private set; } - public int mp_subscript { get; private set; } - public int mp_ass_subscript { get; private set; } - public int sq_length { get; private set; } - public int sq_concat { get; private set; } - public int sq_repeat { get; private set; } - public int sq_item { get; private set; } - public int was_sq_slice { get; private set; } - public int sq_ass_item { get; private set; } - public int was_sq_ass_slice { get; private set; } - public int sq_contains { get; private set; } - public int sq_inplace_concat { get; private set; } - public int sq_inplace_repeat { get; private set; } - public int bf_getbuffer { get; private set; } - public int bf_releasebuffer { get; private set; } - public int name { get; private set; } - public int ht_slots { get; private set; } - public int qualname { get; private set; } - public int ht_cached_keys { get; private set; } - public int ht_module { get; private set; } + public int ob_refcnt { get; private set; } + public int ob_type { get; private set; } + public int ob_size { get; private set; } + public int tp_name { get; private set; } + public int tp_basicsize { get; private set; } + public int tp_itemsize { get; private set; } + public int tp_dealloc { get; private set; } + public int tp_vectorcall_offset { get; private set; } + public int tp_getattr { get; private set; } + public int tp_setattr { get; private set; } + public int tp_as_async { get; private set; } + public int tp_repr { get; private set; } + public int tp_as_number { get; private set; } + public int tp_as_sequence { get; private set; } + public int tp_as_mapping { get; private set; } + public int tp_hash { get; private set; } + public int tp_call { get; private set; } + public int tp_str { get; private set; } + public int tp_getattro { get; private set; } + public int tp_setattro { get; private set; } + public int tp_as_buffer { get; private set; } + public int tp_flags { get; private set; } + public int tp_doc { get; private set; } + public int tp_traverse { get; private set; } + public int tp_clear { get; private set; } + public int tp_richcompare { get; private set; } + public int tp_weaklistoffset { get; private set; } + public int tp_iter { get; private set; } + public int tp_iternext { get; private set; } + public int tp_methods { get; private set; } + public int tp_members { get; private set; } + public int tp_getset { get; private set; } + public int tp_base { get; private set; } + public int tp_dict { get; private set; } + public int tp_descr_get { get; private set; } + public int tp_descr_set { get; private set; } + public int tp_dictoffset { get; private set; } + public int tp_init { get; private set; } + public int tp_alloc { get; private set; } + public int tp_new { get; private set; } + public int tp_free { get; private set; } + public int tp_is_gc { get; private set; } + public int tp_bases { get; private set; } + public int tp_mro { get; private set; } + public int tp_cache { get; private set; } + public int tp_subclasses { get; private set; } + public int tp_weaklist { get; private set; } + public int tp_del { get; private set; } + public int tp_version_tag { get; private set; } + public int tp_finalize { get; private set; } + public int tp_vectorcall { get; private set; } + public int am_await { get; private set; } + public int am_aiter { get; private set; } + public int am_anext { get; private set; } + public int am_send { get; private set; } + public int nb_add { get; private set; } + public int nb_subtract { get; private set; } + public int nb_multiply { get; private set; } + public int nb_remainder { get; private set; } + public int nb_divmod { get; private set; } + public int nb_power { get; private set; } + public int nb_negative { get; private set; } + public int nb_positive { get; private set; } + public int nb_absolute { get; private set; } + public int nb_bool { get; private set; } + public int nb_invert { get; private set; } + public int nb_lshift { get; private set; } + public int nb_rshift { get; private set; } + public int nb_and { get; private set; } + public int nb_xor { get; private set; } + public int nb_or { get; private set; } + public int nb_int { get; private set; } + public int nb_reserved { get; private set; } + public int nb_float { get; private set; } + public int nb_inplace_add { get; private set; } + public int nb_inplace_subtract { get; private set; } + public int nb_inplace_multiply { get; private set; } + public int nb_inplace_remainder { get; private set; } + public int nb_inplace_power { get; private set; } + public int nb_inplace_lshift { get; private set; } + public int nb_inplace_rshift { get; private set; } + public int nb_inplace_and { get; private set; } + public int nb_inplace_xor { get; private set; } + public int nb_inplace_or { get; private set; } + public int nb_floor_divide { get; private set; } + public int nb_true_divide { get; private set; } + public int nb_inplace_floor_divide { get; private set; } + public int nb_inplace_true_divide { get; private set; } + public int nb_index { get; private set; } + public int nb_matrix_multiply { get; private set; } + public int nb_inplace_matrix_multiply { get; private set; } + public int mp_length { get; private set; } + public int mp_subscript { get; private set; } + public int mp_ass_subscript { get; private set; } + public int sq_length { get; private set; } + public int sq_concat { get; private set; } + public int sq_repeat { get; private set; } + public int sq_item { get; private set; } + public int was_sq_slice { get; private set; } + public int sq_ass_item { get; private set; } + public int was_sq_ass_slice { get; private set; } + public int sq_contains { get; private set; } + public int sq_inplace_concat { get; private set; } + public int sq_inplace_repeat { get; private set; } + public int bf_getbuffer { get; private set; } + public int bf_releasebuffer { get; private set; } + public int name { get; private set; } + public int ht_slots { get; private set; } + public int qualname { get; private set; } + public int ht_cached_keys { get; private set; } + public int ht_module { get; private set; } } } diff --git a/src/runtime/Native/TypeOffset311.cs b/src/runtime/Native/TypeOffset311.cs index de5afacb9..738b49fb7 100644 --- a/src/runtime/Native/TypeOffset311.cs +++ b/src/runtime/Native/TypeOffset311.cs @@ -24,118 +24,118 @@ internal class TypeOffset311 : GeneratedTypeOffsets, ITypeOffsets { public TypeOffset311() { } // Auto-generated from PyHeapTypeObject in Python.h - public int ob_refcnt { get; private set; } - public int ob_type { get; private set; } - public int ob_size { get; private set; } - public int tp_name { get; private set; } - public int tp_basicsize { get; private set; } - public int tp_itemsize { get; private set; } - public int tp_dealloc { get; private set; } - public int tp_vectorcall_offset { get; private set; } - public int tp_getattr { get; private set; } - public int tp_setattr { get; private set; } - public int tp_as_async { get; private set; } - public int tp_repr { get; private set; } - public int tp_as_number { get; private set; } - public int tp_as_sequence { get; private set; } - public int tp_as_mapping { get; private set; } - public int tp_hash { get; private set; } - public int tp_call { get; private set; } - public int tp_str { get; private set; } - public int tp_getattro { get; private set; } - public int tp_setattro { get; private set; } - public int tp_as_buffer { get; private set; } - public int tp_flags { get; private set; } - public int tp_doc { get; private set; } - public int tp_traverse { get; private set; } - public int tp_clear { get; private set; } - public int tp_richcompare { get; private set; } - public int tp_weaklistoffset { get; private set; } - public int tp_iter { get; private set; } - public int tp_iternext { get; private set; } - public int tp_methods { get; private set; } - public int tp_members { get; private set; } - public int tp_getset { get; private set; } - public int tp_base { get; private set; } - public int tp_dict { get; private set; } - public int tp_descr_get { get; private set; } - public int tp_descr_set { get; private set; } - public int tp_dictoffset { get; private set; } - public int tp_init { get; private set; } - public int tp_alloc { get; private set; } - public int tp_new { get; private set; } - public int tp_free { get; private set; } - public int tp_is_gc { get; private set; } - public int tp_bases { get; private set; } - public int tp_mro { get; private set; } - public int tp_cache { get; private set; } - public int tp_subclasses { get; private set; } - public int tp_weaklist { get; private set; } - public int tp_del { get; private set; } - public int tp_version_tag { get; private set; } - public int tp_finalize { get; private set; } - public int tp_vectorcall { get; private set; } - public int am_await { get; private set; } - public int am_aiter { get; private set; } - public int am_anext { get; private set; } - public int am_send { get; private set; } - public int nb_add { get; private set; } - public int nb_subtract { get; private set; } - public int nb_multiply { get; private set; } - public int nb_remainder { get; private set; } - public int nb_divmod { get; private set; } - public int nb_power { get; private set; } - public int nb_negative { get; private set; } - public int nb_positive { get; private set; } - public int nb_absolute { get; private set; } - public int nb_bool { get; private set; } - public int nb_invert { get; private set; } - public int nb_lshift { get; private set; } - public int nb_rshift { get; private set; } - public int nb_and { get; private set; } - public int nb_xor { get; private set; } - public int nb_or { get; private set; } - public int nb_int { get; private set; } - public int nb_reserved { get; private set; } - public int nb_float { get; private set; } - public int nb_inplace_add { get; private set; } - public int nb_inplace_subtract { get; private set; } - public int nb_inplace_multiply { get; private set; } - public int nb_inplace_remainder { get; private set; } - public int nb_inplace_power { get; private set; } - public int nb_inplace_lshift { get; private set; } - public int nb_inplace_rshift { get; private set; } - public int nb_inplace_and { get; private set; } - public int nb_inplace_xor { get; private set; } - public int nb_inplace_or { get; private set; } - public int nb_floor_divide { get; private set; } - public int nb_true_divide { get; private set; } - public int nb_inplace_floor_divide { get; private set; } - public int nb_inplace_true_divide { get; private set; } - public int nb_index { get; private set; } - public int nb_matrix_multiply { get; private set; } - public int nb_inplace_matrix_multiply { get; private set; } - public int mp_length { get; private set; } - public int mp_subscript { get; private set; } - public int mp_ass_subscript { get; private set; } - public int sq_length { get; private set; } - public int sq_concat { get; private set; } - public int sq_repeat { get; private set; } - public int sq_item { get; private set; } - public int was_sq_slice { get; private set; } - public int sq_ass_item { get; private set; } - public int was_sq_ass_slice { get; private set; } - public int sq_contains { get; private set; } - public int sq_inplace_concat { get; private set; } - public int sq_inplace_repeat { get; private set; } - public int bf_getbuffer { get; private set; } - public int bf_releasebuffer { get; private set; } - public int name { get; private set; } - public int ht_slots { get; private set; } - public int qualname { get; private set; } - public int ht_cached_keys { get; private set; } - public int ht_module { get; private set; } - public int _ht_tpname { get; private set; } - public int spec_cache_getitem { get; private set; } + public int ob_refcnt { get; private set; } + public int ob_type { get; private set; } + public int ob_size { get; private set; } + public int tp_name { get; private set; } + public int tp_basicsize { get; private set; } + public int tp_itemsize { get; private set; } + public int tp_dealloc { get; private set; } + public int tp_vectorcall_offset { get; private set; } + public int tp_getattr { get; private set; } + public int tp_setattr { get; private set; } + public int tp_as_async { get; private set; } + public int tp_repr { get; private set; } + public int tp_as_number { get; private set; } + public int tp_as_sequence { get; private set; } + public int tp_as_mapping { get; private set; } + public int tp_hash { get; private set; } + public int tp_call { get; private set; } + public int tp_str { get; private set; } + public int tp_getattro { get; private set; } + public int tp_setattro { get; private set; } + public int tp_as_buffer { get; private set; } + public int tp_flags { get; private set; } + public int tp_doc { get; private set; } + public int tp_traverse { get; private set; } + public int tp_clear { get; private set; } + public int tp_richcompare { get; private set; } + public int tp_weaklistoffset { get; private set; } + public int tp_iter { get; private set; } + public int tp_iternext { get; private set; } + public int tp_methods { get; private set; } + public int tp_members { get; private set; } + public int tp_getset { get; private set; } + public int tp_base { get; private set; } + public int tp_dict { get; private set; } + public int tp_descr_get { get; private set; } + public int tp_descr_set { get; private set; } + public int tp_dictoffset { get; private set; } + public int tp_init { get; private set; } + public int tp_alloc { get; private set; } + public int tp_new { get; private set; } + public int tp_free { get; private set; } + public int tp_is_gc { get; private set; } + public int tp_bases { get; private set; } + public int tp_mro { get; private set; } + public int tp_cache { get; private set; } + public int tp_subclasses { get; private set; } + public int tp_weaklist { get; private set; } + public int tp_del { get; private set; } + public int tp_version_tag { get; private set; } + public int tp_finalize { get; private set; } + public int tp_vectorcall { get; private set; } + public int am_await { get; private set; } + public int am_aiter { get; private set; } + public int am_anext { get; private set; } + public int am_send { get; private set; } + public int nb_add { get; private set; } + public int nb_subtract { get; private set; } + public int nb_multiply { get; private set; } + public int nb_remainder { get; private set; } + public int nb_divmod { get; private set; } + public int nb_power { get; private set; } + public int nb_negative { get; private set; } + public int nb_positive { get; private set; } + public int nb_absolute { get; private set; } + public int nb_bool { get; private set; } + public int nb_invert { get; private set; } + public int nb_lshift { get; private set; } + public int nb_rshift { get; private set; } + public int nb_and { get; private set; } + public int nb_xor { get; private set; } + public int nb_or { get; private set; } + public int nb_int { get; private set; } + public int nb_reserved { get; private set; } + public int nb_float { get; private set; } + public int nb_inplace_add { get; private set; } + public int nb_inplace_subtract { get; private set; } + public int nb_inplace_multiply { get; private set; } + public int nb_inplace_remainder { get; private set; } + public int nb_inplace_power { get; private set; } + public int nb_inplace_lshift { get; private set; } + public int nb_inplace_rshift { get; private set; } + public int nb_inplace_and { get; private set; } + public int nb_inplace_xor { get; private set; } + public int nb_inplace_or { get; private set; } + public int nb_floor_divide { get; private set; } + public int nb_true_divide { get; private set; } + public int nb_inplace_floor_divide { get; private set; } + public int nb_inplace_true_divide { get; private set; } + public int nb_index { get; private set; } + public int nb_matrix_multiply { get; private set; } + public int nb_inplace_matrix_multiply { get; private set; } + public int mp_length { get; private set; } + public int mp_subscript { get; private set; } + public int mp_ass_subscript { get; private set; } + public int sq_length { get; private set; } + public int sq_concat { get; private set; } + public int sq_repeat { get; private set; } + public int sq_item { get; private set; } + public int was_sq_slice { get; private set; } + public int sq_ass_item { get; private set; } + public int was_sq_ass_slice { get; private set; } + public int sq_contains { get; private set; } + public int sq_inplace_concat { get; private set; } + public int sq_inplace_repeat { get; private set; } + public int bf_getbuffer { get; private set; } + public int bf_releasebuffer { get; private set; } + public int name { get; private set; } + public int ht_slots { get; private set; } + public int qualname { get; private set; } + public int ht_cached_keys { get; private set; } + public int ht_module { get; private set; } + public int _ht_tpname { get; private set; } + public int spec_cache_getitem { get; private set; } } } diff --git a/src/runtime/Native/TypeOffset312.cs b/src/runtime/Native/TypeOffset312.cs index 8ba30e816..1219650d3 100644 --- a/src/runtime/Native/TypeOffset312.cs +++ b/src/runtime/Native/TypeOffset312.cs @@ -24,121 +24,121 @@ internal class TypeOffset312 : GeneratedTypeOffsets, ITypeOffsets { public TypeOffset312() { } // Auto-generated from PyHeapTypeObject in Python.h - public int ob_refcnt { get; private set; } - public int ob_type { get; private set; } - public int ob_size { get; private set; } - public int tp_name { get; private set; } - public int tp_basicsize { get; private set; } - public int tp_itemsize { get; private set; } - public int tp_dealloc { get; private set; } - public int tp_vectorcall_offset { get; private set; } - public int tp_getattr { get; private set; } - public int tp_setattr { get; private set; } - public int tp_as_async { get; private set; } - public int tp_repr { get; private set; } - public int tp_as_number { get; private set; } - public int tp_as_sequence { get; private set; } - public int tp_as_mapping { get; private set; } - public int tp_hash { get; private set; } - public int tp_call { get; private set; } - public int tp_str { get; private set; } - public int tp_getattro { get; private set; } - public int tp_setattro { get; private set; } - public int tp_as_buffer { get; private set; } - public int tp_flags { get; private set; } - public int tp_doc { get; private set; } - public int tp_traverse { get; private set; } - public int tp_clear { get; private set; } - public int tp_richcompare { get; private set; } - public int tp_weaklistoffset { get; private set; } - public int tp_iter { get; private set; } - public int tp_iternext { get; private set; } - public int tp_methods { get; private set; } - public int tp_members { get; private set; } - public int tp_getset { get; private set; } - public int tp_base { get; private set; } - public int tp_dict { get; private set; } - public int tp_descr_get { get; private set; } - public int tp_descr_set { get; private set; } - public int tp_dictoffset { get; private set; } - public int tp_init { get; private set; } - public int tp_alloc { get; private set; } - public int tp_new { get; private set; } - public int tp_free { get; private set; } - public int tp_is_gc { get; private set; } - public int tp_bases { get; private set; } - public int tp_mro { get; private set; } - public int tp_cache { get; private set; } - public int tp_subclasses { get; private set; } - public int tp_weaklist { get; private set; } - public int tp_del { get; private set; } - public int tp_version_tag { get; private set; } - public int tp_finalize { get; private set; } - public int tp_vectorcall { get; private set; } - public int tp_watched { get; private set; } - public int am_await { get; private set; } - public int am_aiter { get; private set; } - public int am_anext { get; private set; } - public int am_send { get; private set; } - public int nb_add { get; private set; } - public int nb_subtract { get; private set; } - public int nb_multiply { get; private set; } - public int nb_remainder { get; private set; } - public int nb_divmod { get; private set; } - public int nb_power { get; private set; } - public int nb_negative { get; private set; } - public int nb_positive { get; private set; } - public int nb_absolute { get; private set; } - public int nb_bool { get; private set; } - public int nb_invert { get; private set; } - public int nb_lshift { get; private set; } - public int nb_rshift { get; private set; } - public int nb_and { get; private set; } - public int nb_xor { get; private set; } - public int nb_or { get; private set; } - public int nb_int { get; private set; } - public int nb_reserved { get; private set; } - public int nb_float { get; private set; } - public int nb_inplace_add { get; private set; } - public int nb_inplace_subtract { get; private set; } - public int nb_inplace_multiply { get; private set; } - public int nb_inplace_remainder { get; private set; } - public int nb_inplace_power { get; private set; } - public int nb_inplace_lshift { get; private set; } - public int nb_inplace_rshift { get; private set; } - public int nb_inplace_and { get; private set; } - public int nb_inplace_xor { get; private set; } - public int nb_inplace_or { get; private set; } - public int nb_floor_divide { get; private set; } - public int nb_true_divide { get; private set; } - public int nb_inplace_floor_divide { get; private set; } - public int nb_inplace_true_divide { get; private set; } - public int nb_index { get; private set; } - public int nb_matrix_multiply { get; private set; } - public int nb_inplace_matrix_multiply { get; private set; } - public int mp_length { get; private set; } - public int mp_subscript { get; private set; } - public int mp_ass_subscript { get; private set; } - public int sq_length { get; private set; } - public int sq_concat { get; private set; } - public int sq_repeat { get; private set; } - public int sq_item { get; private set; } - public int was_sq_slice { get; private set; } - public int sq_ass_item { get; private set; } - public int was_sq_ass_slice { get; private set; } - public int sq_contains { get; private set; } - public int sq_inplace_concat { get; private set; } - public int sq_inplace_repeat { get; private set; } - public int bf_getbuffer { get; private set; } - public int bf_releasebuffer { get; private set; } - public int name { get; private set; } - public int ht_slots { get; private set; } - public int qualname { get; private set; } - public int ht_cached_keys { get; private set; } - public int ht_module { get; private set; } - public int _ht_tpname { get; private set; } - public int spec_cache_getitem { get; private set; } - public int getitem_version { get; private set; } + public int ob_refcnt { get; private set; } + public int ob_type { get; private set; } + public int ob_size { get; private set; } + public int tp_name { get; private set; } + public int tp_basicsize { get; private set; } + public int tp_itemsize { get; private set; } + public int tp_dealloc { get; private set; } + public int tp_vectorcall_offset { get; private set; } + public int tp_getattr { get; private set; } + public int tp_setattr { get; private set; } + public int tp_as_async { get; private set; } + public int tp_repr { get; private set; } + public int tp_as_number { get; private set; } + public int tp_as_sequence { get; private set; } + public int tp_as_mapping { get; private set; } + public int tp_hash { get; private set; } + public int tp_call { get; private set; } + public int tp_str { get; private set; } + public int tp_getattro { get; private set; } + public int tp_setattro { get; private set; } + public int tp_as_buffer { get; private set; } + public int tp_flags { get; private set; } + public int tp_doc { get; private set; } + public int tp_traverse { get; private set; } + public int tp_clear { get; private set; } + public int tp_richcompare { get; private set; } + public int tp_weaklistoffset { get; private set; } + public int tp_iter { get; private set; } + public int tp_iternext { get; private set; } + public int tp_methods { get; private set; } + public int tp_members { get; private set; } + public int tp_getset { get; private set; } + public int tp_base { get; private set; } + public int tp_dict { get; private set; } + public int tp_descr_get { get; private set; } + public int tp_descr_set { get; private set; } + public int tp_dictoffset { get; private set; } + public int tp_init { get; private set; } + public int tp_alloc { get; private set; } + public int tp_new { get; private set; } + public int tp_free { get; private set; } + public int tp_is_gc { get; private set; } + public int tp_bases { get; private set; } + public int tp_mro { get; private set; } + public int tp_cache { get; private set; } + public int tp_subclasses { get; private set; } + public int tp_weaklist { get; private set; } + public int tp_del { get; private set; } + public int tp_version_tag { get; private set; } + public int tp_finalize { get; private set; } + public int tp_vectorcall { get; private set; } + public int tp_watched { get; private set; } + public int am_await { get; private set; } + public int am_aiter { get; private set; } + public int am_anext { get; private set; } + public int am_send { get; private set; } + public int nb_add { get; private set; } + public int nb_subtract { get; private set; } + public int nb_multiply { get; private set; } + public int nb_remainder { get; private set; } + public int nb_divmod { get; private set; } + public int nb_power { get; private set; } + public int nb_negative { get; private set; } + public int nb_positive { get; private set; } + public int nb_absolute { get; private set; } + public int nb_bool { get; private set; } + public int nb_invert { get; private set; } + public int nb_lshift { get; private set; } + public int nb_rshift { get; private set; } + public int nb_and { get; private set; } + public int nb_xor { get; private set; } + public int nb_or { get; private set; } + public int nb_int { get; private set; } + public int nb_reserved { get; private set; } + public int nb_float { get; private set; } + public int nb_inplace_add { get; private set; } + public int nb_inplace_subtract { get; private set; } + public int nb_inplace_multiply { get; private set; } + public int nb_inplace_remainder { get; private set; } + public int nb_inplace_power { get; private set; } + public int nb_inplace_lshift { get; private set; } + public int nb_inplace_rshift { get; private set; } + public int nb_inplace_and { get; private set; } + public int nb_inplace_xor { get; private set; } + public int nb_inplace_or { get; private set; } + public int nb_floor_divide { get; private set; } + public int nb_true_divide { get; private set; } + public int nb_inplace_floor_divide { get; private set; } + public int nb_inplace_true_divide { get; private set; } + public int nb_index { get; private set; } + public int nb_matrix_multiply { get; private set; } + public int nb_inplace_matrix_multiply { get; private set; } + public int mp_length { get; private set; } + public int mp_subscript { get; private set; } + public int mp_ass_subscript { get; private set; } + public int sq_length { get; private set; } + public int sq_concat { get; private set; } + public int sq_repeat { get; private set; } + public int sq_item { get; private set; } + public int was_sq_slice { get; private set; } + public int sq_ass_item { get; private set; } + public int was_sq_ass_slice { get; private set; } + public int sq_contains { get; private set; } + public int sq_inplace_concat { get; private set; } + public int sq_inplace_repeat { get; private set; } + public int bf_getbuffer { get; private set; } + public int bf_releasebuffer { get; private set; } + public int name { get; private set; } + public int ht_slots { get; private set; } + public int qualname { get; private set; } + public int ht_cached_keys { get; private set; } + public int ht_module { get; private set; } + public int _ht_tpname { get; private set; } + public int spec_cache_getitem { get; private set; } + public int getitem_version { get; private set; } } } diff --git a/src/runtime/Properties/AssemblyInfo.cs b/src/runtime/Properties/AssemblyInfo.cs index b05fcc8bf..61b6bd0c5 100644 --- a/src/runtime/Properties/AssemblyInfo.cs +++ b/src/runtime/Properties/AssemblyInfo.cs @@ -2,4 +2,4 @@ [assembly: InternalsVisibleTo("Python.EmbeddingTest, PublicKey=00240000048000009400000006020000002400005253413100040000110000005ffd8f49fb44ab0641b3fd8d55e749f716e6dd901032295db641eb98ee46063cbe0d4a1d121ef0bc2af95f8a7438d7a80a3531316e6b75c2dae92fb05a99f03bf7e0c03980e1c3cfb74ba690aca2f3339ef329313bcc5dccced125a4ffdc4531dcef914602cd5878dc5fbb4d4c73ddfbc133f840231343e013762884d6143189")] -[assembly: InternalsVisibleTo("Python.Test, PublicKey=00240000048000009400000006020000002400005253413100040000110000005ffd8f49fb44ab0641b3fd8d55e749f716e6dd901032295db641eb98ee46063cbe0d4a1d121ef0bc2af95f8a7438d7a80a3531316e6b75c2dae92fb05a99f03bf7e0c03980e1c3cfb74ba690aca2f3339ef329313bcc5dccced125a4ffdc4531dcef914602cd5878dc5fbb4d4c73ddfbc133f840231343e013762884d6143189")] \ No newline at end of file +[assembly: InternalsVisibleTo("Python.Test, PublicKey=00240000048000009400000006020000002400005253413100040000110000005ffd8f49fb44ab0641b3fd8d55e749f716e6dd901032295db641eb98ee46063cbe0d4a1d121ef0bc2af95f8a7438d7a80a3531316e6b75c2dae92fb05a99f03bf7e0c03980e1c3cfb74ba690aca2f3339ef329313bcc5dccced125a4ffdc4531dcef914602cd5878dc5fbb4d4c73ddfbc133f840231343e013762884d6143189")] diff --git a/src/runtime/PyExportAttribute.cs b/src/runtime/PyExportAttribute.cs index 52a8be15d..6c591945a 100644 --- a/src/runtime/PyExportAttribute.cs +++ b/src/runtime/PyExportAttribute.cs @@ -1,4 +1,5 @@ -namespace Python.Runtime { +namespace Python.Runtime +{ using System; /// diff --git a/src/runtime/PythonEngine.cs b/src/runtime/PythonEngine.cs index 2c4c6c088..2a780a34a 100644 --- a/src/runtime/PythonEngine.cs +++ b/src/runtime/PythonEngine.cs @@ -452,7 +452,7 @@ public static void RemoveShutdownHandler(ShutdownHandler handler) /// static void ExecuteShutdownHandlers() { - while(ShutdownHandlers.Count > 0) + while (ShutdownHandlers.Count > 0) { var handler = ShutdownHandlers[ShutdownHandlers.Count - 1]; ShutdownHandlers.RemoveAt(ShutdownHandlers.Count - 1); diff --git a/src/runtime/PythonTypes/PyBuffer.cs b/src/runtime/PythonTypes/PyBuffer.cs index 120582494..71d3413d5 100644 --- a/src/runtime/PythonTypes/PyBuffer.cs +++ b/src/runtime/PythonTypes/PyBuffer.cs @@ -29,12 +29,14 @@ internal PyBuffer(PyObject exporter, PyBUF flags) Shape = intPtrBuf.Select(x => (long)x).ToArray(); } - if (_view.strides != IntPtr.Zero) { + if (_view.strides != IntPtr.Zero) + { Marshal.Copy(_view.strides, intPtrBuf, 0, _view.ndim); Strides = intPtrBuf.Select(x => (long)x).ToArray(); } - if (_view.suboffsets != IntPtr.Zero) { + if (_view.suboffsets != IntPtr.Zero) + { Marshal.Copy(_view.suboffsets, intPtrBuf, 0, _view.ndim); SubOffsets = intPtrBuf.Select(x => (long)x).ToArray(); } @@ -87,7 +89,7 @@ private static char OrderStyleToChar(BufferOrderStyle order, bool eitherOneValid /// public static long SizeFromFormat(string format) { - if (Runtime.PyVersion < new Version(3,9)) + if (Runtime.PyVersion < new Version(3, 9)) throw new NotSupportedException("SizeFromFormat requires at least Python 3.9"); nint result = Runtime.PyBuffer_SizeFromFormat(format); if (result == -1) throw PythonException.ThrowLastAsClrException(); @@ -206,7 +208,8 @@ public void Write(byte[] buffer, int sourceOffset, int count, nint destinationOf /// /// Reads the buffer of a python object into a managed byte array. This can be used to pass data like images from python to managed. /// - public void Read(byte[] buffer, int destinationOffset, int count, nint sourceOffset) { + public void Read(byte[] buffer, int destinationOffset, int count, nint sourceOffset) + { if (disposedValue) throw new ObjectDisposedException(nameof(PyBuffer)); if (_view.ndim != 1) diff --git a/src/runtime/PythonTypes/PyFloat.cs b/src/runtime/PythonTypes/PyFloat.cs index 50621d5c2..8f6915cde 100644 --- a/src/runtime/PythonTypes/PyFloat.cs +++ b/src/runtime/PythonTypes/PyFloat.cs @@ -103,5 +103,10 @@ public static PyFloat AsFloat(PyObject value) public double ToDouble() => Runtime.PyFloat_AsDouble(obj); public override TypeCode GetTypeCode() => TypeCode.Double; + + public override int GetHashCode() + { + throw new NotImplementedException(); + } } } diff --git a/src/runtime/PythonTypes/PyInt.cs b/src/runtime/PythonTypes/PyInt.cs index 0d00f5a13..b85949510 100644 --- a/src/runtime/PythonTypes/PyInt.cs +++ b/src/runtime/PythonTypes/PyInt.cs @@ -232,5 +232,10 @@ public string ToString(string format, IFormatProvider formatProvider) } public override TypeCode GetTypeCode() => TypeCode.Int64; + + public override int GetHashCode() + { + throw new NotImplementedException(); + } } } diff --git a/src/runtime/PythonTypes/PyIter.cs b/src/runtime/PythonTypes/PyIter.cs index f9847b11c..02fd3de80 100644 --- a/src/runtime/PythonTypes/PyIter.cs +++ b/src/runtime/PythonTypes/PyIter.cs @@ -31,7 +31,8 @@ internal PyIter(in StolenReference reference) : base(reference) /// The object must support iterator protocol. /// public PyIter(PyObject pyObject) : base(FromPyObject(pyObject)) { } - static BorrowedReference FromPyObject(PyObject pyObject) { + static BorrowedReference FromPyObject(PyObject pyObject) + { if (pyObject is null) throw new ArgumentNullException(nameof(pyObject)); if (!Runtime.PyIter_Check(pyObject.Reference)) diff --git a/src/runtime/PythonTypes/PyModule.cs b/src/runtime/PythonTypes/PyModule.cs index 243f77ecc..d921d2daa 100644 --- a/src/runtime/PythonTypes/PyModule.cs +++ b/src/runtime/PythonTypes/PyModule.cs @@ -1,7 +1,7 @@ using System; -using System.Linq; using System.Collections.Generic; using System.Dynamic; +using System.Linq; using System.Runtime.Serialization; namespace Python.Runtime diff --git a/src/runtime/PythonTypes/PyObject.IConvertible.cs b/src/runtime/PythonTypes/PyObject.IConvertible.cs index 503d3cab4..050d4df3d 100644 --- a/src/runtime/PythonTypes/PyObject.IConvertible.cs +++ b/src/runtime/PythonTypes/PyObject.IConvertible.cs @@ -50,4 +50,4 @@ public object ToType(Type conversionType, IFormatProvider provider) } } -} \ No newline at end of file +} diff --git a/src/runtime/PythonTypes/PyObject.cs b/src/runtime/PythonTypes/PyObject.cs index cf0c2a03f..123c4d4e3 100644 --- a/src/runtime/PythonTypes/PyObject.cs +++ b/src/runtime/PythonTypes/PyObject.cs @@ -30,10 +30,10 @@ public partial class PyObject : DynamicObject, IDisposable, ISerializable protected IntPtr rawPtr = IntPtr.Zero; internal readonly int run = Runtime.GetRun(); - internal BorrowedReference obj => new (rawPtr); + internal BorrowedReference obj => new(rawPtr); - public static PyObject None => new (Runtime.PyNone); - internal BorrowedReference Reference => new (rawPtr); + public static PyObject None => new(Runtime.PyNone); + internal BorrowedReference Reference => new(rawPtr); /// /// PyObject Constructor @@ -235,7 +235,7 @@ public void Dispose() { GC.SuppressFinalize(this); Dispose(true); - + } internal StolenReference Steal() diff --git a/src/runtime/Resources/clr.py b/src/runtime/Resources/clr.py index d4330a4d5..c55a060ad 100644 --- a/src/runtime/Resources/clr.py +++ b/src/runtime/Resources/clr.py @@ -28,9 +28,7 @@ def __init__(self, type_, fget=None, fset=None): self.fset = fset def __call__(self, fget): - return self.__class__(self._clr_property_type_, - fget=fget, - fset=self.fset) + return self.__class__(self._clr_property_type_, fget=fget, fset=self.fset) def setter(self, fset): self.fset = fset @@ -75,10 +73,12 @@ def __init__(self, return_type, arg_types, clrname=None, func=None): self.__func = func def __call__(self, func): - return self.__class__(self._clr_return_type_, - self._clr_arg_types_, - clrname=self._clr_method_name_, - func=func) + return self.__class__( + self._clr_return_type_, + self._clr_arg_types_, + clrname=self._clr_method_name_, + func=func, + ) def __get__(self, instance, owner): return self.__func.__get__(instance, owner) diff --git a/src/runtime/Resources/interop.py b/src/runtime/Resources/interop.py index a47d16c68..a5e4c2758 100644 --- a/src/runtime/Resources/interop.py +++ b/src/runtime/Resources/interop.py @@ -1,10 +1,11 @@ _UNSET = object() + class PyErr: def __init__(self, type=_UNSET, value=_UNSET, traceback=_UNSET): - if not(type is _UNSET): + if type is not _UNSET: self.type = type - if not(value is _UNSET): + if value is not _UNSET: self.value = value - if not(traceback is _UNSET): + if traceback is not _UNSET: self.traceback = traceback diff --git a/src/runtime/Runtime.cs b/src/runtime/Runtime.cs index 4e1c6156a..23846c4e4 100644 --- a/src/runtime/Runtime.cs +++ b/src/runtime/Runtime.cs @@ -1,12 +1,14 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; +using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; -using System.Collections.Generic; + using Python.Runtime.Native; -using System.Linq; + using static System.FormattableString; namespace Python.Runtime @@ -72,7 +74,7 @@ private static string GetDefaultDllName(Version version) public static int MainManagedThreadId { get; private set; } - private static readonly List _pyRefs = new (); + private static readonly List _pyRefs = new(); internal static Version PyVersion { @@ -564,7 +566,7 @@ internal static void CheckExceptionOccurred() if (mt is ClassBase b) { var _type = b.type; - t = _type.Valid ? _type.Value : null; + t = _type.Valid ? _type.Value : null; } else if (mt is CLRObject ob) { @@ -671,7 +673,7 @@ internal static T TryUsingDll(Func op) /// /// PyObject Ptr - internal static void Py_DecRef(StolenReference ob) => Delegates.Py_DecRef(ob); + internal static void Py_DecRef(StolenReference ob) => Delegates.Py_DecRef(ob.AnalyzerWorkaround()); internal static void Py_Initialize() => Delegates.Py_Initialize(); @@ -799,6 +801,10 @@ internal static int PyRun_SimpleString(string code) return Delegates.PyRun_SimpleStringFlags(codePtr, Utf8String); } + // NoCopy05 is the "return of noncopyable" warning. Since we do this in + // all `NewReference` returning functions in here, we disable it. +#pragma warning disable NoCopy05 + internal static NewReference PyRun_String(string code, RunFlagType st, BorrowedReference globals, BorrowedReference locals) { using var codePtr = new StrPtr(code, Encoding.UTF8); @@ -1252,7 +1258,7 @@ internal static bool PyString_CheckExact(BorrowedReference ob) internal static NewReference PyString_FromString(string value) { - fixed(char* ptr = value) + fixed (char* ptr = value) return Delegates.PyUnicode_DecodeUTF16( (IntPtr)ptr, value.Length * sizeof(Char), @@ -1449,7 +1455,7 @@ internal static bool PyList_Check(BorrowedReference ob) internal static BorrowedReference PyList_GetItem(BorrowedReference pointer, nint index) => Delegates.PyList_GetItem(pointer, index); - internal static int PyList_SetItem(BorrowedReference pointer, nint index, StolenReference value) => Delegates.PyList_SetItem(pointer, index, value); + internal static int PyList_SetItem(BorrowedReference pointer, nint index, StolenReference value) => Delegates.PyList_SetItem(pointer, index, value.AnalyzerWorkaround()); internal static int PyList_Insert(BorrowedReference pointer, nint index, BorrowedReference value) => Delegates.PyList_Insert(pointer, index, value); @@ -1487,7 +1493,7 @@ internal static int PyTuple_SetItem(BorrowedReference pointer, nint index, Borro return PyTuple_SetItem(pointer, index, newRef.Steal()); } - internal static int PyTuple_SetItem(BorrowedReference pointer, nint index, StolenReference value) => Delegates.PyTuple_SetItem(pointer, index, value); + internal static int PyTuple_SetItem(BorrowedReference pointer, nint index, StolenReference value) => Delegates.PyTuple_SetItem(pointer, index, value.AnalyzerWorkaround()); internal static NewReference PyTuple_GetSlice(BorrowedReference pointer, nint start, nint end) => Delegates.PyTuple_GetSlice(pointer, start, end); @@ -1647,7 +1653,7 @@ internal static bool PyType_IsSameAsOrSubtype(BorrowedReference type, BorrowedRe internal static NewReference PyObject_GenericGetDict(BorrowedReference o) => PyObject_GenericGetDict(o, IntPtr.Zero); internal static NewReference PyObject_GenericGetDict(BorrowedReference o, IntPtr context) => Delegates.PyObject_GenericGetDict(o, context); - internal static void PyObject_GC_Del(StolenReference ob) => Delegates.PyObject_GC_Del(ob); + internal static void PyObject_GC_Del(StolenReference ob) => Delegates.PyObject_GC_Del(ob.AnalyzerWorkaround()); internal static bool PyObject_GC_IsTracked(BorrowedReference ob) @@ -1710,7 +1716,7 @@ internal static void PyErr_SetString(BorrowedReference ob, string message) internal static void PyErr_Fetch(out NewReference type, out NewReference val, out NewReference tb) => Delegates.PyErr_Fetch(out type, out val, out tb); - internal static void PyErr_Restore(StolenReference type, StolenReference val, StolenReference tb) => Delegates.PyErr_Restore(type, val, tb); + internal static void PyErr_Restore(StolenReference type, StolenReference val, StolenReference tb) => Delegates.PyErr_Restore(type.AnalyzerWorkaround(), val.AnalyzerWorkaround(), tb.AnalyzerWorkaround()); internal static void PyErr_Clear() => Delegates.PyErr_Clear(); @@ -1728,7 +1734,7 @@ internal static NewReference PyException_GetTraceback(BorrowedReference ex) /// Set the cause associated with the exception to cause. Use NULL to clear it. There is no type check to make sure that cause is either an exception instance or None. This steals a reference to cause. /// internal static void PyException_SetCause(BorrowedReference ex, StolenReference cause) - => Delegates.PyException_SetCause(ex, cause); + => Delegates.PyException_SetCause(ex, cause.AnalyzerWorkaround()); internal static int PyException_SetTraceback(BorrowedReference ex, BorrowedReference tb) => Delegates.PyException_SetTraceback(ex, tb); @@ -1745,7 +1751,7 @@ internal static int PyException_SetTraceback(BorrowedReference ex, BorrowedRefer internal static nint PyGC_Collect() => Delegates.PyGC_Collect(); internal static void Py_CLEAR(BorrowedReference ob, int offset) => ReplaceReference(ob, offset, default); internal static void Py_CLEAR(ref T? ob) - where T: PyObject + where T : PyObject { ob?.Dispose(); ob = null; @@ -1793,6 +1799,8 @@ internal static void SetNoSiteFlag() } } +#pragma warning restore NoCopy05 + internal class BadPythonDllException : MissingMethodException { public BadPythonDllException(string message, Exception innerException) diff --git a/src/runtime/StateSerialization/MaybeMemberInfo.cs b/src/runtime/StateSerialization/MaybeMemberInfo.cs index b734bb070..832c4d060 100644 --- a/src/runtime/StateSerialization/MaybeMemberInfo.cs +++ b/src/runtime/StateSerialization/MaybeMemberInfo.cs @@ -21,7 +21,7 @@ public string DeletedMessage { get { - return $"The .NET {typeof(T).Name} {Description} no longer exists. Cause: " + deserializationException?.Message ; + return $"The .NET {typeof(T).Name} {Description} no longer exists. Cause: " + deserializationException?.Message; } } diff --git a/src/runtime/StateSerialization/MaybeMethodBase.cs b/src/runtime/StateSerialization/MaybeMethodBase.cs index d196d5e88..b173994f7 100644 --- a/src/runtime/StateSerialization/MaybeMethodBase.cs +++ b/src/runtime/StateSerialization/MaybeMethodBase.cs @@ -1,16 +1,16 @@ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Reflection; using System.Runtime.Serialization; -using System.Linq; using Python.Runtime.Reflection; namespace Python.Runtime { [Serializable] - internal struct MaybeMethodBase : ISerializable where T: MethodBase + internal struct MaybeMethodBase : ISerializable where T : MethodBase { // .ToString() of the serialized object const string SerializationName = "s"; @@ -22,7 +22,7 @@ internal struct MaybeMethodBase : ISerializable where T: MethodBase const string SerializationGenericParamCount = "G"; const string SerializationFlags = "V"; - public static implicit operator MaybeMethodBase (T? ob) => new (ob); + public static implicit operator MaybeMethodBase(T? ob) => new(ob); readonly string? name; readonly MethodBase? info; @@ -30,11 +30,11 @@ internal struct MaybeMethodBase : ISerializable where T: MethodBase [NonSerialized] readonly Exception? deserializationException; - public string DeletedMessage + public string DeletedMessage { get { - return $"The .NET {typeof(T)} {name} no longer exists. Cause: " + deserializationException?.Message ; + return $"The .NET {typeof(T)} {name} no longer exists. Cause: " + deserializationException?.Message; } } diff --git a/src/runtime/StateSerialization/MaybeType.cs b/src/runtime/StateSerialization/MaybeType.cs index 884b7edb0..c75a38875 100644 --- a/src/runtime/StateSerialization/MaybeType.cs +++ b/src/runtime/StateSerialization/MaybeType.cs @@ -1,15 +1,15 @@ using System; +using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; -using System.IO; namespace Python.Runtime { [Serializable] internal struct MaybeType : ISerializable { - public static implicit operator MaybeType (Type ob) => new(ob); + public static implicit operator MaybeType(Type ob) => new(ob); // The AssemblyQualifiedName of the serialized Type const string SerializationName = "n"; @@ -53,7 +53,7 @@ public MaybeType(Type tp) private MaybeType(SerializationInfo serializationInfo, StreamingContext context) { name = (string)serializationInfo.GetValue(SerializationName, typeof(string)); - type = Type.GetType(name, throwOnError:false); + type = Type.GetType(name, throwOnError: false); } public void GetObjectData(SerializationInfo serializationInfo, StreamingContext context) diff --git a/src/runtime/StateSerialization/RuntimeData.cs b/src/runtime/StateSerialization/RuntimeData.cs index 204e15b5b..a7a3163d1 100644 --- a/src/runtime/StateSerialization/RuntimeData.cs +++ b/src/runtime/StateSerialization/RuntimeData.cs @@ -36,7 +36,7 @@ public static Type? FormatterType /// /// Clears the old "clr_data" entry if a previous one is present. /// - static void ClearCLRData () + static void ClearCLRData() { BorrowedReference capsule = PySys_GetObject("clr_data"); if (!capsule.IsNull) @@ -123,7 +123,7 @@ public static void ClearStash() PySys_SetObject("clr_data", default); } - static bool CheckSerializable (object o) + static bool CheckSerializable(object o) { Type type = o.GetType(); do diff --git a/src/runtime/TypeManager.cs b/src/runtime/TypeManager.cs index 559d5148e..3a0047f6d 100644 --- a/src/runtime/TypeManager.cs +++ b/src/runtime/TypeManager.cs @@ -1,9 +1,10 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; -using System.Diagnostics; + using Python.Runtime.Native; using Python.Runtime.StateSerialization; diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 592eefd55..d136418f7 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -165,7 +165,7 @@ internal static Type CreateDerivedType(string name, Type baseClass = baseType; var interfaces = new HashSet { typeof(IPythonDerivedType) }; - foreach(var interfaceType in typeInterfaces) + foreach (var interfaceType in typeInterfaces) interfaces.Add(interfaceType); // if the base type is an interface then use System.Object as the base class diff --git a/src/runtime/Types/ClrModule.cs b/src/runtime/Types/ClrModule.cs index b7d10260c..3c23fbb57 100644 --- a/src/runtime/Types/ClrModule.cs +++ b/src/runtime/Types/ClrModule.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.IO; +using System.Linq; using System.Reflection; namespace Python.Runtime @@ -123,7 +123,7 @@ public static Assembly AddReference(string name) // method because it may be called from other threads, leading to deadlocks // if it is called while Python code is executing. var currNs = AssemblyManager.GetNamespaces().Except(origNs); - foreach(var ns in currNs) + foreach (var ns in currNs) { ImportHook.AddNamespaceWithGIL(ns); } diff --git a/src/runtime/Types/ExtensionType.cs b/src/runtime/Types/ExtensionType.cs index 305fdc15d..ee44facd2 100644 --- a/src/runtime/Types/ExtensionType.cs +++ b/src/runtime/Types/ExtensionType.cs @@ -44,7 +44,7 @@ public virtual NewReference Alloc() // "borrowed" references internal static readonly HashSet loadedExtensions = new(); - void SetupGc (BorrowedReference ob, BorrowedReference tp) + void SetupGc(BorrowedReference ob, BorrowedReference tp) { GCHandle gc = GCHandle.Alloc(this); InitGCHandle(ob, tp, gc); diff --git a/src/runtime/Types/Iterator.cs b/src/runtime/Types/Iterator.cs index 49145d2c3..db76b5491 100644 --- a/src/runtime/Types/Iterator.cs +++ b/src/runtime/Types/Iterator.cs @@ -46,6 +46,8 @@ public static NewReference tp_iternext(BorrowedReference ob) return Converter.ToPython(item, self.elemType); } - public static NewReference tp_iter(BorrowedReference ob) => new (ob); +#pragma warning disable NoCopy05, NoCopy06 + public static NewReference tp_iter(BorrowedReference ob) => new(ob); +#pragma warning restore } } diff --git a/src/runtime/Types/ManagedType.cs b/src/runtime/Types/ManagedType.cs index 97a19497c..599440b50 100644 --- a/src/runtime/Types/ManagedType.cs +++ b/src/runtime/Types/ManagedType.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; using System.Linq; +using System.Runtime.InteropServices; namespace Python.Runtime { @@ -83,8 +83,8 @@ internal static unsafe void DecrefTypeAndFree(StolenReference ob) var freePtr = Util.ReadIntPtr(type, TypeOffset.tp_free); Debug.Assert(freePtr != IntPtr.Zero); - var free = (delegate* unmanaged[Cdecl])freePtr; - free(ob); + var free = (delegate* unmanaged[Cdecl])freePtr; + free(ob.DangerousGetAddress()); Runtime.XDecref(StolenReference.DangerousFromPointer(type.DangerousGetAddress())); } @@ -261,7 +261,7 @@ static Offsets() tp_clr_inst = tp_clr_inst_offset + IntPtr.Size; } public static int tp_clr_inst_offset { get; } - public static int tp_clr_inst { get; } + public static int tp_clr_inst { get; } } } } diff --git a/src/runtime/Types/MethodObject.cs b/src/runtime/Types/MethodObject.cs index 12484d301..42fcd002e 100644 --- a/src/runtime/Types/MethodObject.cs +++ b/src/runtime/Types/MethodObject.cs @@ -113,7 +113,8 @@ internal NewReference GetDocString() internal NewReference GetName() { var names = new HashSet(binder.GetMethods().Select(m => m.Name)); - if (names.Count != 1) { + if (names.Count != 1) + { Exceptions.SetError(Exceptions.AttributeError, "a method has no name"); return default; } diff --git a/src/runtime/Types/ModuleObject.cs b/src/runtime/Types/ModuleObject.cs index f641b393e..764a03f8b 100644 --- a/src/runtime/Types/ModuleObject.cs +++ b/src/runtime/Types/ModuleObject.cs @@ -18,12 +18,12 @@ internal class ModuleObject : ExtensionType internal string moduleName; internal PyDict dict; protected string _namespace; - private readonly PyList __all__ = new (); + private readonly PyList __all__ = new(); // Attributes to be set on the module according to PEP302 and 451 // by the import machinery. static readonly HashSet settableAttributes = - new () {"__spec__", "__file__", "__name__", "__path__", "__loader__", "__package__"}; + new() { "__spec__", "__file__", "__name__", "__path__", "__loader__", "__package__" }; #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. /// is initialized in @@ -364,7 +364,7 @@ public static int tp_traverse(BorrowedReference ob, IntPtr visit, IntPtr arg) { var managedKey = Runtime.GetManagedString(key); if ((settableAttributes.Contains(managedKey)) || - (ManagedType.GetManagedObject(val) is ModuleObject) ) + (ManagedType.GetManagedObject(val) is ModuleObject)) { var self = (ModuleObject)ManagedType.GetManagedObject(ob)!; return Runtime.PyDict_SetItem(self.dict, key, val); diff --git a/src/runtime/Types/OperatorMethod.cs b/src/runtime/Types/OperatorMethod.cs index a2ca73982..acdfa877a 100644 --- a/src/runtime/Types/OperatorMethod.cs +++ b/src/runtime/Types/OperatorMethod.cs @@ -142,7 +142,8 @@ public static string GetPyMethodName(string clrName) if (OpMethodMap.ContainsKey(clrName)) { return OpMethodMap[clrName].MethodName; - } else + } + else { return ComparisonOpMap[clrName]; } diff --git a/src/runtime/Util/EventHandlerCollection.cs b/src/runtime/Util/EventHandlerCollection.cs index 0cd03d0fd..992f7d064 100644 --- a/src/runtime/Util/EventHandlerCollection.cs +++ b/src/runtime/Util/EventHandlerCollection.cs @@ -7,7 +7,7 @@ namespace Python.Runtime; [Serializable] -internal class EventHandlerCollection: Dictionary> +internal class EventHandlerCollection : Dictionary> { readonly EventInfo info; public EventHandlerCollection(EventInfo @event) diff --git a/src/runtime/Util/GenericUtil.cs b/src/runtime/Util/GenericUtil.cs index 907a3a616..498707305 100644 --- a/src/runtime/Util/GenericUtil.cs +++ b/src/runtime/Util/GenericUtil.cs @@ -1,6 +1,6 @@ -using System.Linq; using System; using System.Collections.Generic; +using System.Linq; using System.Resources; namespace Python.Runtime diff --git a/src/runtime/Util/NonCopyableAttribute.cs b/src/runtime/Util/NonCopyableAttribute.cs index 63d36ab42..c73edbd4c 100644 --- a/src/runtime/Util/NonCopyableAttribute.cs +++ b/src/runtime/Util/NonCopyableAttribute.cs @@ -1,6 +1,6 @@ namespace Python.Runtime { - using System; + using System; [AttributeUsage(AttributeTargets.Struct)] class NonCopyableAttribute : Attribute { } } diff --git a/src/runtime/Util/OpsHelper.cs b/src/runtime/Util/OpsHelper.cs index 7c35f27eb..04a65b0ee 100644 --- a/src/runtime/Util/OpsHelper.cs +++ b/src/runtime/Util/OpsHelper.cs @@ -35,7 +35,7 @@ public static Expression EnumUnderlyingValue(Expression enumValue) } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - internal class OpsAttribute: Attribute { } + internal class OpsAttribute : Attribute { } [Ops] internal static class FlagEnumOps where T : Enum diff --git a/src/runtime/Util/ReflectionPolyfills.cs b/src/runtime/Util/ReflectionPolyfills.cs index b33698509..a400f3973 100644 --- a/src/runtime/Util/ReflectionPolyfills.cs +++ b/src/runtime/Util/ReflectionPolyfills.cs @@ -17,14 +17,14 @@ public static Type CreateType(this TypeBuilder typeBuilder) return typeBuilder.CreateTypeInfo(); } - public static T GetCustomAttribute(this Type type) where T: Attribute + public static T GetCustomAttribute(this Type type) where T : Attribute { return type.GetCustomAttributes(typeof(T), inherit: false) .Cast() .SingleOrDefault(); } - public static T GetCustomAttribute(this Assembly assembly) where T: Attribute + public static T GetCustomAttribute(this Assembly assembly) where T : Attribute { return assembly.GetCustomAttributes(typeof(T), inherit: false) .Cast() diff --git a/src/runtime/Util/Util.cs b/src/runtime/Util/Util.cs index 2429c460b..6b39f881b 100644 --- a/src/runtime/Util/Util.cs +++ b/src/runtime/Util/Util.cs @@ -40,7 +40,7 @@ internal static long ReadInt64(BorrowedReference ob, int offset) [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static T* ReadPtr(BorrowedReference ob, int offset) - where T: unmanaged + where T : unmanaged { Debug.Assert(offset >= 0); IntPtr ptr = Marshal.ReadIntPtr(ob.DangerousGetAddress(), offset); @@ -151,7 +151,7 @@ internal static string ReadStringResource(this System.Reflection.Assembly assemb public static IEnumerator GetEnumerator(this IEnumerator enumerator) => enumerator; public static IEnumerable WhereNotNull(this IEnumerable source) - where T: class + where T : class { foreach (var item in source) { diff --git a/src/testing/CodecTest.cs b/src/testing/CodecTest.cs index f3c243dab..6f710741e 100644 --- a/src/testing/CodecTest.cs +++ b/src/testing/CodecTest.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; + using Python.Runtime; namespace Python.Test diff --git a/src/testing/conversiontest.cs b/src/testing/conversiontest.cs index 272bb74c2..e8c7fba5b 100644 --- a/src/testing/conversiontest.cs +++ b/src/testing/conversiontest.cs @@ -39,7 +39,8 @@ public ConversionTest() public sbyte[] SByteArrayField; public readonly List ListField = new List(); - public T? Echo(T? arg) where T: struct { + public T? Echo(T? arg) where T : struct + { return arg; } diff --git a/src/testing/eventtest.cs b/src/testing/eventtest.cs index c9573f71a..9440b473d 100644 --- a/src/testing/eventtest.cs +++ b/src/testing/eventtest.cs @@ -7,7 +7,7 @@ namespace Python.Test /// public delegate void EventHandlerTest(object sender, EventArgsTest e); - #pragma warning disable 67 // Unused events, these are only accessed from Python +#pragma warning disable 67 // Unused events, these are only accessed from Python public class EventTest { public static event EventHandlerTest PublicStaticEvent; @@ -145,7 +145,7 @@ public static void ShutUpCompiler() e.PrivateEvent += f; } } - #pragma warning restore 67 +#pragma warning restore 67 public class EventArgsTest : EventArgs diff --git a/src/testing/exceptiontest.cs b/src/testing/exceptiontest.cs index 0b72e0014..903f06732 100644 --- a/src/testing/exceptiontest.cs +++ b/src/testing/exceptiontest.cs @@ -1,8 +1,9 @@ -using Python.Runtime; using System; using System.Collections; using System.Collections.Generic; +using Python.Runtime; + namespace Python.Test { /// @@ -82,14 +83,14 @@ public static void ThrowChainedExceptions() throw new Exception("Outer exception", exc2); } } - + public static IntPtr DoThrowSimple() { using (Py.GIL()) { dynamic builtins = Py.Import("builtins"); var typeErrorType = new PyType(builtins.TypeError); - var pyerr = new PythonException(typeErrorType, value:null, traceback:null, "Type error, the first", innerException:null); + var pyerr = new PythonException(typeErrorType, value: null, traceback: null, "Type error, the first", innerException: null); throw new ArgumentException("Bogus bad parameter", pyerr); } @@ -97,21 +98,21 @@ public static IntPtr DoThrowSimple() public static void DoThrowWithInner() { - using(Py.GIL()) + using (Py.GIL()) { // create a TypeError dynamic builtins = Py.Import("builtins"); - var pyerrFirst = new PythonException(new PyType(builtins.TypeError), value:null, traceback:null, "Type error, the first", innerException:null); + var pyerrFirst = new PythonException(new PyType(builtins.TypeError), value: null, traceback: null, "Type error, the first", innerException: null); // Create an ArgumentException, but as a python exception, with the previous type error as the inner exception var argExc = new ArgumentException("Bogus bad parameter", pyerrFirst); var argExcPyObj = argExc.ToPython(); - var pyArgExc = new PythonException(argExcPyObj.GetPythonType(), value:null, traceback:null, argExc.Message, innerException:argExc.InnerException); + var pyArgExc = new PythonException(argExcPyObj.GetPythonType(), value: null, traceback: null, argExc.Message, innerException: argExc.InnerException); // This object must be disposed explicitly or else we get a false-positive leak. argExcPyObj.Dispose(); - + // Then throw a TypeError with the ArgumentException-as-python-error exception as inner. - var pyerrSecond = new PythonException(new PyType(builtins.TypeError), value:null, traceback:null, "Type error, the second", innerException:pyArgExc); + var pyerrSecond = new PythonException(new PyType(builtins.TypeError), value: null, traceback: null, "Type error, the second", innerException: pyArgExc); throw pyerrSecond; } diff --git a/src/testing/generictest.cs b/src/testing/generictest.cs index b333910c2..3aae263c5 100644 --- a/src/testing/generictest.cs +++ b/src/testing/generictest.cs @@ -36,7 +36,7 @@ public DerivedFromOpenGeneric(int arg1, V arg2, W arg3) : base(arg1, arg2) } public class GenericTypeWithConstraint - where T: struct + where T : struct { } public class GenericNameTest1 diff --git a/src/testing/indexertest.cs b/src/testing/indexertest.cs index 08e6ad053..a3389ff9a 100644 --- a/src/testing/indexertest.cs +++ b/src/testing/indexertest.cs @@ -427,7 +427,7 @@ public interface IIndexer public interface IInheritedIndexer : IIndexer { } - public class InterfaceInheritedIndexerTest : IndexerBase, IInheritedIndexer + public class InterfaceInheritedIndexerTest : IndexerBase, IInheritedIndexer { private System.Collections.Generic.IDictionary d = new System.Collections.Generic.Dictionary(); diff --git a/src/testing/interfacetest.cs b/src/testing/interfacetest.cs index a1a7106b5..39d26dfa8 100644 --- a/src/testing/interfacetest.cs +++ b/src/testing/interfacetest.cs @@ -58,7 +58,7 @@ public ISayHello1 GetNoSayHello(out ISayHello2 hello2) return null; } - public ISayHello1 [] GetISayHello1Array() + public ISayHello1[] GetISayHello1Array() { return new[] { this }; } diff --git a/src/testing/methodtest.cs b/src/testing/methodtest.cs index ec05fef72..cbdb2e182 100644 --- a/src/testing/methodtest.cs +++ b/src/testing/methodtest.cs @@ -652,7 +652,7 @@ public static int Overloaded(int i, string s) } public virtual void OverloadedConstrainedGeneric(T generic) where T : MethodTest { } - public virtual void OverloadedConstrainedGeneric(T generic, string str) where T: MethodTest { } + public virtual void OverloadedConstrainedGeneric(T generic, string str) where T : MethodTest { } public static string CaseSensitive() { diff --git a/src/testing/mp_lengthtest.cs b/src/testing/mp_lengthtest.cs index a4f3e8c25..b2525174b 100644 --- a/src/testing/mp_lengthtest.cs +++ b/src/testing/mp_lengthtest.cs @@ -71,7 +71,8 @@ public class MpLengthGenericCollectionTest : ICollection { private readonly List items; - public MpLengthGenericCollectionTest() { + public MpLengthGenericCollectionTest() + { SyncRoot = new object(); items = new List(); } diff --git a/src/testing/threadtest.cs b/src/testing/threadtest.cs index 3c137df4e..9e7fe320b 100644 --- a/src/testing/threadtest.cs +++ b/src/testing/threadtest.cs @@ -1,4 +1,5 @@ using System; + using Python.Runtime; namespace Python.Test diff --git a/tests/_missing_import.py b/tests/_missing_import.py index a104cda49..633f86615 100644 --- a/tests/_missing_import.py +++ b/tests/_missing_import.py @@ -1,3 +1,2 @@ # -*- coding: utf-8 -*- -import this_package_should_never_exist_ever diff --git a/tests/conftest.py b/tests/conftest.py index 1ac20e1dd..6c348fdb2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -80,6 +80,7 @@ def pytest_configure(config): ) import os + os.environ["PYTHONNET_RUNTIME"] = runtime_opt for k, v in runtime_params.items(): os.environ[f"PYTHONNET_{runtime_opt.upper()}_{k.upper()}"] = v diff --git a/tests/domain_tests/TestRunner.cs b/tests/domain_tests/TestRunner.cs index 4f6a3ea28..05ef59f5a 100644 --- a/tests/domain_tests/TestRunner.cs +++ b/tests/domain_tests/TestRunner.cs @@ -1,11 +1,12 @@ // We can't refer to or use Python.Runtime here. // We want it to be loaded only inside the subdomains using System; -using Microsoft.CSharp; using System.CodeDom.Compiler; using System.IO; using System.Linq; +using Microsoft.CSharp; + namespace Python.DomainReloadTests { /// @@ -110,7 +111,7 @@ assert sys.my_cls is not None ", }, - new TestCase + new TestCase { Name = "static_member_rename", DotNetBefore = @" @@ -165,7 +166,7 @@ assert sys.my_fn is not None }, - new TestCase + new TestCase { Name = "member_rename", DotNetBefore = @" @@ -1209,7 +1210,7 @@ static void Run(TestCase testCase) CreatePythonModule(testCase); { - var runnerAssembly = CreateCaseRunnerAssembly(verb:"before"); + var runnerAssembly = CreateCaseRunnerAssembly(verb: "before"); CreateTestClassAssembly(testCase.DotNetBefore); { var runnerDomain = CreateDomain("case runner before"); @@ -1222,7 +1223,7 @@ static void Run(TestCase testCase) } { - var runnerAssembly = CreateCaseRunnerAssembly(verb:"after"); + var runnerAssembly = CreateCaseRunnerAssembly(verb: "after"); CreateTestClassAssembly(testCase.DotNetAfter); // Do it twice for good measure @@ -1311,8 +1312,8 @@ static string CreateAssembly(string name, string code, bool exe = false) parameters.ReferencedAssemblies.Add(netstandard); parameters.ReferencedAssemblies.Add(PythonDllLocation); // Write code to file so it can debugged. - var sourcePath = Path.Combine(TestPath, name+"_source.cs"); - using(var file = new StreamWriter(sourcePath)) + var sourcePath = Path.Combine(TestPath, name + "_source.cs"); + using (var file = new StreamWriter(sourcePath)) { file.Write(code); } diff --git a/tests/domain_tests/test_domain_reload.py b/tests/domain_tests/test_domain_reload.py index 8999e481b..b8b46c941 100644 --- a/tests/domain_tests/test_domain_reload.py +++ b/tests/domain_tests/test_domain_reload.py @@ -5,18 +5,21 @@ import pytest from find_libpython import find_libpython + libpython = find_libpython() -pytestmark = pytest.mark.xfail(libpython is None, reason="Can't find suitable libpython") +pytestmark = pytest.mark.xfail( + libpython is None, reason="Can't find suitable libpython" +) def _run_test(testname): dirname = os.path.split(__file__)[0] - exename = os.path.join(dirname, 'bin', 'Python.DomainReloadTests.exe') + exename = os.path.join(dirname, "bin", "Python.DomainReloadTests.exe") args = [exename, testname] - if platform.system() != 'Windows': - args = ['mono'] + args + if platform.system() != "Windows": + args = ["mono"] + args env = os.environ.copy() env["PYTHONNET_PYDLL"] = libpython @@ -26,65 +29,86 @@ def _run_test(testname): assert proc.returncode == 0 + def test_rename_class(): - _run_test('class_rename') + _run_test("class_rename") + def test_rename_class_member_static_function(): - _run_test('static_member_rename') + _run_test("static_member_rename") + def test_rename_class_member_function(): - _run_test('member_rename') + _run_test("member_rename") + def test_rename_class_member_field(): - _run_test('field_rename') + _run_test("field_rename") + def test_rename_class_member_property(): - _run_test('property_rename') + _run_test("property_rename") + def test_rename_namespace(): - _run_test('namespace_rename') + _run_test("namespace_rename") + def test_field_visibility_change(): _run_test("field_visibility_change") + def test_method_visibility_change(): _run_test("method_visibility_change") + def test_property_visibility_change(): _run_test("property_visibility_change") + def test_class_visibility_change(): _run_test("class_visibility_change") + def test_method_parameters_change(): _run_test("method_parameters_change") + def test_method_return_type_change(): _run_test("method_return_type_change") + def test_field_type_change(): _run_test("field_type_change") + def test_rename_event(): - _run_test('event_rename') + _run_test("event_rename") + def test_construct_removed_class(): _run_test("construct_removed_class") + def test_out_to_ref_param(): _run_test("out_to_ref_param") + def test_ref_to_out_param(): _run_test("ref_to_out_param") + def test_ref_to_in_param(): _run_test("ref_to_in_param") + def test_in_to_ref_param(): _run_test("in_to_ref_param") + def test_nested_type(): _run_test("nested_type") + def test_import_after_reload(): _run_test("import_after_reload") diff --git a/tests/fixtures/argv-fixture.py b/tests/fixtures/argv-fixture.py index d56dea4e0..11c854884 100644 --- a/tests/fixtures/argv-fixture.py +++ b/tests/fixtures/argv-fixture.py @@ -7,6 +7,5 @@ from __future__ import print_function import sys -import clr print(sys.argv) diff --git a/tests/importtest.py b/tests/importtest.py index fe93764e9..e8ca9d950 100644 --- a/tests/importtest.py +++ b/tests/importtest.py @@ -1,13 +1,13 @@ # -*- coding: utf-8 -*- import sys + try: del sys.modules["System.IO"] except KeyError: pass assert "FileStream" not in globals() -import System.IO -from System.IO import * +from System.IO import * # noqa assert "FileStream" in globals() diff --git a/tests/leaktest.py b/tests/leaktest.py index 02133fece..9f0a237ed 100644 --- a/tests/leaktest.py +++ b/tests/leaktest.py @@ -4,22 +4,28 @@ from __future__ import print_function -import clr import gc import sys import System -from .utils import (CallableHandler, ClassMethodHandler, GenericHandler, - HelloClass, StaticMethodHandler, VarCallableHandler, - VariableArgsHandler, hello_func) +from .utils import ( + CallableHandler, + ClassMethodHandler, + GenericHandler, + HelloClass, + StaticMethodHandler, + VarCallableHandler, + VariableArgsHandler, + hello_func, +) class LeakTest(object): """A leak-check test for the objects implemented in the managed - runtime. For each kind of object tested, memory should reach - a particular level after warming up and stay essentially the - same, net of minor fluctuation induced by GC.""" + runtime. For each kind of object tested, memory should reach + a particular level after warming up and stay essentially the + same, net of minor fluctuation induced by GC.""" def __init__(self): self.count = 50000 @@ -42,9 +48,9 @@ def end_test(self): end = System.Environment.WorkingSet diff = end - start if diff > 0: - diff = '+{0}'.format(diff) + diff = "+{0}".format(diff) else: - diff = '{0}'.format(diff) + diff = "{0}".format(diff) print(" start: {0} end: {1} diff: {2}".format(start, end, diff)) print("") @@ -69,11 +75,11 @@ def test_modules(self): if i == 10: self.start_test() - __import__('clr') - __import__('System') - __import__('System.IO') - __import__('System.Net') - __import__('System.Xml') + __import__("clr") + __import__("System") + __import__("System.IO") + __import__("System.Net") + __import__("System.Xml") self.end_test() @@ -202,10 +208,10 @@ def test_events(self): testob.PublicEvent -= EventTest.StaticHandler # Function event handler - dict_ = {'value': None} + dict_ = {"value": None} def handler(sender, args, dict_=dict_): - dict_['value'] = args.value + dict_["value"] = args.value testob.PublicEvent += handler testob.PublicEvent(testob, EventArgsTest(10)) @@ -326,7 +332,7 @@ def test_delegates(self): self.end_test() -if __name__ == '__main__': +if __name__ == "__main__": test = LeakTest() test.run() test.report() diff --git a/tests/profile.py b/tests/profile.py index 2113b1727..af6e38c33 100644 --- a/tests/profile.py +++ b/tests/profile.py @@ -3,7 +3,7 @@ # FIXME: FAIL: testImplicitAssemblyLoad AssertionError: 0 != 1 """Run all of the unit tests for this package over and over, - in order to provide for better profiling. +in order to provide for better profiling. """ from __future__ import print_function @@ -25,16 +25,16 @@ def main(): start = time.clock() for i in range(50): - print('iteration: {0:d}'.format(i)) + print("iteration: {0:d}".format(i)) runtests.main() stop = time.clock() took = str(stop - start) - print('Total Time: {0}'.format(took)) + print("Total Time: {0}".format(took)) for item in gc.get_objects(): print(item, sys.getrefcount(item)) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/tests/runtests.py b/tests/runtests.py index 9b90bcf6a..bcf0f7082 100644 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -9,7 +9,7 @@ import pytest try: - import System + import System # noqa: F401 except ImportError: print("Load clr import hook") import clr @@ -31,8 +31,8 @@ def main(verbosity=1): pytest.main() -if __name__ == '__main__': +if __name__ == "__main__": main() - if '--pause' in sys.argv: + if "--pause" in sys.argv: print("Press enter to continue") input() diff --git a/tests/stress.py b/tests/stress.py index f1f0fac6b..d9278226e 100644 --- a/tests/stress.py +++ b/tests/stress.py @@ -27,6 +27,7 @@ def __init__(self): sys.path.append(self.dirname) gc.set_debug(gc.DEBUG_LEAK) import runtests + self.module = runtests self.done = [] @@ -64,7 +65,7 @@ def stress_test(self, iterations=1, threads=1): dprint(len(self.done)) time.sleep(0.1) self.mark_finish() - took = self.elapsed() + # took = self.elapsed() self.print_gc_report() @@ -73,5 +74,5 @@ def main(): test.stress_test(2, 10) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/tests/stresstest.py b/tests/stresstest.py index b0dca9461..51af84e27 100644 --- a/tests/stresstest.py +++ b/tests/stresstest.py @@ -12,10 +12,11 @@ # import pdb try: - import System + import System # noqa: F401 except ImportError: print("Load clr import hook") import clr + clr.AddReference("Python.Test") clr.AddReference("System.Collections") clr.AddReference("System.Data") @@ -28,18 +29,18 @@ def main(): for i in range(2000): print(i) for name in ( - 'test_module', - 'test_conversion', + "test_module", + "test_conversion", # 'test_class', - 'test_interface', - 'test_enum', - 'test_field', - 'test_property', - 'test_indexer', - 'test_event', - 'test_method', + "test_interface", + "test_enum", + "test_field", + "test_property", + "test_indexer", + "test_event", + "test_method", # 'test_delegate', - 'test_array', + "test_array", ): module = __import__(name) unittest.TextTestRunner().run(module.test_suite()) @@ -48,11 +49,11 @@ def main(): stop = time.clock() took = str(stop - start) - print('Total Time: {0}'.format(took)) + print("Total Time: {0}".format(took)) for i in gc.get_objects(): print(i) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/tests/test_array.py b/tests/test_array.py index d207a36fb..aba2adefa 100644 --- a/tests/test_array.py +++ b/tests/test_array.py @@ -2,7 +2,6 @@ """Test support for managed arrays.""" -import clr import Python.Test as Test import System import pytest @@ -120,9 +119,13 @@ def test_array_contains(): assert 3 in items assert 4 in items - assert not (5 in items) # "H:\Python27\Lib\unittest\case.py", line 592, in deprecated_func, - assert not (-1 in items) # TypeError: int() argument must be a string or a number, not 'NoneType' - assert not (None in items) # which threw ^ here which is a little odd. + assert ( + 5 not in items + ) # "H:\Python27\Lib\unittest\case.py", line 592, in deprecated_func, + assert ( + -1 not in items + ) # TypeError: int() argument must be a string or a number, not 'NoneType' + assert None not in items # which threw ^ here which is a little odd. # But when run from runtests.py. Not when this module ran by itself. @@ -245,8 +248,8 @@ def test_char_array(): assert len(items) == 5 - assert items[0] == 'a' - assert items[4] == 'e' + assert items[0] == "a" + assert items[4] == "e" max_ = chr(65535) min_ = chr(0) @@ -598,6 +601,7 @@ def test_decimal_array(): items = ob.items from System import Decimal + max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") @@ -634,8 +638,8 @@ def test_string_array(): assert len(items) == 5 - assert items[0] == '0' - assert items[4] == '4' + assert items[0] == "0" + assert items[4] == "4" items[0] = "spam" assert items[0] == "spam" @@ -661,6 +665,7 @@ def test_string_array(): def test_enum_array(): """Test enum arrays.""" from Python.Test import ShortEnum + ob = Test.EnumArrayTest() items = ob.items @@ -697,6 +702,7 @@ def test_enum_array(): def test_object_array(): """Test ob arrays.""" from Python.Test import Spam + ob = Test.ObjectArrayTest() items = ob.items @@ -765,6 +771,7 @@ def test_null_array(): def test_interface_array(): """Test interface arrays.""" from Python.Test import Spam + ob = Test.InterfaceArrayTest() items = ob.items @@ -804,6 +811,7 @@ def test_interface_array(): def test_typed_array(): """Test typed arrays.""" from Python.Test import Spam + ob = Test.TypedArrayTest() items = ob.items @@ -847,6 +855,7 @@ def test_typed_array(): ob = Test.TypedArrayTest() ob.items[0.5] = Spam("0") + def test_multi_dimensional_array(): """Test multi-dimensional arrays.""" ob = Test.MultiDimensionalArrayTest() @@ -927,6 +936,7 @@ def test_multi_dimensional_array(): ob = Test.MultiDimensionalArrayTest() ob.items[0.5, 0] = 0 + def test_array_iteration(): """Test array iteration.""" items = Test.Int32ArrayTest().items @@ -942,7 +952,7 @@ def test_array_iteration(): empty = Test.NullArrayTest().empty for i in empty: - raise TypeError('iteration over empty array') + raise TypeError("iteration over empty array") def test_tuple_array_conversion(): @@ -1195,6 +1205,7 @@ def test_boxed_value_type_mutation_result(): assert items[i].X == i + 1 assert items[i].Y == i + 1 + def test_create_array_from_shape(): from System import Array @@ -1211,18 +1222,20 @@ def test_create_array_from_shape(): Array[int](-1) with pytest.raises(TypeError): - Array[int]('1') + Array[int]("1") with pytest.raises(ValueError): Array[int](-1, -1) with pytest.raises(TypeError): - Array[int]('1', '1') + Array[int]("1", "1") + def test_special_array_creation(): """Test using the Array[] syntax for creating arrays.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from System import Array + inst = InterfaceTest() value = Array[System.Boolean]([True, True]) @@ -1245,9 +1258,9 @@ def test_special_array_creation(): assert value[1] == 127 assert value.Length == 2 - value = Array[System.Char]([u'A', u'Z']) - assert value[0] == u'A' - assert value[1] == u'Z' + value = Array[System.Char](["A", "Z"]) + assert value[0] == "A" + assert value[1] == "Z" assert value.Length == 2 value = Array[System.Char]([0, 65535]) @@ -1372,10 +1385,10 @@ def test_array_abuse(): Test.PublicArrayTest.__setitem__(0, 0, 0) with pytest.raises(KeyError): - Test.PublicArrayTest.__dict__['__getitem__'] + Test.PublicArrayTest.__dict__["__getitem__"] with pytest.raises(KeyError): - Test.PublicArrayTest.__dict__['__setitem__'] + Test.PublicArrayTest.__dict__["__setitem__"] def test_iterator_to_array(): @@ -1404,4 +1417,3 @@ def test_dict_keys_to_array(): assert arr[0] == "a" assert arr[1] == "b" assert arr[2] == "c" - diff --git a/tests/test_callback.py b/tests/test_callback.py index f94a9d52e..6656ce828 100644 --- a/tests/test_callback.py +++ b/tests/test_callback.py @@ -3,7 +3,7 @@ """Test that callbacks from C# into python work.""" -def simpleDefaultArg(arg='test'): +def simpleDefaultArg(arg="test"): return arg diff --git a/tests/test_class.py b/tests/test_class.py index f63f05f4d..80e25c865 100644 --- a/tests/test_class.py +++ b/tests/test_class.py @@ -3,7 +3,6 @@ """Test CLR class support.""" -import clr import Python.Test as Test import System import pytest @@ -15,6 +14,7 @@ def test_basic_reference_type(): """Test usage of CLR defined reference types.""" assert System.String.Empty == "" + def test_basic_value_type(): """Test usage of CLR defined value types.""" assert System.Int32.MaxValue == 2147483647 @@ -24,16 +24,17 @@ def test_class_standard_attrs(): """Test standard class attributes.""" from Python.Test import ClassTest - assert ClassTest.__name__ == 'ClassTest' - assert ClassTest.__module__ == 'Python.Test' + assert ClassTest.__name__ == "ClassTest" + assert ClassTest.__module__ == "Python.Test" assert isinstance(ClassTest.__dict__, DictProxyType) assert len(ClassTest.__doc__) > 0 + def test_class_docstrings(): """Test standard class docstring generation""" from Python.Test import ClassTest - value = 'Void .ctor()' + value = "Void .ctor()" assert ClassTest.__doc__ == value @@ -52,15 +53,16 @@ def test_class_default_repr(): def test_non_public_class(): """Test that non-public classes are inaccessible.""" with pytest.raises(ImportError): - from Python.Test import InternalClass + pass with pytest.raises(AttributeError): _ = Test.InternalClass + def test_non_exported(): """Test [PyExport(false)]""" with pytest.raises(ImportError): - from Python.Test import NonExportable + pass with pytest.raises(AttributeError): _ = Test.NonExportable @@ -76,15 +78,15 @@ def how_many(self): table = MyTable() - assert table.__class__.__name__.endswith('MyTable') - assert type(table).__name__.endswith('MyTable') + assert table.__class__.__name__.endswith("MyTable") + assert type(table).__name__.endswith("MyTable") assert len(table.__class__.__bases__) == 1 assert table.__class__.__bases__[0] == Hashtable assert table.how_many() == 0 assert table.Count == 0 - table.set_Item('one', 'one') + table.set_Item("one", "one") assert table.how_many() == 1 assert table.Count == 1 @@ -99,7 +101,7 @@ def __init__(self, name): self.name = name # This failed in earlier versions - _ = SubClass('test') + _ = SubClass("test") def test_subclass_with_various_constructors(): @@ -111,18 +113,18 @@ def __init__(self, v): ClassCtorTest2.__init__(self, v) self.value2 = v - inst = SubClass('test') - assert inst.value == 'test' - assert inst.value2 == 'test' + inst = SubClass("test") + assert inst.value == "test" + assert inst.value2 == "test" class SubClass2(ClassCtorTest2): def __init__(self, v): ClassCtorTest2.__init__(self, v) self.value2 = v - inst = SubClass2('test') - assert inst.value == 'test' - assert inst.value2 == 'test' + inst = SubClass2("test") + assert inst.value == "test" + assert inst.value2 == "test" def test_struct_construction(): @@ -164,7 +166,7 @@ def test_ienumerable_iteration(): for item in dict_: cname = item.__class__.__name__ - assert cname.endswith('DictionaryEntry') + assert cname.endswith("DictionaryEntry") def test_ienumerator_iteration(): @@ -174,7 +176,8 @@ def test_ienumerator_iteration(): chars = ClassTest.GetEnumerator() for item in chars: - assert item in 'test string' + assert item in "test string" + def test_iterable(): """Test what objects are Iterable""" @@ -184,8 +187,8 @@ def test_iterable(): assert isinstance(System.String.Empty, Iterable) assert isinstance(ClassTest.GetArrayList(), Iterable) assert isinstance(ClassTest.GetEnumerator(), Iterable) - assert (not isinstance(ClassTest, Iterable)) - assert (not isinstance(ClassTest(), Iterable)) + assert not isinstance(ClassTest, Iterable) + assert not isinstance(ClassTest(), Iterable) class ShouldBeIterable(ClassTest): def __iter__(self): @@ -201,16 +204,16 @@ def test_override_get_item(): class MyTable(Hashtable): def __getitem__(self, key): value = Hashtable.__getitem__(self, key) - return 'my ' + str(value) + return "my " + str(value) table = MyTable() - table['one'] = 'one' - table['two'] = 'two' - table['three'] = 'three' + table["one"] = "one" + table["two"] = "two" + table["three"] = "three" - assert table['one'] == 'my one' - assert table['two'] == 'my two' - assert table['three'] == 'my three' + assert table["one"] == "my one" + assert table["two"] == "my two" + assert table["three"] == "my three" assert table.Count == 3 @@ -221,17 +224,17 @@ def test_override_set_item(): class MyTable(Hashtable): def __setitem__(self, key, value): - value = 'my ' + str(value) + value = "my " + str(value) Hashtable.__setitem__(self, key, value) table = MyTable() - table['one'] = 'one' - table['two'] = 'two' - table['three'] = 'three' + table["one"] = "one" + table["two"] = "two" + table["three"] = "three" - assert table['one'] == 'my one' - assert table['two'] == 'my two' - assert table['three'] == 'my three' + assert table["one"] == "my one" + assert table["two"] == "my two" + assert table["three"] == "my three" assert table.Count == 3 @@ -254,29 +257,29 @@ def test_comparisons(): d1 = DateTimeOffset.Parse("2016-11-14") d2 = DateTimeOffset.Parse("2016-11-15") - assert (d1 == d2) == False - assert (d1 != d2) == True + assert (d1 == d2) == False # noqa + assert (d1 != d2) == True # noqa - assert (d1 < d2) == True - assert (d1 <= d2) == True - assert (d1 >= d2) == False - assert (d1 > d2) == False + assert (d1 < d2) == True # noqa + assert (d1 <= d2) == True # noqa + assert (d1 >= d2) == False # noqa + assert (d1 > d2) == False # noqa - assert (d1 == d1) == True - assert (d1 != d1) == False + assert (d1 == d1) == True # noqa + assert (d1 != d1) == False # noqa - assert (d1 < d1) == False - assert (d1 <= d1) == True - assert (d1 >= d1) == True - assert (d1 > d1) == False + assert (d1 < d1) == False # noqa + assert (d1 <= d1) == True # noqa + assert (d1 >= d1) == True # noqa + assert (d1 > d1) == False # noqa - assert (d2 == d1) == False - assert (d2 != d1) == True + assert (d2 == d1) == False # noqa + assert (d2 != d1) == True # noqa - assert (d2 < d1) == False - assert (d2 <= d1) == False - assert (d2 >= d1) == True - assert (d2 > d1) == True + assert (d2 < d1) == False # noqa + assert (d2 <= d1) == False # noqa + assert (d2 >= d1) == True # noqa + assert (d2 > d1) == True # noqa with pytest.raises(TypeError): d1 < None @@ -312,13 +315,13 @@ def PyCallback(self, self2): def test_method_inheritance(): """Ensure that we call the overridden method instead of the one provided in - the base class.""" + the base class.""" base = Test.BaseClass() derived = Test.DerivedClass() - assert base.IsBase() == True - assert derived.IsBase() == False + assert base.IsBase() + assert not derived.IsBase() def test_callable(): @@ -327,5 +330,5 @@ def test_callable(): def foo(): pass - assert callable(System.String("foo")) == False - assert callable(System.Action(foo)) == True + assert not callable(System.String("foo")) + assert callable(System.Action(foo)) diff --git a/tests/test_clrmethod.py b/tests/test_clrmethod.py index 0c63f9c59..70d5d03bc 100644 --- a/tests/test_clrmethod.py +++ b/tests/test_clrmethod.py @@ -2,29 +2,33 @@ """Test clrmethod and clrproperty support for calling methods and getting/setting python properties from CLR.""" -import Python.Test as Test import System -import pytest import clr + class ExampleClrClass(System.Object): __namespace__ = "PyTest" + def __init__(self): self._x = 3 + @clr.clrmethod(int, [int]) def test(self, x): - return x*2 + return x * 2 def get_X(self): return self._x + def set_X(self, value): self._x = value + X = clr.clrproperty(int, get_X, set_X) @clr.clrproperty(int) def Y(self): return self._x * 2 + def test_set_and_get_property_from_py(): """Test setting and getting clr-accessible properties from python.""" t = ExampleClrClass() @@ -34,6 +38,7 @@ def test_set_and_get_property_from_py(): assert t.X == 4 assert t.Y == 4 * 2 + def test_set_and_get_property_from_clr(): """Test setting and getting clr-accessible properties from the clr.""" t = ExampleClrClass() @@ -62,12 +67,14 @@ def test_set_and_get_property_from_clr_and_py(): assert t.X == 5 assert t.Y == 5 * 2 + def test_method_invocation_from_py(): """Test calling a clr-accessible method from python.""" t = ExampleClrClass() - assert t.test(41) == 41*2 + assert t.test(41) == 41 * 2 + def test_method_invocation_from_clr(): """Test calling a clr-accessible method from the clr.""" t = ExampleClrClass() - assert t.GetType().GetMethod("test").Invoke(t, [37]) == 37*2 + assert t.GetType().GetMethod("test").Invoke(t, [37]) == 37 * 2 diff --git a/tests/test_codec.py b/tests/test_codec.py index 0c1fb44f4..ea6038968 100644 --- a/tests/test_codec.py +++ b/tests/test_codec.py @@ -74,11 +74,11 @@ def test_list(): Python.Runtime.Codecs.SequenceDecoder.Register() ob = ListConversionTester() - l = [1, 2, 3] - assert 3 == ob.GetLength(l) + lst = [1, 2, 3] + assert 3 == ob.GetLength(lst) - l2 = [ListMember(1, "one"), ListMember(2, "two"), ListMember(3, "three")] - assert 3 == ob.GetLength(l2) + lst2 = [ListMember(1, "one"), ListMember(2, "two"), ListMember(3, "three")] + assert 3 == ob.GetLength(lst2) def test_enum(): diff --git a/tests/test_collection_mixins.py b/tests/test_collection_mixins.py index 0ac040038..91ea66938 100644 --- a/tests/test_collection_mixins.py +++ b/tests/test_collection_mixins.py @@ -1,20 +1,23 @@ import System.Collections.Generic as C + def test_contains(): - l = C.List[int]() - l.Add(42) - assert 42 in l - assert 43 not in l + lst = C.List[int]() + lst.Add(42) + assert 42 in lst + assert 43 not in lst + def test_dict_items(): d = C.Dictionary[int, str]() d[42] = "a" items = d.items() assert len(items) == 1 - k,v = items[0] + k, v = items[0] assert k == 42 assert v == "a" + # regression test for https://github.com/pythonnet/pythonnet/issues/1785 def test_dict_in_keys(): d = C.Dictionary[str, int]() diff --git a/tests/test_constructors.py b/tests/test_constructors.py index 3e0b1bb93..72f6909a9 100644 --- a/tests/test_constructors.py +++ b/tests/test_constructors.py @@ -80,16 +80,15 @@ def test_constructor_leak(): Runtime.TryCollectingGarbage(20) ref_count = sys.getrefcount(uri) - # check disabled due to GC uncertainty - # assert ref_count == 1 - + if ref_count != 1: + pytest.xfail("might have failed due to GC uncertainty") def test_string_constructor(): from System import String, Char, Array - ob = String('A', 10) - assert ob == 'A' * 10 + ob = String("A", 10) + assert ob == "A" * 10 arr = Array[Char](10) for i in range(10): diff --git a/tests/test_conversion.py b/tests/test_conversion.py index bb686dd52..def44f348 100644 --- a/tests/test_conversion.py +++ b/tests/test_conversion.py @@ -4,7 +4,12 @@ import pytest import System -from Python.Test import ConversionTest, MethodResolutionInt, UnicodeString, CodecResetter +from Python.Test import ( + ConversionTest, + MethodResolutionInt, + UnicodeString, + CodecResetter, +) from Python.Runtime import PyObjectConversions from Python.Runtime.Codecs import RawProxyEncoder @@ -33,7 +38,7 @@ def test_bool_conversion(): ob.BooleanField = None with pytest.raises(TypeError): - ob.BooleanField = '' + ob.BooleanField = "" with pytest.raises(TypeError): ob.BooleanField = System.Boolean(0) @@ -42,7 +47,7 @@ def test_bool_conversion(): ob.BooleanField = System.Boolean(1) with pytest.raises(TypeError): - ob.BooleanField = System.Boolean('a') + ob.BooleanField = System.Boolean("a") def test_sbyte_conversion(): @@ -129,16 +134,16 @@ def test_char_conversion(): assert System.Char.MinValue == chr(0) ob = ConversionTest() - assert ob.CharField == u'A' + assert ob.CharField == "A" - ob.CharField = 'B' - assert ob.CharField == u'B' + ob.CharField = "B" + assert ob.CharField == "B" - ob.CharField = u'B' - assert ob.CharField == u'B' + ob.CharField = "B" + assert ob.CharField == "B" ob.CharField = 67 - assert ob.CharField == u'C' + assert ob.CharField == "C" with pytest.raises(OverflowError): ConversionTest().CharField = 65536 @@ -447,7 +452,6 @@ def test_double_conversion(): ConversionTest().DoubleField = None - def test_decimal_conversion(): """Test decimal conversion.""" from System import Decimal @@ -490,25 +494,25 @@ def test_string_conversion(): ob = ConversionTest() assert ob.StringField == "spam" - assert ob.StringField == u"spam" + assert ob.StringField == "spam" ob.StringField = "eggs" assert ob.StringField == "eggs" - assert ob.StringField == u"eggs" + assert ob.StringField == "eggs" - ob.StringField = u"spam" + ob.StringField = "spam" + assert ob.StringField == "spam" assert ob.StringField == "spam" - assert ob.StringField == u"spam" - ob.StringField = u'\uffff\uffff' - assert ob.StringField == u'\uffff\uffff' + ob.StringField = "\uffff\uffff" + assert ob.StringField == "\uffff\uffff" ob.StringField = System.String("spam") assert ob.StringField == "spam" - assert ob.StringField == u"spam" + assert ob.StringField == "spam" - ob.StringField = System.String(u'\uffff\uffff') - assert ob.StringField == u'\uffff\uffff' + ob.StringField = System.String("\uffff\uffff") + assert ob.StringField == "\uffff\uffff" ob.StringField = None assert ob.StringField is None @@ -517,7 +521,7 @@ def test_string_conversion(): ConversionTest().StringField = 1 world = UnicodeString() - test_unicode_str = u"안녕" + test_unicode_str = "안녕" assert test_unicode_str == str(world.value) assert test_unicode_str == str(world.GetString()) assert test_unicode_str == str(world) @@ -574,12 +578,13 @@ def test_object_conversion(): class Foo(object): pass + ob.ObjectField = Foo assert ob.ObjectField == Foo class PseudoSeq: def __getitem__(self, idx): - return 0 + return 0 ob.ObjectField = PseudoSeq() assert ob.ObjectField.__class__.__name__ == "PseudoSeq" @@ -600,7 +605,7 @@ def test_null_conversion(): ob.SpamField = None assert ob.SpamField is None - pi = 22/7 + pi = 22 / 7 assert ob.Echo[System.Double](pi) == pi assert ob.Echo[System.DateTime](None) is None @@ -650,24 +655,31 @@ def test_sbyte_array_conversion(): for i, _ in enumerate(value): assert array[i] == operator.getitem(value, i) + def test_codecs(): """Test codec registration from Python""" + class ListAsRawEncoder(RawProxyEncoder): __namespace__ = "Python.Test" + def CanEncode(self, clr_type): - return clr_type.Name == "List`1" and clr_type.Namespace == "System.Collections.Generic" + return ( + clr_type.Name == "List`1" + and clr_type.Namespace == "System.Collections.Generic" + ) list_raw_encoder = ListAsRawEncoder() PyObjectConversions.RegisterEncoder(list_raw_encoder) ob = ConversionTest() - l = ob.ListField - l.Add(42) + lst = ob.ListField + lst.Add(42) assert ob.ListField.Count == 1 CodecResetter.Reset() + def test_int_param_resolution_required(): """Test resolution of `int` parameters when resolution is needed""" @@ -680,6 +692,7 @@ def test_int_param_resolution_required(): assert len(data) == 10 assert data[0] == 0 + def test_iconvertible_conversion(): change_type = System.Convert.ChangeType @@ -687,6 +700,7 @@ def test_iconvertible_conversion(): assert 1024 == change_type(1024, System.Int64) assert 1024 == change_type(1024, System.Int16) + def test_intptr_construction(): from System import IntPtr, UIntPtr, Int64, UInt64 from ctypes import sizeof, c_void_p @@ -720,11 +734,10 @@ def test_intptr_construction(): with pytest.raises(OverflowError): UIntPtr(v) + def test_explicit_conversion(): from operator import index - from System import ( - Int64, UInt64, Int32, UInt32, Int16, UInt16, Byte, SByte, Boolean - ) + from System import Int64, UInt64, Int32, UInt32, Int16, UInt16, Byte, SByte, Boolean from System import Double, Single assert int(Boolean(False)) == 0 @@ -744,7 +757,7 @@ def test_explicit_conversion(): assert float(t(-127)) == -127.0 assert int(Int64(Int64.MaxValue)) == 2**63 - 1 - assert int(Int64(Int64.MinValue)) == -2**63 + assert int(Int64(Int64.MinValue)) == -(2**63) assert int(UInt64(UInt64.MaxValue)) == 2**64 - 1 for t in [Single, Double]: diff --git a/tests/test_delegate.py b/tests/test_delegate.py index 55115203c..51e4351e2 100644 --- a/tests/test_delegate.py +++ b/tests/test_delegate.py @@ -14,8 +14,8 @@ def test_delegate_standard_attrs(): """Test standard delegate attributes.""" from Python.Test import PublicDelegate - assert PublicDelegate.__name__ == 'PublicDelegate' - assert PublicDelegate.__module__ == 'Python.Test' + assert PublicDelegate.__name__ == "PublicDelegate" + assert PublicDelegate.__module__ == "Python.Test" assert isinstance(PublicDelegate.__dict__, DictProxyType) assert PublicDelegate.__doc__ is None @@ -24,11 +24,12 @@ def test_global_delegate_visibility(): """Test visibility of module-level delegates.""" from Python.Test import PublicDelegate - assert PublicDelegate.__name__ == 'PublicDelegate' - assert Test.PublicDelegate.__name__ == 'PublicDelegate' + assert PublicDelegate.__name__ == "PublicDelegate" + assert Test.PublicDelegate.__name__ == "PublicDelegate" with pytest.raises(ImportError): from Python.Test import InternalDelegate + _ = InternalDelegate with pytest.raises(AttributeError): @@ -38,10 +39,10 @@ def test_global_delegate_visibility(): def test_nested_delegate_visibility(): """Test visibility of nested delegates.""" ob = DelegateTest.PublicDelegate - assert ob.__name__ == 'PublicDelegate' + assert ob.__name__ == "PublicDelegate" ob = DelegateTest.ProtectedDelegate - assert ob.__name__ == 'ProtectedDelegate' + assert ob.__name__ == "ProtectedDelegate" with pytest.raises(AttributeError): _ = DelegateTest.InternalDelegate @@ -227,6 +228,7 @@ def test_subclass_delegate_fails(): from Python.Test import PublicDelegate with pytest.raises(TypeError): + class Boom(PublicDelegate): pass @@ -258,10 +260,12 @@ def always_so_negative(): def always_so_positive(): return 1 + bad = BoolDelegate(always_so_positive) with pytest.raises(TypeError): ob.CallBoolDelegate(bad) + def test_object_delegate(): """Test object delegate.""" from Python.Test import ObjectDelegate @@ -273,6 +277,7 @@ def create_object(): ob = DelegateTest() ob.CallObjectDelegate(d) + def test_invalid_object_delegate(): """Test invalid object delegate with mismatched return type.""" from Python.Test import ObjectDelegate @@ -282,9 +287,11 @@ def test_invalid_object_delegate(): with pytest.raises(TypeError): ob.CallObjectDelegate(d) + def test_out_int_delegate(): """Test delegate with an out int parameter.""" from Python.Test import OutIntDelegate + value = 7 def out_hello_func(ignored): @@ -299,31 +306,35 @@ def out_hello_func(ignored): assert result == 5 def invalid_handler(ignored): - return '5' + return "5" d = OutIntDelegate(invalid_handler) with pytest.raises(TypeError): result = d(value) + def test_out_string_delegate(): """Test delegate with an out string parameter.""" from Python.Test import OutStringDelegate - value = 'goodbye' + + value = "goodbye" def out_hello_func(ignored): - return 'hello' + return "hello" d = OutStringDelegate(out_hello_func) result = d(value) - assert result == 'hello' + assert result == "hello" ob = DelegateTest() result = ob.CallOutStringDelegate(d, value) - assert result == 'hello' + assert result == "hello" + def test_ref_int_delegate(): """Test delegate with a ref string parameter.""" from Python.Test import RefIntDelegate + value = 7 def ref_hello_func(data): @@ -338,44 +349,48 @@ def ref_hello_func(data): result = ob.CallRefIntDelegate(d, value) assert result == value + 1 + def test_ref_string_delegate(): """Test delegate with a ref string parameter.""" from Python.Test import RefStringDelegate - value = 'goodbye' + + value = "goodbye" def ref_hello_func(data): assert data == value - return 'hello' + return "hello" d = RefStringDelegate(ref_hello_func) result = d(value) - assert result == 'hello' + assert result == "hello" ob = DelegateTest() result = ob.CallRefStringDelegate(d, value) - assert result == 'hello' + assert result == "hello" + def test_ref_int_ref_string_delegate(): """Test delegate with a ref int and ref string parameter.""" from Python.Test import RefIntRefStringDelegate + intData = 7 - stringData = 'goodbye' + stringData = "goodbye" def ref_hello_func(intValue, stringValue): assert intData == intValue assert stringData == stringValue - return (intValue + 1, stringValue + '!') + return (intValue + 1, stringValue + "!") d = RefIntRefStringDelegate(ref_hello_func) result = d(intData, stringData) - assert result == (intData + 1, stringData + '!') + assert result == (intData + 1, stringData + "!") ob = DelegateTest() result = ob.CallRefIntRefStringDelegate(d, intData, stringData) - assert result == (intData + 1, stringData + '!') + assert result == (intData + 1, stringData + "!") def not_a_tuple(intValue, stringValue): - return 'a' + return "a" d = RefIntRefStringDelegate(not_a_tuple) with pytest.raises(TypeError): @@ -389,40 +404,42 @@ def short_tuple(intValue, stringValue): result = d(intData, stringData) def long_tuple(intValue, stringValue): - return (5, 'a', 'b') + return (5, "a", "b") d = RefIntRefStringDelegate(long_tuple) with pytest.raises(TypeError): result = d(intData, stringData) def wrong_tuple_item(intValue, stringValue): - return ('a', 'b') + return ("a", "b") d = RefIntRefStringDelegate(wrong_tuple_item) with pytest.raises(TypeError): result = d(intData, stringData) + def test_int_ref_int_ref_string_delegate(): """Test delegate with a ref int and ref string parameter.""" from Python.Test import IntRefIntRefStringDelegate + intData = 7 - stringData = 'goodbye' + stringData = "goodbye" def ref_hello_func(intValue, stringValue): assert intData == intValue assert stringData == stringValue - return (intValue + len(stringValue), intValue + 1, stringValue + '!') + return (intValue + len(stringValue), intValue + 1, stringValue + "!") d = IntRefIntRefStringDelegate(ref_hello_func) result = d(intData, stringData) - assert result == (intData + len(stringData), intData + 1, stringData + '!') + assert result == (intData + len(stringData), intData + 1, stringData + "!") ob = DelegateTest() result = ob.CallIntRefIntRefStringDelegate(d, intData, stringData) - assert result == (intData + len(stringData), intData + 1, stringData + '!') + assert result == (intData + len(stringData), intData + 1, stringData + "!") def not_a_tuple(intValue, stringValue): - return 'a' + return "a" d = IntRefIntRefStringDelegate(not_a_tuple) with pytest.raises(TypeError): @@ -436,7 +453,7 @@ def short_tuple(intValue, stringValue): result = d(intData, stringData) def wrong_return_type(intValue, stringValue): - return ('a', 7, 'b') + return ("a", 7, "b") d = IntRefIntRefStringDelegate(wrong_return_type) with pytest.raises(TypeError): diff --git a/tests/test_docstring.py b/tests/test_docstring.py index 36c925a74..1941e1664 100644 --- a/tests/test_docstring.py +++ b/tests/test_docstring.py @@ -6,25 +6,33 @@ def test_doc_with_ctor(): from Python.Test import DocWithCtorTest - assert DocWithCtorTest.__doc__ == 'DocWithCtorTest Class' - assert DocWithCtorTest.TestMethod.__doc__ == 'DocWithCtorTest TestMethod' - assert DocWithCtorTest.StaticTestMethod.__doc__ == 'DocWithCtorTest StaticTestMethod' + assert DocWithCtorTest.__doc__ == "DocWithCtorTest Class" + assert DocWithCtorTest.TestMethod.__doc__ == "DocWithCtorTest TestMethod" + assert ( + DocWithCtorTest.StaticTestMethod.__doc__ == "DocWithCtorTest StaticTestMethod" + ) def test_doc_with_ctor_no_doc(): from Python.Test import DocWithCtorNoDocTest - assert DocWithCtorNoDocTest.__doc__ == 'Void .ctor(Boolean)' - assert DocWithCtorNoDocTest.TestMethod.__doc__ == 'Void TestMethod(Double, Int32)' - assert DocWithCtorNoDocTest.StaticTestMethod.__doc__ == 'Void StaticTestMethod(Double, Int32)' + assert DocWithCtorNoDocTest.__doc__ == "Void .ctor(Boolean)" + assert DocWithCtorNoDocTest.TestMethod.__doc__ == "Void TestMethod(Double, Int32)" + assert ( + DocWithCtorNoDocTest.StaticTestMethod.__doc__ + == "Void StaticTestMethod(Double, Int32)" + ) def test_doc_without_ctor(): from Python.Test import DocWithoutCtorTest - assert DocWithoutCtorTest.__doc__ == 'DocWithoutCtorTest Class' - assert DocWithoutCtorTest.TestMethod.__doc__ == 'DocWithoutCtorTest TestMethod' - assert DocWithoutCtorTest.StaticTestMethod.__doc__ == 'DocWithoutCtorTest StaticTestMethod' + assert DocWithoutCtorTest.__doc__ == "DocWithoutCtorTest Class" + assert DocWithoutCtorTest.TestMethod.__doc__ == "DocWithoutCtorTest TestMethod" + assert ( + DocWithoutCtorTest.StaticTestMethod.__doc__ + == "DocWithoutCtorTest StaticTestMethod" + ) def test_doc_primitve(): diff --git a/tests/test_engine.py b/tests/test_engine.py index 65aaa3ce8..a3b17195e 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -50,6 +50,8 @@ def test_run_string(): PythonEngine.ReleaseLock() + def test_leak_type(): import clr + sys._leaked_intptr = clr.GetClrType(System.IntPtr) diff --git a/tests/test_enum.py b/tests/test_enum.py index 3d3edba10..fcb407796 100644 --- a/tests/test_enum.py +++ b/tests/test_enum.py @@ -12,8 +12,8 @@ def test_enum_standard_attrs(): """Test standard enum attributes.""" from System import DayOfWeek - assert DayOfWeek.__name__ == 'DayOfWeek' - assert DayOfWeek.__module__ == 'System' + assert DayOfWeek.__name__ == "DayOfWeek" + assert DayOfWeek.__module__ == "System" assert isinstance(DayOfWeek.__dict__, DictProxyType) @@ -88,6 +88,7 @@ def test_ulong_enum(): def test_simple_enum_to_int(): from System import DayOfWeek + assert int(DayOfWeek.Sunday) == 0 @@ -113,6 +114,7 @@ def test_subclass_enum_fails(): from System import DayOfWeek with pytest.raises(TypeError): + class Boom(DayOfWeek): pass diff --git a/tests/test_event.py b/tests/test_event.py index 885589032..8ce71fc06 100644 --- a/tests/test_event.py +++ b/tests/test_event.py @@ -5,9 +5,15 @@ import pytest from Python.Test import EventTest, EventArgsTest -from .utils import (CallableHandler, ClassMethodHandler, GenericHandler, - MultipleHandler, StaticMethodHandler, VarCallableHandler, - VariableArgsHandler) +from .utils import ( + CallableHandler, + ClassMethodHandler, + GenericHandler, + MultipleHandler, + StaticMethodHandler, + VarCallableHandler, + VariableArgsHandler, +) def test_public_instance_event(): @@ -278,28 +284,30 @@ def test_unbound_method_handler(): def test_function_handler(): """Test function handlers.""" ob = EventTest() - dict_ = {'value': None} + dict_ = {"value": None} def handler(sender, args, dict_=dict_): - dict_['value'] = args.value + dict_["value"] = args.value ob.PublicEvent += handler - assert dict_['value'] is None + assert dict_["value"] is None ob.OnPublicEvent(EventArgsTest(10)) - assert dict_['value'] == 10 + assert dict_["value"] == 10 ob.PublicEvent -= handler - assert dict_['value'] == 10 + assert dict_["value"] == 10 ob.OnPublicEvent(EventArgsTest(20)) - assert dict_['value'] == 10 + assert dict_["value"] == 10 + def test_out_function_handler(): """Test function handlers with Out arguments.""" ob = EventTest() value = 10 + def handler(ignored): return value @@ -308,15 +316,17 @@ def handler(ignored): assert result == value ob.OutStringEvent += handler - value = 'This is the event data' - result = ob.OnOutStringEvent('Hello') + value = "This is the event data" + result = ob.OnOutStringEvent("Hello") assert result == value + def test_ref_function_handler(): """Test function handlers with Ref arguments.""" ob = EventTest() value = 10 + def handler(data): return value + data @@ -327,9 +337,10 @@ def handler(data): ob.RefStringEvent += ob.RefStringHandler ob.RefStringEvent += handler - value = 'This is the event data' - result = ob.OnRefStringEvent('!') - assert result == value + '!!' + value = "This is the event data" + result = ob.OnRefStringEvent("!") + assert result == value + "!!" + def test_add_non_callable_handler(): """Test handling of attempts to add non-callable handlers.""" @@ -343,6 +354,7 @@ def test_add_non_callable_handler(): ob.PublicEvent += "spam" with pytest.raises(TypeError): + class Spam(object): pass @@ -451,6 +463,7 @@ def test_remove_multiple_static_handlers(): def test_random_multiple_handlers(): """Test random subscribe / unsubscribe of the same handlers.""" import random + ob = EventTest() handler = MultipleHandler() handler2 = MultipleHandler() @@ -522,7 +535,7 @@ def test_handler_callback_failure(): class BadHandler(object): def handler(self, one): - return 'too many' + return "too many" ob = EventTest() handler = BadHandler() @@ -535,7 +548,7 @@ def handler(self, one): class BadHandler(object): def handler(self, one, two, three, four, five): - return 'not enough' + return "not enough" ob = EventTest() handler = BadHandler() @@ -600,9 +613,9 @@ def test_event_descriptor_abuse(): del EventTest.PublicEvent with pytest.raises(TypeError): - del EventTest.__dict__['PublicEvent'] + del EventTest.__dict__["PublicEvent"] - desc = EventTest.__dict__['PublicEvent'] + desc = EventTest.__dict__["PublicEvent"] with pytest.raises(TypeError): desc.__get__(0, 0) diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 469934fe5..f47b20cd7 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -14,15 +14,17 @@ # into olist, using seen to track # already processed objects. + def _getr(slist, olist, seen): for e in slist: - if id(e) in seen: - continue - seen[id(e)] = None - olist.append(e) - tl = gc.get_referents(e) - if tl: - _getr(tl, olist, seen) + if id(e) in seen: + continue + seen[id(e)] = None + olist.append(e) + tl = gc.get_referents(e) + if tl: + _getr(tl, olist, seen) + # The public function. def get_all_objects(): @@ -36,27 +38,37 @@ def get_all_objects(): # _getr does the real work. _getr(gcl, olist, seen) return olist + + # end code from https://utcc.utoronto.ca/~cks/space/blog/python/GetAllObjects + def leak_check(func): def do_leak_check(): func() gc.collect() - exc = {x for x in get_all_objects() if isinstance(x, Exception) and not isinstance(x, pytest.PytestDeprecationWarning)} + exc = { + x + for x in get_all_objects() + if isinstance(x, Exception) + and not isinstance(x, pytest.PytestDeprecationWarning) + } print(len(exc)) if len(exc): for x in exc: - print('-------') + print("-------") print(repr(x)) print(gc.get_referrers(x)) print(len(gc.get_referrers(x))) assert False + gc.collect() return do_leak_check + def test_unified_exception_semantics(): """Test unified exception semantics.""" - e = System.Exception('Something bad happened') + e = System.Exception("Something bad happened") assert isinstance(e, Exception) assert isinstance(e, System.Exception) @@ -69,10 +81,10 @@ def test_standard_exception_attributes(): e = ExceptionTest.GetExplicitException() assert isinstance(e, OverflowException) - assert e.Message == 'error' + assert e.Message == "error" - e.Source = 'Test Suite' - assert e.Source == 'Test Suite' + e.Source = "Test Suite" + assert e.Source == "Test Suite" v = e.ToString() assert len(v) > 0 @@ -88,19 +100,19 @@ def test_extended_exception_attributes(): assert isinstance(e, OverflowException) assert isinstance(e, System.Exception) - assert e.Message == 'error' + assert e.Message == "error" - e.Source = 'Test Suite' - assert e.Source == 'Test Suite' + e.Source = "Test Suite" + assert e.Source == "Test Suite" v = e.ToString() assert len(v) > 0 - assert e.ExtraProperty == 'extra' - e.ExtraProperty = 'changed' - assert e.ExtraProperty == 'changed' + assert e.ExtraProperty == "extra" + e.ExtraProperty = "changed" + assert e.ExtraProperty == "changed" - assert e.GetExtraInfo() == 'changed' + assert e.GetExtraInfo() == "changed" def test_raise_class_exception(): @@ -118,6 +130,7 @@ def test_exc_info(): """Test class exception propagation. Behavior of exc_info changed in Py3. Refactoring its test""" from System import NullReferenceException + try: raise NullReferenceException("message") except Exception as exc: @@ -135,11 +148,11 @@ def test_raise_class_exception_with_value(): from System import NullReferenceException with pytest.raises(NullReferenceException) as cm: - raise NullReferenceException('Aiiieee!') + raise NullReferenceException("Aiiieee!") exc = cm.value assert isinstance(exc, NullReferenceException) - assert exc.Message == 'Aiiieee!' + assert exc.Message == "Aiiieee!" def test_raise_instance_exception(): @@ -163,7 +176,7 @@ def test_raise_instance_exception_with_args(): exc = cm.value assert isinstance(exc, NullReferenceException) - assert exc.Message == 'Aiiieee!' + assert exc.Message == "Aiiieee!" def test_managed_exception_propagation(): @@ -190,13 +203,13 @@ def test_managed_exception_conversion(): assert isinstance(e, OverflowException) assert isinstance(e, System.Exception) - v = ExceptionTest.SetBaseException(System.Exception('error')) + v = ExceptionTest.SetBaseException(System.Exception("error")) assert v - v = ExceptionTest.SetExplicitException(OverflowException('error')) + v = ExceptionTest.SetExplicitException(OverflowException("error")) assert v - v = ExceptionTest.SetWidenedException(OverflowException('error')) + v = ExceptionTest.SetWidenedException(OverflowException("error")) assert v @@ -235,7 +248,7 @@ def test_catch_exception_managed_class(): from System import OverflowException with pytest.raises(OverflowException): - raise OverflowException('overflow') + raise OverflowException("overflow") def test_catch_exception_python_class(): @@ -243,7 +256,7 @@ def test_catch_exception_python_class(): from System import OverflowException with pytest.raises(Exception): - raise OverflowException('overflow') + raise OverflowException("overflow") def test_catch_exception_base_class(): @@ -251,7 +264,7 @@ def test_catch_exception_base_class(): from System import OverflowException, ArithmeticException with pytest.raises(ArithmeticException): - raise OverflowException('overflow') + raise OverflowException("overflow") def test_catch_exception_nested_base_class(): @@ -259,7 +272,7 @@ def test_catch_exception_nested_base_class(): from System import OverflowException, SystemException with pytest.raises(SystemException): - raise OverflowException('overflow') + raise OverflowException("overflow") def test_catch_exception_with_assignment(): @@ -267,7 +280,7 @@ def test_catch_exception_with_assignment(): from System import OverflowException with pytest.raises(OverflowException) as cm: - raise OverflowException('overflow') + raise OverflowException("overflow") e = cm.value assert isinstance(e, OverflowException) @@ -278,11 +291,11 @@ def test_catch_exception_unqualified(): from System import OverflowException try: - raise OverflowException('overflow') - except: + raise OverflowException("overflow") + except: # noqa: E722 pass else: - self.fail("failed to catch unqualified exception") + pytest.fail("failed to catch unqualified exception") def test_catch_baseexception(): @@ -290,34 +303,35 @@ def test_catch_baseexception(): from System import OverflowException with pytest.raises(BaseException): - raise OverflowException('overflow') + raise OverflowException("overflow") def test_apparent_module_of_exception(): """Test the apparent module of an exception.""" from System import OverflowException - assert System.Exception.__module__ == 'System' - assert OverflowException.__module__ == 'System' + assert System.Exception.__module__ == "System" + assert OverflowException.__module__ == "System" def test_str_of_exception(): """Test the str() representation of an exception.""" from System import NullReferenceException, Convert, FormatException - e = NullReferenceException('') - assert str(e) == '' + e = NullReferenceException("") + assert str(e) == "" - e = NullReferenceException('Something bad happened') - assert str(e).startswith('Something bad happened') + e = NullReferenceException("Something bad happened") + assert str(e).startswith("Something bad happened") - with pytest.raises(FormatException) as cm: - Convert.ToDateTime('this will fail') + with pytest.raises(FormatException): + Convert.ToDateTime("this will fail") def test_python_compat_of_managed_exceptions(): """Test managed exceptions compatible with Python's implementation""" from System import OverflowException + msg = "Simple message" e = OverflowException(msg) @@ -326,7 +340,7 @@ def test_python_compat_of_managed_exceptions(): assert e.args == (msg,) assert isinstance(e.args, tuple) strexp = "OverflowException('Simple message" - assert repr(e)[:len(strexp)] == strexp + assert repr(e)[: len(strexp)] == strexp def test_exception_is_instance_of_system_object(): @@ -348,7 +362,7 @@ def test_exception_is_instance_of_system_object(): # be true, even though it does not really subclass Object. from System import OverflowException, Object - o = OverflowException('error') + o = OverflowException("error") if sys.version_info >= (2, 6): assert isinstance(o, Object) @@ -372,14 +386,17 @@ def test_chained_exceptions(): exc = cm.value - msgs = ("Outer exception", - "Inner exception", - "Innermost exception",) + msgs = ( + "Outer exception", + "Inner exception", + "Innermost exception", + ) for msg in msgs: assert exc.Message == msg assert exc.__cause__ == exc.InnerException exc = exc.__cause__ + def test_iteration_exception(): from Python.Test import ExceptionTest from System import OverflowException @@ -421,6 +438,7 @@ def test_iteration_innerexception(): with pytest.raises(StopIteration): next(val) + def leak_test(func): def do_test_leak(): # PyTest leaks things, gather the current state @@ -432,6 +450,7 @@ def do_test_leak(): return do_test_leak + @leak_test def test_dont_leak_exceptions_simple(): from Python.Test import ExceptionTest @@ -439,14 +458,16 @@ def test_dont_leak_exceptions_simple(): try: ExceptionTest.DoThrowSimple() except System.ArgumentException: - print('type error, as expected') + print("type error, as expected") + @leak_test def test_dont_leak_exceptions_inner(): from Python.Test import ExceptionTest + try: ExceptionTest.DoThrowWithInner() except TypeError: - print('type error, as expected') + print("type error, as expected") except System.ArgumentException: - print('type error, also expected') \ No newline at end of file + print("type error, also expected") diff --git a/tests/test_field.py b/tests/test_field.py index 52fed54cb..0d7ef3552 100644 --- a/tests/test_field.py +++ b/tests/test_field.py @@ -158,16 +158,16 @@ def test_field_descriptor_get_set(): assert FieldTest.PublicStaticField == 0 assert ob.PublicStaticField == 0 - descriptor = FieldTest.__dict__['PublicStaticField'] - assert type(descriptor) != int + descriptor = FieldTest.__dict__["PublicStaticField"] + assert not isinstance(descriptor, int) ob.PublicStaticField = 0 - descriptor = FieldTest.__dict__['PublicStaticField'] - assert type(descriptor) != int + descriptor = FieldTest.__dict__["PublicStaticField"] + assert not isinstance(descriptor, int) FieldTest.PublicStaticField = 0 - descriptor = FieldTest.__dict__['PublicStaticField'] - assert type(descriptor) != int + descriptor = FieldTest.__dict__["PublicStaticField"] + assert not isinstance(descriptor, int) def test_field_descriptor_wrong_type(): @@ -179,7 +179,7 @@ def test_field_descriptor_wrong_type(): def test_field_descriptor_abuse(): """Test field descriptor abuse.""" - desc = FieldTest.__dict__['PublicField'] + desc = FieldTest.__dict__["PublicField"] with pytest.raises(TypeError): desc.__get__(0, 0) @@ -228,16 +228,16 @@ def test_byte_field(): def test_char_field(): """Test char fields.""" ob = FieldTest() - assert ob.CharField == u'A' - assert ob.CharField == 'A' + assert ob.CharField == "A" + assert ob.CharField == "A" - ob.CharField = 'B' - assert ob.CharField == u'B' - assert ob.CharField == 'B' + ob.CharField = "B" + assert ob.CharField == "B" + assert ob.CharField == "B" - ob.CharField = u'C' - assert ob.CharField == u'C' - assert ob.CharField == 'C' + ob.CharField = "C" + assert ob.CharField == "C" + assert ob.CharField == "C" def test_int16_field(): diff --git a/tests/test_generic.py b/tests/test_generic.py index 6d514d638..a56d6301a 100644 --- a/tests/test_generic.py +++ b/tests/test_generic.py @@ -222,11 +222,11 @@ def test_derived_from_open_generic_type(): from Python.Test import DerivedFromOpenGeneric type_ = DerivedFromOpenGeneric[System.String, System.String] - inst = type_(1, 'two', 'three') + inst = type_(1, "two", "three") assert inst.value1 == 1 - assert inst.value2 == 'two' - assert inst.value3 == 'three' + assert inst.value2 == "two" + assert inst.value3 == "three" def test_generic_type_name_resolution(): @@ -263,7 +263,7 @@ def test_generic_type_binding(): assert_generic_wrapper_by_type(bool, True) assert_generic_wrapper_by_type(System.Byte, 255) assert_generic_wrapper_by_type(System.SByte, 127) - assert_generic_wrapper_by_type(System.Char, u'A') + assert_generic_wrapper_by_type(System.Char, "A") assert_generic_wrapper_by_type(System.Int16, 32767) assert_generic_wrapper_by_type(System.Int32, 2147483647) assert_generic_wrapper_by_type(int, 2147483647) @@ -307,7 +307,7 @@ def test_generic_method_binding(): def test_generic_method_type_handling(): """Test argument conversion / binding for generic methods.""" - from Python.Test import InterfaceTest, ISayHello1, ShortEnum + from Python.Test import InterfaceTest, ShortEnum import System # FIXME: Fails because Converter.GetTypeByAlias returns int32 for any integer, including ulong @@ -316,7 +316,7 @@ def test_generic_method_type_handling(): assert_generic_method_by_type(bool, True) assert_generic_method_by_type(System.Byte, 255) assert_generic_method_by_type(System.SByte, 127) - assert_generic_method_by_type(System.Char, u'A') + assert_generic_method_by_type(System.Char, "A") assert_generic_method_by_type(System.Int16, 32767) assert_generic_method_by_type(System.Int32, 2147483647) assert_generic_method_by_type(int, 2147483647) @@ -334,33 +334,34 @@ def test_generic_method_type_handling(): def test_correct_overload_selection(): """Test correct overloading selection for common types.""" - from System import (String, Double, Single, - Int16, Int32, Int64) + from System import String, Double, Single, Int16, Int32, Int64 from System import Math substr = String("substring") - assert substr.Substring(2) == substr.Substring.__overloads__[Int32]( - Int32(2)) + assert substr.Substring(2) == substr.Substring.__overloads__[Int32](Int32(2)) assert substr.Substring(2, 3) == substr.Substring.__overloads__[Int32, Int32]( - Int32(2), Int32(3)) + Int32(2), Int32(3) + ) - for atype, value1, value2 in zip([Double, Single, Int16, Int32, Int64], - [1.0, 1.0, 1, 1, 1], - [2.0, 0.5, 2, 0, -1]): + for atype, value1, value2 in zip( + [Double, Single, Int16, Int32, Int64], [1.0, 1.0, 1, 1, 1], [2.0, 0.5, 2, 0, -1] + ): assert Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype(value1)) assert Math.Abs(value1) == Math.Abs.__overloads__[atype](atype(value1)) - assert Math.Max(atype(value1), - atype(value2)) == Math.Max.__overloads__[atype, atype]( - atype(value1), atype(value2)) - assert Math.Max(atype(value1), - value2) == Math.Max.__overloads__[atype, atype]( - atype(value1), atype(value2)) + assert Math.Max(atype(value1), atype(value2)) == Math.Max.__overloads__[ + atype, atype + ](atype(value1), atype(value2)) + assert Math.Max(atype(value1), value2) == Math.Max.__overloads__[atype, atype]( + atype(value1), atype(value2) + ) clr.AddReference("System.Runtime.InteropServices") from System.Runtime.InteropServices import GCHandle, GCHandleType from System import Array, Byte + cs_array = Array.CreateInstance(Byte, 1000) handler = GCHandle.Alloc(cs_array, GCHandleType.Pinned) + assert handler is not None def test_generic_method_overload_selection(): @@ -469,9 +470,9 @@ def test_method_overload_selection_with_generic_types(): assert value.value == 127 vtype = GenericWrapper[System.Char] - input_ = vtype(u'A') + input_ = vtype("A") value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value.value == u'A' + assert value.value == "A" vtype = GenericWrapper[System.Char] input_ = vtype(65535) @@ -608,9 +609,9 @@ def test_overload_selection_with_arrays_of_generic_types(): gtype = GenericWrapper[System.Char] vtype = System.Array[gtype] - input_ = vtype([gtype(u'A'), gtype(u'A')]) + input_ = vtype([gtype("A"), gtype("A")]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value[0].value == u'A' + assert value[0].value == "A" assert value.Length == 2 gtype = GenericWrapper[System.Char] @@ -643,8 +644,7 @@ def test_overload_selection_with_arrays_of_generic_types(): gtype = GenericWrapper[System.Int64] vtype = System.Array[gtype] - input_ = vtype([gtype(9223372036854775807), - gtype(9223372036854775807)]) + input_ = vtype([gtype(9223372036854775807), gtype(9223372036854775807)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) assert value[0].value == 9223372036854775807 assert value.Length == 2 @@ -665,8 +665,7 @@ def test_overload_selection_with_arrays_of_generic_types(): gtype = GenericWrapper[System.UInt64] vtype = System.Array[gtype] - input_ = vtype([gtype(18446744073709551615), - gtype(18446744073709551615)]) + input_ = vtype([gtype(18446744073709551615), gtype(18446744073709551615)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) assert value[0].value == 18446744073709551615 assert value.Length == 2 @@ -680,24 +679,21 @@ def test_overload_selection_with_arrays_of_generic_types(): gtype = GenericWrapper[System.Double] vtype = System.Array[gtype] - input_ = vtype([gtype(1.7976931348623157e308), - gtype(1.7976931348623157e308)]) + input_ = vtype([gtype(1.7976931348623157e308), gtype(1.7976931348623157e308)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) assert value[0].value == 1.7976931348623157e308 assert value.Length == 2 gtype = GenericWrapper[float] vtype = System.Array[gtype] - input_ = vtype([gtype(1.7976931348623157e308), - gtype(1.7976931348623157e308)]) + input_ = vtype([gtype(1.7976931348623157e308), gtype(1.7976931348623157e308)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) assert value[0].value == 1.7976931348623157e308 assert value.Length == 2 gtype = GenericWrapper[System.Decimal] vtype = System.Array[gtype] - input_ = vtype([gtype(System.Decimal.One), - gtype(System.Decimal.One)]) + input_ = vtype([gtype(System.Decimal.One), gtype(System.Decimal.One)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) assert value[0].value == System.Decimal.One assert value.Length == 2 @@ -757,11 +753,14 @@ def test_nested_generic_class(): # TODO NotImplemented pass + def test_missing_generic_type(): from System.Collections import IList + with pytest.raises(TypeError): IList[bool] + # https://github.com/pythonnet/pythonnet/issues/1522 def test_overload_generic_parameter(): from Python.Test import MethodTest, MethodTestSub @@ -771,19 +770,24 @@ def test_overload_generic_parameter(): inst.OverloadedConstrainedGeneric(generic) inst.OverloadedConstrainedGeneric[MethodTestSub](generic) - inst.OverloadedConstrainedGeneric[MethodTestSub](generic, '42') - inst.OverloadedConstrainedGeneric[MethodTestSub](generic, System.String('42')) + inst.OverloadedConstrainedGeneric[MethodTestSub](generic, "42") + inst.OverloadedConstrainedGeneric[MethodTestSub](generic, System.String("42")) + def test_invalid_generic_type_parameter(): from Python.Test import GenericTypeWithConstraint + with pytest.raises(TypeError): GenericTypeWithConstraint[System.Object] + def test_invalid_generic_method_type_parameter(): from Python.Test import ConversionTest + with pytest.raises(TypeError): ConversionTest.Echo[System.Object] + def test_generic_list_array_conversion(): """Test conversion of lists to generic array arguments.""" from Python.Test import GenericArrayConversionTest diff --git a/tests/test_import.py b/tests/test_import.py index 877eacd84..8cd8bcf13 100644 --- a/tests/test_import.py +++ b/tests/test_import.py @@ -5,12 +5,13 @@ import pytest import sys + def test_relative_missing_import(): """Test that a relative missing import doesn't crash. Some modules use this to check if a package is installed. Relative import in the site-packages folder""" with pytest.raises(ImportError): - from . import _missing_import + pass def test_import_all_on_second_time(): @@ -18,5 +19,5 @@ def test_import_all_on_second_time(): Due to import * only allowed at module level, the test body splitted to a module file.""" from . import importtest + del sys.modules[importtest.__name__] - diff --git a/tests/test_indexer.py b/tests/test_indexer.py index 8cf3150ba..f1365b6a6 100644 --- a/tests/test_indexer.py +++ b/tests/test_indexer.py @@ -340,6 +340,7 @@ def test_decimal_indexer(): ob = Test.DecimalIndexerTest() from System import Decimal + max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") @@ -365,19 +366,19 @@ def test_string_indexer(): ob = Test.StringIndexerTest() assert ob["spam"] is None - assert ob[u"spam"] is None + assert ob["spam"] is None ob["spam"] = "spam" assert ob["spam"] == "spam" - assert ob["spam"] == u"spam" - assert ob[u"spam"] == "spam" - assert ob[u"spam"] == u"spam" + assert ob["spam"] == "spam" + assert ob["spam"] == "spam" + assert ob["spam"] == "spam" - ob[u"eggs"] = u"eggs" + ob["eggs"] = "eggs" + assert ob["eggs"] == "eggs" + assert ob["eggs"] == "eggs" + assert ob["eggs"] == "eggs" assert ob["eggs"] == "eggs" - assert ob["eggs"] == u"eggs" - assert ob[u"eggs"] == "eggs" - assert ob[u"eggs"] == u"eggs" with pytest.raises(TypeError): ob = Test.StringIndexerTest() @@ -421,6 +422,7 @@ def test_object_indexer(): ob = Test.ObjectIndexerTest() from Python.Test import Spam + spam = Spam("spam") assert ob[spam] is None @@ -454,6 +456,7 @@ def test_interface_indexer(): ob = Test.InterfaceIndexerTest() from Python.Test import Spam + spam = Spam("spam") assert ob[spam] is None @@ -478,6 +481,7 @@ def test_typed_indexer(): ob = Test.TypedIndexerTest() from Python.Test import Spam + spam = Spam("spam") assert ob[spam] is None @@ -604,6 +608,7 @@ def test_indexer_abuse(): def test_indexer_accessed_through_interface(): """Test that indexers can be accessed through interfaces""" from System.Collections.Generic import Dictionary, IDictionary + d = IDictionary[str, str](Dictionary[str, str]()) d["one"] = "1" assert d["one"] == "1" @@ -612,6 +617,7 @@ def test_indexer_accessed_through_interface(): def test_using_indexer_on_object_without_indexer(): """Test using subscript syntax on an object an without indexer raises""" from System import Object + o = Object() with pytest.raises(TypeError): o[0] @@ -651,6 +657,7 @@ def test_inherited_indexer_interface(): ifc[0] = "zero" assert ifc[0] == "zero" + def test_public_inherited_overloaded_indexer(): """Test public indexers.""" ob = Test.PublicInheritedOverloadedIndexer() diff --git a/tests/test_interface.py b/tests/test_interface.py index ac620684d..342e9ccbe 100644 --- a/tests/test_interface.py +++ b/tests/test_interface.py @@ -12,8 +12,8 @@ def test_interface_standard_attrs(): """Test standard class attributes.""" from Python.Test import IPublicInterface - assert IPublicInterface.__name__ == 'IPublicInterface' - assert IPublicInterface.__module__ == 'Python.Test' + assert IPublicInterface.__name__ == "IPublicInterface" + assert IPublicInterface.__module__ == "Python.Test" assert isinstance(IPublicInterface.__dict__, DictProxyType) @@ -21,10 +21,11 @@ def test_global_interface_visibility(): """Test visibility of module-level interfaces.""" from Python.Test import IPublicInterface - assert IPublicInterface.__name__ == 'IPublicInterface' + assert IPublicInterface.__name__ == "IPublicInterface" with pytest.raises(ImportError): from Python.Test import IInternalInterface + _ = IInternalInterface with pytest.raises(AttributeError): @@ -36,10 +37,10 @@ def test_nested_interface_visibility(): from Python.Test import InterfaceTest ob = InterfaceTest.IPublic - assert ob.__name__ == 'IPublic' + assert ob.__name__ == "IPublic" ob = InterfaceTest.IProtected - assert ob.__name__ == 'IProtected' + assert ob.__name__ == "IProtected" with pytest.raises(AttributeError): _ = InterfaceTest.IInternal @@ -53,22 +54,22 @@ def test_explicit_cast_to_interface(): from Python.Test import InterfaceTest ob = InterfaceTest() - assert type(ob).__name__ == 'InterfaceTest' - assert hasattr(ob, 'HelloProperty') + assert type(ob).__name__ == "InterfaceTest" + assert hasattr(ob, "HelloProperty") i1 = Test.ISayHello1(ob) - assert type(i1).__name__ == 'ISayHello1' - assert hasattr(i1, 'SayHello') - assert i1.SayHello() == 'hello 1' - assert not hasattr(i1, 'HelloProperty') + assert type(i1).__name__ == "ISayHello1" + assert hasattr(i1, "SayHello") + assert i1.SayHello() == "hello 1" + assert not hasattr(i1, "HelloProperty") assert i1.__implementation__ == ob assert i1.__raw_implementation__ == ob i2 = Test.ISayHello2(ob) - assert type(i2).__name__ == 'ISayHello2' - assert i2.SayHello() == 'hello 2' - assert hasattr(i2, 'SayHello') - assert not hasattr(i2, 'HelloProperty') + assert type(i2).__name__ == "ISayHello2" + assert i2.SayHello() == "hello 2" + assert hasattr(i2, "SayHello") + assert not hasattr(i2, "HelloProperty") def test_interface_object_returned_through_method(): @@ -77,10 +78,10 @@ def test_interface_object_returned_through_method(): ob = InterfaceTest() hello1 = ob.GetISayHello1() - assert type(hello1).__name__ == 'ISayHello1' + assert type(hello1).__name__ == "ISayHello1" assert hello1.__implementation__.__class__.__name__ == "InterfaceTest" - assert hello1.SayHello() == 'hello 1' + assert hello1.SayHello() == "hello 1" def test_interface_object_returned_through_out_param(): @@ -89,9 +90,10 @@ def test_interface_object_returned_through_out_param(): ob = InterfaceTest() hello2 = ob.GetISayHello2(None) - assert type(hello2).__name__ == 'ISayHello2' + assert type(hello2).__name__ == "ISayHello2" + + assert hello2.SayHello() == "hello 2" - assert hello2.SayHello() == 'hello 2' def test_interface_out_param_python_impl(): from Python.Test import IOutArg, OutArgCaller @@ -101,7 +103,7 @@ class MyOutImpl(IOutArg): def MyMethod_Out(self, name, index): other_index = 101 - return ('MyName', other_index) + return ("MyName", other_index) py_impl = MyOutImpl() @@ -117,19 +119,22 @@ def test_null_interface_object_returned(): assert hello1 is None assert hello2 is None + def test_interface_array_returned(): """Test interface type used for methods returning interface arrays""" from Python.Test import InterfaceTest ob = InterfaceTest() hellos = ob.GetISayHello1Array() - assert type(hellos[0]).__name__ == 'ISayHello1' + assert type(hellos[0]).__name__ == "ISayHello1" assert hellos[0].__implementation__.__class__.__name__ == "InterfaceTest" + def test_implementation_access(): """Test the __implementation__ and __raw_implementation__ properties""" import System - clrVal = System.Int32(100) + + clrVal = System.Int32(100) i = System.IComparable(clrVal) assert 100 == i.__implementation__ assert clrVal == i.__raw_implementation__ @@ -140,6 +145,7 @@ def test_interface_collection_iteration(): """Test interface type is used when iterating over interface collection""" import System from System.Collections.Generic import List + elem = System.IComparable(System.Int32(100)) typed_list = List[System.IComparable]() typed_list.Add(elem) @@ -155,7 +161,8 @@ def test_interface_collection_iteration(): def test_methods_of_Object_are_available(): """Test calling methods inherited from Object""" import System - clrVal = System.Int32(100) + + clrVal = System.Int32(100) i = System.IComparable(clrVal) assert i.Equals(clrVal) assert clrVal.GetHashCode() == i.GetHashCode() diff --git a/tests/test_method.py b/tests/test_method.py index b86bbd6b4..661c344cc 100644 --- a/tests/test_method.py +++ b/tests/test_method.py @@ -6,6 +6,7 @@ import pytest from Python.Test import MethodTest + def test_instance_method_overwritable(): """Test instance method overwriting.""" @@ -110,7 +111,7 @@ def test_overloaded_method_inheritance(): def test_method_descriptor_abuse(): """Test method descriptor abuse.""" - desc = MethodTest.__dict__['PublicMethod'] + desc = MethodTest.__dict__["PublicMethod"] with pytest.raises(TypeError): desc.__get__(0, 0) @@ -122,7 +123,7 @@ def test_method_descriptor_abuse(): def test_method_docstrings(): """Test standard method docstring generation""" method = MethodTest.GetType - value = 'System.Type GetType()' + value = "System.Type GetType()" assert method.__doc__ == value @@ -180,36 +181,36 @@ def test_null_array_conversion(): def test_string_params_args(): """Test use of string params.""" - result = MethodTest.TestStringParamsArg('one', 'two', 'three') + result = MethodTest.TestStringParamsArg("one", "two", "three") assert result.Length == 4 assert len(result) == 4, result - assert result[0] == 'one' - assert result[1] == 'two' - assert result[2] == 'three' + assert result[0] == "one" + assert result[1] == "two" + assert result[2] == "three" # ensures params string[] overload takes precedence over params object[] - assert result[3] == 'tail' + assert result[3] == "tail" - result = MethodTest.TestStringParamsArg(['one', 'two', 'three']) + result = MethodTest.TestStringParamsArg(["one", "two", "three"]) assert len(result) == 4 - assert result[0] == 'one' - assert result[1] == 'two' - assert result[2] == 'three' - assert result[3] == 'tail' + assert result[0] == "one" + assert result[1] == "two" + assert result[2] == "three" + assert result[3] == "tail" def test_object_params_args(): """Test use of object params.""" - result = MethodTest.TestObjectParamsArg('one', 'two', 'three') + result = MethodTest.TestObjectParamsArg("one", "two", "three") assert len(result) == 3, result - assert result[0] == 'one' - assert result[1] == 'two' - assert result[2] == 'three' + assert result[0] == "one" + assert result[1] == "two" + assert result[2] == "three" - result = MethodTest.TestObjectParamsArg(['one', 'two', 'three']) + result = MethodTest.TestObjectParamsArg(["one", "two", "three"]) assert len(result) == 3, result - assert result[0] == 'one' - assert result[1] == 'two' - assert result[2] == 'three' + assert result[0] == "one" + assert result[1] == "two" + assert result[2] == "three" def test_value_params_args(): @@ -233,38 +234,42 @@ def test_non_params_array_in_last_place(): result = MethodTest.TestNonParamsArrayInLastPlace(1, 2, 3) assert result + def test_params_methods_with_no_params(): """Tests that passing no arguments to a params method passes an empty array""" result = MethodTest.TestValueParamsArg() assert len(result) == 0 - result = MethodTest.TestOneArgWithParams('Some String') + result = MethodTest.TestOneArgWithParams("Some String") assert len(result) == 0 - result = MethodTest.TestTwoArgWithParams('Some String', 'Some Other String') + result = MethodTest.TestTwoArgWithParams("Some String", "Some Other String") assert len(result) == 0 + def test_params_methods_with_non_lists(): """Tests that passing single parameters to a params method will convert into an array on the .NET side""" - result = MethodTest.TestOneArgWithParams('Some String', [1, 2, 3, 4]) + result = MethodTest.TestOneArgWithParams("Some String", [1, 2, 3, 4]) assert len(result) == 4 - result = MethodTest.TestOneArgWithParams('Some String', 1, 2, 3, 4) + result = MethodTest.TestOneArgWithParams("Some String", 1, 2, 3, 4) assert len(result) == 4 - result = MethodTest.TestOneArgWithParams('Some String', [5]) + result = MethodTest.TestOneArgWithParams("Some String", [5]) assert len(result) == 1 - result = MethodTest.TestOneArgWithParams('Some String', 5) + result = MethodTest.TestOneArgWithParams("Some String", 5) assert len(result) == 1 + def test_params_method_with_lists(): """Tests passing multiple lists to a params object[] method""" - result = MethodTest.TestObjectParamsArg([],[]) + result = MethodTest.TestObjectParamsArg([], []) assert len(result) == 2 + def test_string_out_params(): """Test use of string out-parameters.""" result = MethodTest.TestStringOutParams("hi", "there") @@ -468,15 +473,13 @@ def test_two_default_param(): def test_explicit_selection_with_out_modifier(): """Check explicit overload selection with out modifiers.""" refstr = System.String("").GetType().MakeByRefType() - result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( - "hi", "there") + result = MethodTest.TestStringOutParams.__overloads__[str, refstr]("hi", "there") assert isinstance(result, tuple) assert len(result) == 2 assert result[0] is True assert result[1] == "output string" - result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( - "hi", None) + result = MethodTest.TestStringOutParams.__overloads__[str, refstr]("hi", None) assert isinstance(result, tuple) assert len(result) == 2 assert result[0] is True @@ -486,15 +489,13 @@ def test_explicit_selection_with_out_modifier(): def test_explicit_selection_with_ref_modifier(): """Check explicit overload selection with ref modifiers.""" refstr = System.String("").GetType().MakeByRefType() - result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( - "hi", "there") + result = MethodTest.TestStringRefParams.__overloads__[str, refstr]("hi", "there") assert isinstance(result, tuple) assert len(result) == 2 assert result[0] is True assert result[1] == "output string" - result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( - "hi", None) + result = MethodTest.TestStringRefParams.__overloads__[str, refstr]("hi", None) assert isinstance(result, tuple) assert len(result) == 2 assert result[0] is True @@ -520,8 +521,8 @@ def test_explicit_overload_selection(): value = MethodTest.Overloaded.__overloads__[System.SByte](127) assert value == 127 - value = MethodTest.Overloaded.__overloads__[System.Char](u'A') - assert value == u'A' + value = MethodTest.Overloaded.__overloads__[System.Char]("A") + assert value == "A" value = MethodTest.Overloaded.__overloads__[System.Char](65535) assert value == chr(65535) @@ -535,37 +536,28 @@ def test_explicit_overload_selection(): value = MethodTest.Overloaded.__overloads__[int](2147483647) assert value == 2147483647 - value = MethodTest.Overloaded.__overloads__[System.Int64]( - 9223372036854775807 - ) + value = MethodTest.Overloaded.__overloads__[System.Int64](9223372036854775807) assert value == 9223372036854775807 value = MethodTest.Overloaded.__overloads__[System.UInt16](65000) assert value == 65000 - value = MethodTest.Overloaded.__overloads__[System.UInt32]( - 4294967295 - ) + value = MethodTest.Overloaded.__overloads__[System.UInt32](4294967295) assert value == 4294967295 - value = MethodTest.Overloaded.__overloads__[System.UInt64]( - 18446744073709551615 - ) + value = MethodTest.Overloaded.__overloads__[System.UInt64](18446744073709551615) assert value == 18446744073709551615 value = MethodTest.Overloaded.__overloads__[System.Single](3.402823e38) assert value == System.Single(3.402823e38) - value = MethodTest.Overloaded.__overloads__[System.Double]( - 1.7976931348623157e308) + value = MethodTest.Overloaded.__overloads__[System.Double](1.7976931348623157e308) assert value == 1.7976931348623157e308 - value = MethodTest.Overloaded.__overloads__[float]( - 1.7976931348623157e308) + value = MethodTest.Overloaded.__overloads__[float](1.7976931348623157e308) assert value == 1.7976931348623157e308 - value = MethodTest.Overloaded.__overloads__[System.Decimal]( - System.Decimal.One) + value = MethodTest.Overloaded.__overloads__[System.Decimal](System.Decimal.One) assert value == System.Decimal.One value = MethodTest.Overloaded.__overloads__[System.String]("spam") @@ -590,7 +582,8 @@ def test_explicit_overload_selection(): atype = Array[System.Object] value = MethodTest.Overloaded.__overloads__[str, int, atype]( - "one", 1, atype([1, 2, 3])) + "one", 1, atype([1, 2, 3]) + ) assert value == 3 value = MethodTest.Overloaded.__overloads__[str, int]("one", 1) @@ -632,10 +625,10 @@ def test_overload_selection_with_array_types(): assert value[1] == 127 vtype = Array[System.Char] - input_ = vtype([u'A', u'Z']) + input_ = vtype(["A", "Z"]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - assert value[0] == u'A' - assert value[1] == u'Z' + assert value[0] == "A" + assert value[1] == "Z" vtype = Array[System.Char] input_ = vtype([0, 65535]) @@ -769,7 +762,7 @@ def test_we_can_bind_to_encoding_get_string(): from System.Text import Encoding from System.IO import MemoryStream - my_bytes = Encoding.UTF8.GetBytes('Some testing string') + my_bytes = Encoding.UTF8.GetBytes("Some testing string") stream = MemoryStream() stream.Write(my_bytes, 0, my_bytes.Length) stream.Position = 0 @@ -784,8 +777,8 @@ def test_we_can_bind_to_encoding_get_string(): temp = Encoding.UTF8.GetString(buff, 0, read) data.append(temp) - data = ''.join(data) - assert data == 'Some testing string' + data = "".join(data) + assert data == "Some testing string" def test_wrong_overload(): @@ -795,23 +788,24 @@ def test_wrong_overload(): # Used to return `50L` res = System.Math.Abs(50.5) assert res == 50.5 - assert type(res) == float + assert type(res) == float # noqa: E721 res = System.Math.Abs(-50.5) assert res == 50.5 - assert type(res) == float + assert type(res) == float # noqa: E721 res = System.Math.Max(50.5, 50.1) assert res == 50.5 - assert type(res) == float + assert type(res) == float # noqa: E721 res = System.Math.Max(System.Double(10.5), System.Double(50.5)) assert res == 50.5 - assert type(res) == float # Should it return a System.Double? + # Should it return a System.Double? + assert type(res) == float # noqa: E721 res = System.Math.Max(System.Double(50.5), 50.1) assert res == 50.5 - assert type(res) == float + assert type(res) == float # noqa: E721 def test_no_object_in_param(): @@ -833,6 +827,7 @@ def test_no_object_in_param(): with pytest.raises(TypeError): MethodTest.TestOverloadedNoObject(2147483648) + def test_object_in_param(): """Test regression introduced by #151 in which Object method overloads aren't being used. See #203 for issue.""" @@ -916,9 +911,10 @@ def test_object_in_multiparam_exception(): e = excinfo.value c = e.__cause__ - assert c.GetType().FullName == 'System.AggregateException' + assert c.GetType().FullName == "System.AggregateException" assert len(c.InnerExceptions) == 2 + def test_case_sensitive(): """Test that case-sensitivity is respected. GH#81""" @@ -931,6 +927,7 @@ def test_case_sensitive(): with pytest.raises(AttributeError): MethodTest.casesensitive() + def test_getting_generic_method_binding_does_not_leak_ref_count(): """Test that managed object is freed after calling generic method. Issue #691""" @@ -941,16 +938,22 @@ def test_getting_generic_method_binding_does_not_leak_ref_count(): refCount = sys.getrefcount(PlainOldClass().GenericMethod[str]) assert refCount == 1 + def test_getting_generic_method_binding_does_not_leak_memory(): """Test that managed object is freed after calling generic method. Issue #691""" from PlainOldNamespace import PlainOldClass - import psutil, os, gc, clr + import psutil + import os + import gc process = psutil.Process(os.getpid()) processBytesBeforeCall = process.memory_info().rss - print("\n\nMemory consumption (bytes) at start of test: " + str(processBytesBeforeCall)) + print( + "\n\nMemory consumption (bytes) at start of test: " + + str(processBytesBeforeCall) + ) iterations = 500 for i in range(iterations): @@ -972,6 +975,7 @@ def test_getting_generic_method_binding_does_not_leak_memory(): assert bytesLeakedPerIteration < failThresholdBytesLeakedPerIteration + def test_getting_overloaded_method_binding_does_not_leak_ref_count(): """Test that managed object is freed after calling overloaded method. Issue #691""" @@ -982,16 +986,22 @@ def test_getting_overloaded_method_binding_does_not_leak_ref_count(): refCount = sys.getrefcount(PlainOldClass().OverloadedMethod.Overloads[int]) assert refCount == 1 + def test_getting_overloaded_method_binding_does_not_leak_memory(): """Test that managed object is freed after calling overloaded method. Issue #691""" from PlainOldNamespace import PlainOldClass - import psutil, os, gc, clr + import psutil + import os + import gc process = psutil.Process(os.getpid()) processBytesBeforeCall = process.memory_info().rss - print("\n\nMemory consumption (bytes) at start of test: " + str(processBytesBeforeCall)) + print( + "\n\nMemory consumption (bytes) at start of test: " + + str(processBytesBeforeCall) + ) iterations = 500 for i in range(iterations): @@ -1013,6 +1023,7 @@ def test_getting_overloaded_method_binding_does_not_leak_memory(): assert bytesLeakedPerIteration < failThresholdBytesLeakedPerIteration + def test_getting_method_overloads_binding_does_not_leak_ref_count(): """Test that managed object is freed after calling overloaded method. Issue #691""" @@ -1023,16 +1034,22 @@ def test_getting_method_overloads_binding_does_not_leak_ref_count(): refCount = sys.getrefcount(PlainOldClass().OverloadedMethod.Overloads) assert refCount == 1 + def test_getting_method_overloads_binding_does_not_leak_memory(): """Test that managed object is freed after calling overloaded method. Issue #691""" from PlainOldNamespace import PlainOldClass - import psutil, os, gc, clr + import psutil + import os + import gc process = psutil.Process(os.getpid()) processBytesBeforeCall = process.memory_info().rss - print("\n\nMemory consumption (bytes) at start of test: " + str(processBytesBeforeCall)) + print( + "\n\nMemory consumption (bytes) at start of test: " + + str(processBytesBeforeCall) + ) iterations = 500 for i in range(iterations): @@ -1054,6 +1071,7 @@ def test_getting_method_overloads_binding_does_not_leak_memory(): assert bytesLeakedPerIteration < failThresholdBytesLeakedPerIteration + def test_getting_overloaded_constructor_binding_does_not_leak_ref_count(): """Test that managed object is freed after calling overloaded constructor, constructorbinding.cs mp_subscript. Issue #691""" @@ -1068,7 +1086,7 @@ def test_getting_overloaded_constructor_binding_does_not_leak_ref_count(): def test_default_params(): # all positional parameters - res = MethodTest.DefaultParams(1,2,3,4) + res = MethodTest.DefaultParams(1, 2, 3, 4) assert res == "1234" res = MethodTest.DefaultParams(1, 2, 3) @@ -1099,7 +1117,8 @@ def test_default_params(): assert res == "1037" with pytest.raises(TypeError): - MethodTest.DefaultParams(1,2,3,4,5) + MethodTest.DefaultParams(1, 2, 3, 4, 5) + def test_optional_params(): res = MethodTest.OptionalParams(1, 2, 3, 4) @@ -1133,34 +1152,34 @@ def test_optional_params(): assert res == "1037" res = MethodTest.OptionalParams_TestMissing() - assert res == True + assert res == True # noqa: E712 res = MethodTest.OptionalParams_TestMissing(None) - assert res == False + assert res == False # noqa: E712 - res = MethodTest.OptionalParams_TestMissing(a = None) - assert res == False + res = MethodTest.OptionalParams_TestMissing(a=None) + assert res == False # noqa: E712 - res = MethodTest.OptionalParams_TestMissing(a='hi') - assert res == False + res = MethodTest.OptionalParams_TestMissing(a="hi") + assert res == False # noqa: E712 res = MethodTest.OptionalParams_TestReferenceType() - assert res == True + assert res == True # noqa: E712 res = MethodTest.OptionalParams_TestReferenceType(None) - assert res == True + assert res == True # noqa: E712 res = MethodTest.OptionalParams_TestReferenceType(a=None) - assert res == True + assert res == True # noqa: E712 - res = MethodTest.OptionalParams_TestReferenceType('hi') - assert res == False + res = MethodTest.OptionalParams_TestReferenceType("hi") + assert res == False # noqa: E712 - res = MethodTest.OptionalParams_TestReferenceType(a='hi') - assert res == False + res = MethodTest.OptionalParams_TestReferenceType(a="hi") + assert res == False # noqa: E712 -def test_optional_and_default_params(): +def test_optional_and_default_params(): res = MethodTest.OptionalAndDefaultParams() assert res == "0000" @@ -1176,12 +1195,13 @@ def test_optional_and_default_params(): res = MethodTest.OptionalAndDefaultParams2() assert res == "0012" - res = MethodTest.OptionalAndDefaultParams2(a=1,b=2,c=3,d=4) + res = MethodTest.OptionalAndDefaultParams2(a=1, b=2, c=3, d=4) assert res == "1234" res = MethodTest.OptionalAndDefaultParams2(b=2, c=3) assert res == "0232" + def test_default_params_overloads(): res = MethodTest.DefaultParamsWithOverloading(1, 2) assert res == "12" @@ -1207,16 +1227,19 @@ def test_default_params_overloads(): res = MethodTest.DefaultParamsWithOverloading(1, d=1) assert res == "1671XXX" + def test_default_params_overloads_ambiguous_call(): with pytest.raises(TypeError): MethodTest.DefaultParamsWithOverloading() + def test_keyword_arg_method_resolution(): from Python.Test import MethodArityTest ob = MethodArityTest() assert ob.Foo(1, b=2) == "Arity 2" + def test_params_array_overload(): res = MethodTest.ParamsArrayOverloaded() assert res == "without params-array" @@ -1242,6 +1265,7 @@ def test_params_array_overload(): res = MethodTest.ParamsArrayOverloaded(1, 2, 3, i=1) assert res == "with params-array" + @pytest.mark.skip(reason="FIXME: incorrectly failing") def test_params_array_overloaded_failing(): res = MethodTest.ParamsArrayOverloaded(1, 2, i=1) @@ -1250,15 +1274,17 @@ def test_params_array_overloaded_failing(): res = MethodTest.ParamsArrayOverloaded(paramsArray=[], i=1) assert res == "with params-array" + def test_method_encoding(): MethodTest.EncodingTestÅngström() + def test_method_with_pointer_array_argument(): with pytest.raises(TypeError): MethodTest.PointerArray([0]) -def test_method_call_implicit_conversion(): +def test_method_call_implicit_conversion(): class IntAnswerMixin: # For Python >= 3.8 def __index__(self): diff --git a/tests/test_module.py b/tests/test_module.py index ddfa7bb36..9e62154f8 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -16,26 +16,29 @@ # testImplicitAssemblyLoad() passes on deprecation warning; perfect! # # clr.AddReference('System.Windows.Forms') + def test_import_hook_works(): """Test that the import hook works correctly both using the - included runtime and an external runtime. This must be - the first test run in the unit tests!""" - from System import String + included runtime and an external runtime. This must be + the first test run in the unit tests!""" def test_import_clr(): import clr + assert is_clr_root_module(clr) def test_version_clr(): import clr + assert clr.__version__ >= "3.0.0" assert clr.__version__[-1] != "\n" def test_preload_var(): import clr + assert clr.getPreload() is False, clr.getPreload() clr.setPreload(False) assert clr.getPreload() is False, clr.getPreload() @@ -44,6 +47,7 @@ def test_preload_var(): assert clr.getPreload() is True, clr.getPreload() import System.Configuration + content = dir(System.Configuration) assert len(content) > 10, content finally: @@ -53,14 +57,18 @@ def test_preload_var(): def test_module_interface(): """Test the interface exposed by CLR module objects.""" import System - assert type(System.__dict__) == type({}) - assert System.__name__ == 'System' + + assert isinstance(System.__dict__, dict) + assert System.__name__ == "System" # the filename can be any module from the System namespace # (eg System.Data.dll or System.dll, but also mscorlib.dll) system_file = System.__file__ - assert fnmatch(system_file, "*System*.dll") or fnmatch(system_file, "*mscorlib.dll"), \ - "unexpected System.__file__: " + system_file - assert System.__doc__.startswith("Namespace containing types from the following assemblies:") + assert fnmatch(system_file, "*System*.dll") or fnmatch( + system_file, "*mscorlib.dll" + ), "unexpected System.__file__: " + system_file + assert System.__doc__.startswith( + "Namespace containing types from the following assemblies:" + ) assert is_clr_class(System.String) assert is_clr_class(System.Int32) @@ -68,124 +76,148 @@ def test_module_interface(): def test_simple_import(): """Test simple import.""" import System + assert is_clr_module(System) - assert System.__name__ == 'System' + assert System.__name__ == "System" import sys + assert isinstance(sys, types.ModuleType) - assert sys.__name__ == 'sys' + assert sys.__name__ == "sys" import http.client as httplib + assert isinstance(httplib, types.ModuleType) - assert httplib.__name__ == 'http.client' + assert httplib.__name__ == "http.client" def test_simple_import_with_alias(): """Test simple import with aliasing.""" import System as mySystem + assert is_clr_module(mySystem) - assert mySystem.__name__ == 'System' + assert mySystem.__name__ == "System" import sys as mySys + assert isinstance(mySys, types.ModuleType) - assert mySys.__name__ == 'sys' + assert mySys.__name__ == "sys" import http.client as myHttplib + assert isinstance(myHttplib, types.ModuleType) - assert myHttplib.__name__ == 'http.client' + assert myHttplib.__name__ == "http.client" def test_dotted_name_import(): """Test dotted-name import.""" import System.Reflection + assert is_clr_module(System.Reflection) - assert System.Reflection.__name__ == 'System.Reflection' + assert System.Reflection.__name__ == "System.Reflection" import xml.dom + assert isinstance(xml.dom, types.ModuleType) - assert xml.dom.__name__ == 'xml.dom' + assert xml.dom.__name__ == "xml.dom" def test_multiple_dotted_name_import(): """Test an import bug with multiple dotted imports.""" import System.Reflection + assert is_clr_module(System.Reflection) - assert System.Reflection.__name__ == 'System.Reflection' + assert System.Reflection.__name__ == "System.Reflection" import System.Reflection + assert is_clr_module(System.Reflection) - assert System.Reflection.__name__ == 'System.Reflection' + assert System.Reflection.__name__ == "System.Reflection" def test_dotted_name_import_with_alias(): """Test dotted-name import with aliasing.""" import System.Reflection as SysRef + assert is_clr_module(SysRef) - assert SysRef.__name__ == 'System.Reflection' + assert SysRef.__name__ == "System.Reflection" import xml.dom as myDom + assert isinstance(myDom, types.ModuleType) - assert myDom.__name__ == 'xml.dom' + assert myDom.__name__ == "xml.dom" def test_simple_import_from(): """Test simple 'import from'.""" from System import Reflection + assert is_clr_module(Reflection) - assert Reflection.__name__ == 'System.Reflection' + assert Reflection.__name__ == "System.Reflection" from xml import dom + assert isinstance(dom, types.ModuleType) - assert dom.__name__ == 'xml.dom' + assert dom.__name__ == "xml.dom" def test_simple_import_from_with_alias(): """Test simple 'import from' with aliasing.""" from System import Collections as Coll + assert is_clr_module(Coll) - assert Coll.__name__ == 'System.Collections' + assert Coll.__name__ == "System.Collections" from xml import dom as myDom + assert isinstance(myDom, types.ModuleType) - assert myDom.__name__ == 'xml.dom' + assert myDom.__name__ == "xml.dom" def test_dotted_name_import_from(): """Test dotted-name 'import from'.""" from System.Collections import Specialized + assert is_clr_module(Specialized) - assert Specialized.__name__ == 'System.Collections.Specialized' + assert Specialized.__name__ == "System.Collections.Specialized" from System.Collections.Specialized import StringCollection + assert is_clr_class(StringCollection) - assert StringCollection.__name__ == 'StringCollection' + assert StringCollection.__name__ == "StringCollection" from xml.dom import pulldom + assert isinstance(pulldom, types.ModuleType) - assert pulldom.__name__ == 'xml.dom.pulldom' + assert pulldom.__name__ == "xml.dom.pulldom" from xml.dom.pulldom import PullDOM + assert isinstance(PullDOM, type) - assert PullDOM.__name__ == 'PullDOM' + assert PullDOM.__name__ == "PullDOM" def test_dotted_name_import_from_with_alias(): """Test dotted-name 'import from' with aliasing.""" from System.Collections import Specialized as Spec + assert is_clr_module(Spec) - assert Spec.__name__ == 'System.Collections.Specialized' + assert Spec.__name__ == "System.Collections.Specialized" from System.Collections.Specialized import StringCollection as SC + assert is_clr_class(SC) - assert SC.__name__ == 'StringCollection' + assert SC.__name__ == "StringCollection" from xml.dom import pulldom as myPulldom + assert isinstance(myPulldom, types.ModuleType) - assert myPulldom.__name__ == 'xml.dom.pulldom' + assert myPulldom.__name__ == "xml.dom.pulldom" from xml.dom.pulldom import PullDOM as myPullDOM + assert isinstance(myPullDOM, type) - assert myPullDOM.__name__ == 'PullDOM' + assert myPullDOM.__name__ == "PullDOM" def test_from_module_import_star(): @@ -193,8 +225,8 @@ def test_from_module_import_star(): clr.AddReference("System") count = len(locals().keys()) - m = __import__('System', globals(), locals(), ['*']) - assert m.__name__ == 'System' + m = __import__("System", globals(), locals(), ["*"]) + assert m.__name__ == "System" assert is_clr_module(m) assert len(locals().keys()) > count + 1 @@ -207,7 +239,7 @@ def test_implicit_assembly_load(): # The implicit behavior has been disabled in 3.0 # therefore this should fail - import Microsoft.Build + pass with warnings.catch_warnings(record=True) as w: try: @@ -216,26 +248,27 @@ def test_implicit_assembly_load(): pytest.skip() import System.Windows.Forms as Forms + assert is_clr_module(Forms) - assert Forms.__name__ == 'System.Windows.Forms' + assert Forms.__name__ == "System.Windows.Forms" from System.Windows.Forms import Form + assert is_clr_class(Form) - assert Form.__name__ == 'Form' + assert Form.__name__ == "Form" assert len(w) == 0 def test_explicit_assembly_load(): """Test explicit assembly loading using standard CLR tools.""" from System.Reflection import Assembly - import System, sys + import sys - assembly = Assembly.LoadWithPartialName('Microsoft.CSharp') + assembly = Assembly.LoadWithPartialName("Microsoft.CSharp") assert assembly is not None - import Microsoft.CSharp - assert 'Microsoft.CSharp' in sys.modules + assert "Microsoft.CSharp" in sys.modules - assembly = Assembly.LoadWithPartialName('SpamSpamSpamSpamEggsAndSpam') + assembly = Assembly.LoadWithPartialName("SpamSpamSpamSpamEggsAndSpam") assert assembly is None @@ -248,19 +281,20 @@ def test_implicit_load_already_valid_namespace(): # Python runtime to "do the right thing", allowing types from both # assemblies to be found in the System module implicitly. import System + assert is_clr_class(System.UriBuilder) def test_import_non_existant_module(): """Test import failure for a non-existent module.""" with pytest.raises(ImportError): - import System.SpamSpamSpam + pass def test_lookup_no_namespace_type(): """Test lookup of types without a qualified namespace.""" - import Python.Test import clr + assert is_clr_class(clr.NoNamespaceType) @@ -268,11 +302,12 @@ def test_module_lookup_recursion(): """Test for recursive lookup handling.""" with pytest.raises(ImportError): - from System import System + from System import System # noqa F401 with pytest.raises(AttributeError): - import System - _ = System.System + import System as System2 + + _ = System2.System def test_module_get_attr(): @@ -303,7 +338,8 @@ def test_module_attr_abuse(): def test(): import System - System.__dict__['foo'] = 0 + + System.__dict__["foo"] = 0 return 1 assert test() @@ -312,13 +348,14 @@ def test(): def test_module_type_abuse(): """Test handling of attempts to break the module type.""" import System + mtype = type(System) with pytest.raises(TypeError): - mtype.__getattribute__(0, 'spam') + mtype.__getattribute__(0, "spam") with pytest.raises(TypeError): - mtype.__setattr__(0, 'spam', 1) + mtype.__setattr__(0, "spam", 1) with pytest.raises(TypeError): mtype.__repr__(0) @@ -326,16 +363,18 @@ def test_module_type_abuse(): def test_clr_list_assemblies(): from clr import ListAssemblies + verbose = list(ListAssemblies(True)) short = list(ListAssemblies(False)) - assert u'System' in short - assert u'Culture=' in verbose[0] - assert u'Version=' in verbose[0] + assert "System" in short + assert "Culture=" in verbose[0] + assert "Version=" in verbose[0] def test_clr_add_reference(): from clr import AddReference from System.IO import FileNotFoundException + for name in ("System", "Python.Runtime"): assy = AddReference(name) assy_name = assy.GetName().Name @@ -344,12 +383,13 @@ def test_clr_add_reference(): with pytest.raises(FileNotFoundException): AddReference("somethingtotallysilly") + def test_clr_get_clr_type(): """Test clr.GetClrType().""" from clr import GetClrType import System from System import IComparable - from System import ArgumentException + assert GetClrType(System.String).FullName == "System.String" comparable = GetClrType(IComparable) assert comparable.FullName == "System.IComparable" @@ -365,21 +405,25 @@ def test_clr_get_clr_type(): with pytest.raises(TypeError): GetClrType("thiswillfail") + def test_assembly_load_thread_safety(): from Python.Test import ModuleTest + # spin up .NET thread which loads assemblies and triggers AppDomain.AssemblyLoad event ModuleTest.RunThreads() time.sleep(1e-5) for _ in range(1, 100): # call import clr, which in AssemblyManager.GetNames iterates through the loaded types - import clr + # import some .NET types from System import DateTime from System import Guid from System.Collections.Generic import Dictionary + _ = Dictionary[Guid, DateTime]() ModuleTest.JoinThreads() + @pytest.mark.skipif() def test_assembly_load_recursion_bug(): """Test fix for recursion bug documented in #627""" diff --git a/tests/test_mp_length.py b/tests/test_mp_length.py index e86fff288..b827bc28b 100644 --- a/tests/test_mp_length.py +++ b/tests/test_mp_length.py @@ -1,63 +1,75 @@ -# -*- coding: utf-8 -*- - -"""Test __len__ for .NET classes implementing ICollection/ICollection.""" - -import System -import pytest -from Python.Test import MpLengthCollectionTest, MpLengthExplicitCollectionTest, MpLengthGenericCollectionTest, MpLengthExplicitGenericCollectionTest - -def test_simple___len__(): - """Test __len__ for simple ICollection implementers""" - import System - import System.Collections.Generic - l = System.Collections.Generic.List[int]() - assert len(l) == 0 - l.Add(5) - l.Add(6) - assert len(l) == 2 - - d = System.Collections.Generic.Dictionary[int, int]() - assert len(d) == 0 - d.Add(4, 5) - assert len(d) == 1 - - a = System.Array[int]([0,1,2,3]) - assert len(a) == 4 - -def test_custom_collection___len__(): - """Test __len__ for custom collection class""" - s = MpLengthCollectionTest() - assert len(s) == 3 - -def test_custom_collection_explicit___len__(): - """Test __len__ for custom collection class that explicitly implements ICollection""" - s = MpLengthExplicitCollectionTest() - assert len(s) == 2 - -def test_custom_generic_collection___len__(): - """Test __len__ for custom generic collection class""" - s = MpLengthGenericCollectionTest[int]() - s.Add(1) - s.Add(2) - assert len(s) == 2 - -def test_custom_generic_collection_explicit___len__(): - """Test __len__ for custom generic collection that explicity implements ICollection""" - s = MpLengthExplicitGenericCollectionTest[int]() - s.Add(1) - s.Add(10) - assert len(s) == 2 - -def test_len_through_interface_generic(): - """Test __len__ for ICollection""" - import System.Collections.Generic - l = System.Collections.Generic.List[int]() - coll = System.Collections.Generic.ICollection[int](l) - assert len(coll) == 0 - -def test_len_through_interface(): - """Test __len__ for ICollection""" - import System.Collections - l = System.Collections.ArrayList() - coll = System.Collections.ICollection(l) - assert len(coll) == 0 +# -*- coding: utf-8 -*- + +"""Test __len__ for .NET classes implementing ICollection/ICollection.""" + +from Python.Test import ( + MpLengthCollectionTest, + MpLengthExplicitCollectionTest, + MpLengthGenericCollectionTest, + MpLengthExplicitGenericCollectionTest, +) + + +def test_simple___len__(): + """Test __len__ for simple ICollection implementers""" + import System.Collections.Generic + + lst = System.Collections.Generic.List[int]() + assert len(lst) == 0 + lst.Add(5) + lst.Add(6) + assert len(lst) == 2 + + dct = System.Collections.Generic.Dictionary[int, int]() + assert len(dct) == 0 + dct.Add(4, 5) + assert len(dct) == 1 + + arr = System.Array[int]([0, 1, 2, 3]) + assert len(arr) == 4 + + +def test_custom_collection___len__(): + """Test __len__ for custom collection class""" + s = MpLengthCollectionTest() + assert len(s) == 3 + + +def test_custom_collection_explicit___len__(): + """Test __len__ for custom collection class that explicitly implements ICollection""" + s = MpLengthExplicitCollectionTest() + assert len(s) == 2 + + +def test_custom_generic_collection___len__(): + """Test __len__ for custom generic collection class""" + s = MpLengthGenericCollectionTest[int]() + s.Add(1) + s.Add(2) + assert len(s) == 2 + + +def test_custom_generic_collection_explicit___len__(): + """Test __len__ for custom generic collection that explicity implements ICollection""" + s = MpLengthExplicitGenericCollectionTest[int]() + s.Add(1) + s.Add(10) + assert len(s) == 2 + + +def test_len_through_interface_generic(): + """Test __len__ for ICollection""" + import System.Collections.Generic + + lst = System.Collections.Generic.List[int]() + coll = System.Collections.Generic.ICollection[int](lst) + assert len(coll) == 0 + + +def test_len_through_interface(): + """Test __len__ for ICollection""" + import System.Collections + + lst = System.Collections.ArrayList() + coll = System.Collections.ICollection(lst) + assert len(coll) == 0 diff --git a/tests/test_property.py b/tests/test_property.py index 4dc8ea111..0ee10281f 100644 --- a/tests/test_property.py +++ b/tests/test_property.py @@ -106,16 +106,16 @@ def test_property_descriptor_get_set(): assert PropertyTest.PublicStaticProperty == 0 assert ob.PublicStaticProperty == 0 - descriptor = PropertyTest.__dict__['PublicStaticProperty'] - assert type(descriptor) != int + descriptor = PropertyTest.__dict__["PublicStaticProperty"] + assert type(descriptor) != int # noqa: E721 ob.PublicStaticProperty = 0 - descriptor = PropertyTest.__dict__['PublicStaticProperty'] - assert type(descriptor) != int + descriptor = PropertyTest.__dict__["PublicStaticProperty"] + assert type(descriptor) != int # noqa: E721 PropertyTest.PublicStaticProperty = 0 - descriptor = PropertyTest.__dict__['PublicStaticProperty'] - assert type(descriptor) != int + descriptor = PropertyTest.__dict__["PublicStaticProperty"] + assert type(descriptor) != int # noqa: E721 def test_property_descriptor_wrong_type(): @@ -128,7 +128,7 @@ def test_property_descriptor_wrong_type(): def test_property_descriptor_abuse(): """Test property descriptor abuse.""" - desc = PropertyTest.__dict__['PublicProperty'] + desc = PropertyTest.__dict__["PublicProperty"] with pytest.raises(TypeError): desc.__get__(0, 0) @@ -139,8 +139,8 @@ def test_property_descriptor_abuse(): def test_interface_property(): """Test properties of interfaces. Added after a bug report - that an IsAbstract check was inappropriate and prevented - use of properties when only the interface is known.""" + that an IsAbstract check was inappropriate and prevented + use of properties when only the interface is known.""" from System.Collections import Hashtable, ICollection mapping = Hashtable() diff --git a/tests/test_repr.py b/tests/test_repr.py index 5131f5d88..57bff3596 100644 --- a/tests/test_repr.py +++ b/tests/test_repr.py @@ -6,63 +6,67 @@ import pytest from Python.Test import ReprTest + def test_basic(): """Test Point class which implements both ToString and __repr__ without inheritance""" - ob = ReprTest.Point(1,2) + ob = ReprTest.Point(1, 2) # point implements ToString() and __repr__() - assert ob.__repr__() == "Point(1,2)" + assert repr(ob) == "Point(1,2)" assert str(ob) == "Python.Test.ReprTest+Point: X=1, Y=2" + def test_system_string(): """Test system string""" ob = System.String("hello") assert str(ob) == "hello" - assert "