From cdb9a42d6168811885d87f2f07f00e729f93af6e Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 12 Jan 2017 13:58:27 -0700 Subject: [PATCH 001/245] Remove unreachable code from PY32 That entire section is only for PY32 compatiblity --- src/runtime/runtime.cs | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 80f62df49..b7451ecd1 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1563,27 +1563,11 @@ internal static IntPtr PyString_FromStringAndSize(string value, int length) } } -#if (PYTHON33 || PYTHON34 || PYTHON35 || PYTHON36) [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, int size); -#elif (UCS2) - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_FromStringAndSize", - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromStringAndSize(IntPtr value, int size); -#else - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_FromStringAndSize", - ExactSpelling = true, CharSet = CharSet.Ansi)] - internal unsafe static extern IntPtr - PyUnicode_FromStringAndSize(IntPtr value, int size); -#endif - -#else // Python2x - +#elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr From 5357401a4158d222582fbb18bd715e2f188cdbb6 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 12 Jan 2017 14:05:50 -0700 Subject: [PATCH 002/245] Refactor repeated section from UCS4/UCS2 --- src/runtime/runtime.cs | 42 ++++++++---------------------------------- 1 file changed, 8 insertions(+), 34 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index b7451ecd1..46a0d2d91 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1677,37 +1677,6 @@ internal unsafe static extern IntPtr internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #endif - - internal static IntPtr PyUnicode_FromString(string s) - { - return PyUnicode_FromUnicode(s, (s.Length)); - } - - internal unsafe static string GetManagedString(IntPtr op) - { - IntPtr type = PyObject_TYPE(op); - -// Python 3 strings are all unicode -#if PYTHON2 - if (type == Runtime.PyStringType) - { - return Marshal.PtrToStringAnsi( - PyString_AS_STRING(op), - Runtime.PyString_Size(op) - ); - } -#endif - - if (type == Runtime.PyUnicodeType) - { - char* p = Runtime.PyUnicode_AsUnicode(op); - int size = Runtime.PyUnicode_GetSize(op); - return new String(p, 0, size); - } - - return null; - } - #endif #if (UCS4) #if (PYTHON33 || PYTHON34 || PYTHON35 || PYTHON36) @@ -1800,6 +1769,7 @@ internal unsafe static extern IntPtr internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); +#endif #endif internal static IntPtr PyUnicode_FromString(string s) @@ -1811,8 +1781,7 @@ internal unsafe static string GetManagedString(IntPtr op) { IntPtr type = PyObject_TYPE(op); -// Python 3 strings are all unicode -#if PYTHON2 +#if PYTHON2 // Python 3 strings are all Unicode if (type == Runtime.PyStringType) { return Marshal.PtrToStringAnsi( @@ -1824,17 +1793,22 @@ internal unsafe static string GetManagedString(IntPtr op) if (type == Runtime.PyUnicodeType) { +#if UCS4 IntPtr p = Runtime.PyUnicode_AsUnicode(op); int length = Runtime.PyUnicode_GetSize(op); int size = length*4; byte[] buffer = new byte[size]; Marshal.Copy(p, buffer, 0, size); return Encoding.UTF32.GetString(buffer, 0, size); +#elif UCS2 + char* p = Runtime.PyUnicode_AsUnicode(op); + int size = Runtime.PyUnicode_GetSize(op); + return new String(p, 0, size); +#endif } return null; } -#endif //==================================================================== // Python dictionary API From 4f298019722c3b71a3dccfa4ea0ceff9ff1a8b1d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 29 Jan 2017 13:24:47 -0700 Subject: [PATCH 003/245] Clarify nested UCS2/4 PY2/3 directives Clearly shows what each section does --- src/runtime/runtime.cs | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 46a0d2d91..84f237f30 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1590,8 +1590,7 @@ internal static bool PyUnicode_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyUnicodeType; } -#if (UCS2) -#if (PYTHON33 || PYTHON34 || PYTHON35 || PYTHON36) +#if UCS2 && PYTHON3 [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, ExactSpelling=true, CharSet=CharSet.Unicode)] internal unsafe static extern IntPtr @@ -1633,8 +1632,7 @@ internal unsafe static extern IntPtr ExactSpelling = true, CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); - -#else +#elif UCS2 && PYTHON2 [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, EntryPoint="PyUnicodeUCS2_FromObject", ExactSpelling=true, CharSet=CharSet.Unicode)] @@ -1676,10 +1674,7 @@ internal unsafe static extern IntPtr ExactSpelling=true, CharSet=CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); -#endif -#endif -#if (UCS4) -#if (PYTHON33 || PYTHON34 || PYTHON35 || PYTHON36) +#elif UCS4 && PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling=true, CharSet=CharSet.Unicode)] internal unsafe static extern IntPtr @@ -1723,8 +1718,7 @@ internal unsafe static extern IntPtr ExactSpelling = true, CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); - -#else +#elif UCS4 && PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS4_FromObject", ExactSpelling = true, CharSet = CharSet.Unicode)] @@ -1768,8 +1762,6 @@ internal unsafe static extern IntPtr ExactSpelling = true, CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); - -#endif #endif internal static IntPtr PyUnicode_FromString(string s) From 94b9e257eda8a6ce9af08091f3eea8f8ec9201d4 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 29 Jan 2017 13:40:28 -0700 Subject: [PATCH 004/245] Refactor Python version directives Added Python37 definition, won't add interop until final release --- src/runtime/assemblyinfo.cs | 15 +++--- src/runtime/runtime.cs | 96 +++++++++++-------------------------- 2 files changed, 35 insertions(+), 76 deletions(-) diff --git a/src/runtime/assemblyinfo.cs b/src/runtime/assemblyinfo.cs index 49433f0dc..1defa851f 100644 --- a/src/runtime/assemblyinfo.cs +++ b/src/runtime/assemblyinfo.cs @@ -15,20 +15,19 @@ #if PYTHON27 [assembly: AssemblyTitle("Python.Runtime for Python 2.7")] [assembly: AssemblyDescription("Python Runtime for Python 2.7")] -#endif -#if PYTHON33 +#elif PYTHON33 [assembly: AssemblyTitle("Python.Runtime for Python 3.3")] [assembly: AssemblyDescription("Python Runtime for Python 3.3")] -#endif -#if PYTHON34 +#elif PYTHON34 [assembly: AssemblyTitle("Python.Runtime for Python 3.4")] [assembly: AssemblyDescription("Python Runtime for Python 3.4")] -#endif -#if PYTHON35 +#elif PYTHON35 [assembly: AssemblyTitle("Python.Runtime for Python 3.5")] [assembly: AssemblyDescription("Python Runtime for Python 3.5")] -#endif -#if PYTHON36 +#elif PYTHON36 [assembly: AssemblyTitle("Python.Runtime for Python 3.6")] [assembly: AssemblyDescription("Python Runtime for Python 3.6")] +#elif PYTHON37 +[assembly: AssemblyTitle("Python.Runtime for Python 3.7")] +[assembly: AssemblyDescription("Python Runtime for Python 3.7")] #endif diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 84f237f30..4a67e8c65 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -103,96 +103,56 @@ public class Runtime #error You must define either UCS2 or UCS4! #endif -#if (PYTHON23) - public const string pyversion = "2.3"; - public const int pyversionnumber = 23; -#endif -#if (PYTHON24) - public const string pyversion = "2.4"; - public const int pyversionnumber = 24; -#endif -#if (PYTHON25) - public const string pyversion = "2.5"; - public const int pyversionnumber = 25; -#endif -#if (PYTHON26) - public const string pyversion = "2.6"; - public const int pyversionnumber = 26; -#endif -#if (PYTHON27) +#if PYTHON27 public const string pyversion = "2.7"; public const int pyversionnumber = 27; -#endif -#if (PYTHON32) - public const string pyversion = "3.2"; - public const int pyversionnumber = 32; -#endif -#if (PYTHON33) +#elif PYTHON33 public const string pyversion = "3.3"; public const int pyversionnumber = 33; -#endif -#if (PYTHON34) +#elif PYTHON34 public const string pyversion = "3.4"; public const int pyversionnumber = 34; -#endif -#if (PYTHON35) +#elif PYTHON35 public const string pyversion = "3.5"; public const int pyversionnumber = 35; -#endif -#if (PYTHON36) +#elif PYTHON36 public const string pyversion = "3.6"; public const int pyversionnumber = 36; -#endif -#if ! (PYTHON23 || PYTHON24 || PYTHON25 || PYTHON26 || PYTHON27 || PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35 || PYTHON36) -#error You must define one of PYTHON23 to PYTHON36 +#elif PYTHON37 + // TODO: Add interop37 after Python3.7 is released + public const string pyversion = "3.7"; + public const int pyversionnumber = 37; +#else +#error You must define one of PYTHON33 to PYTHON37 or PYTHON27 #endif -#if (PYTHON23) - internal const string dllBase = "python23"; -#endif -#if (PYTHON24) - internal const string dllBase = "python24"; -#endif -#if (PYTHON25) - internal const string dllBase = "python25"; -#endif -#if (PYTHON26) - internal const string dllBase = "python26"; -#endif -#if (PYTHON27) +#if MONO_LINUX || MONO_OSX +#if PYTHON27 internal const string dllBase = "python27"; -#endif -#if (MONO_LINUX || MONO_OSX) -#if (PYTHON32) - internal const string dllBase = "python3.2"; -#endif -#if (PYTHON33) +#elif PYTHON33 internal const string dllBase = "python3.3"; -#endif -#if (PYTHON34) +#elif PYTHON34 internal const string dllBase = "python3.4"; -#endif -#if (PYTHON35) +#elif PYTHON35 internal const string dllBase = "python3.5"; -#endif -#if (PYTHON36) +#elif PYTHON36 internal const string dllBase = "python3.6"; +#elif PYTHON37 + internal const string dllBase = "python3.7"; #endif -#else -#if (PYTHON32) - internal const string dllBase = "python32"; -#endif -#if (PYTHON33) +#else // Windows +#if PYTHON27 + internal const string dllBase = "python27"; +#elif PYTHON33 internal const string dllBase = "python33"; -#endif -#if (PYTHON34) +#elif PYTHON34 internal const string dllBase = "python34"; -#endif -#if (PYTHON35) +#elif PYTHON35 internal const string dllBase = "python35"; -#endif -#if (PYTHON36) +#elif PYTHON36 internal const string dllBase = "python36"; +#elif PYTHON37 + internal const string dllBase = "python37"; #endif #endif From dde711495055c2f77d705ef253bf9c2bd1cbb664 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 29 Jan 2017 13:41:27 -0700 Subject: [PATCH 005/245] Misc directives in runtime --- src/runtime/runtime.cs | 39 +++++++++++++++++---------------------- 1 file changed, 17 insertions(+), 22 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 4a67e8c65..5f0ecfbd2 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1,13 +1,10 @@ using System; using System.Runtime.InteropServices; using System.Security; -#if (UCS4) +#if UCS4 using System.Text; using Mono.Unix; - -#endif - -#if (UCS2 && PYTHON3) +#elif UCS2 && PYTHON3 using System.Text; #endif @@ -16,7 +13,7 @@ namespace Python.Runtime [SuppressUnmanagedCodeSecurityAttribute()] static class NativeMethods { -#if (MONO_LINUX || MONO_OSX) +#if MONO_LINUX || MONO_OSX static public IntPtr LoadLibrary(string fileName) { return dlopen(fileName, RTLD_NOW | RTLD_SHARED); } @@ -40,7 +37,7 @@ static public IntPtr GetProcAddress(IntPtr dllHandle, string name) { return res; } -#if (MONO_OSX) +#if MONO_OSX static int RTLD_NOW = 0x2; static int RTLD_SHARED = 0x20; static IntPtr RTLD_DEFAULT = new IntPtr(-2); @@ -56,7 +53,7 @@ static public IntPtr GetProcAddress(IntPtr dllHandle, string name) { [DllImport("__Internal")] private static extern IntPtr dlerror(); -#else +#elif MONO_LINUX static int RTLD_NOW = 0x2; static int RTLD_SHARED = 0x20; static IntPtr RTLD_DEFAULT = IntPtr.Zero; @@ -74,7 +71,7 @@ static public IntPtr GetProcAddress(IntPtr dllHandle, string name) { private static extern IntPtr dlerror(); #endif -#else +#else // Windows [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); @@ -93,13 +90,11 @@ public class Runtime /// the responsibility of the caller to have acquired the GIL /// before calling any of these methods. /// -#if (UCS4) +#if UCS4 public const int UCS = 4; -#endif -#if (UCS2) +#elif UCS2 public const int UCS = 2; -#endif -#if ! (UCS2 || UCS4) +#else #error You must define either UCS2 or UCS4! #endif @@ -156,23 +151,23 @@ public class Runtime #endif #endif -#if (PYTHON_WITH_PYDEBUG) +#if PYTHON_WITH_PYDEBUG internal const string dllWithPyDebug = "d"; #else internal const string dllWithPyDebug = ""; #endif -#if (PYTHON_WITH_PYMALLOC) +#if PYTHON_WITH_PYMALLOC internal const string dllWithPyMalloc = "m"; #else internal const string dllWithPyMalloc = ""; #endif -#if (PYTHON_WITH_WIDE_UNICODE) +#if PYTHON_WITH_WIDE_UNICODE internal const string dllWithWideUnicode = "u"; #else internal const string dllWithWideUnicode = ""; #endif -#if (PYTHON_WITHOUT_ENABLE_SHARED) +#if PYTHON_WITHOUT_ENABLE_SHARED public const string dll = "__Internal"; #else public const string dll = dllBase + dllWithPyDebug + dllWithPyMalloc + dllWithWideUnicode; @@ -504,7 +499,7 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) internal unsafe static void XIncref(IntPtr op) { -#if (Py_DEBUG) +#if Py_DEBUG // according to Python doc, Py_IncRef() is Py_XINCREF() Py_IncRef(op); return; @@ -526,7 +521,7 @@ internal unsafe static void XIncref(IntPtr op) internal static unsafe void XDecref(IntPtr op) { -#if (Py_DEBUG) +#if Py_DEBUG // Py_DecRef calls Python's Py_DECREF // according to Python doc, Py_DecRef() is Py_XDECREF() Py_DecRef(op); @@ -581,7 +576,7 @@ internal unsafe static long Refcount(IntPtr op) return 0; } -#if (Py_DEBUG) +#if Py_DEBUG // Py_IncRef and Py_DecRef are taking care of the extra payload // in Py_DEBUG builds of Python like _Py_RefTotal [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, @@ -892,7 +887,7 @@ internal unsafe static IntPtr { return IntPtr.Zero; } -#if (Py_DEBUG) +#if Py_DEBUG int n = 3; #else int n = 1; From 67c161266b6c36612eaaf465a549da99112f482a Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 12 Jan 2017 12:44:38 -0700 Subject: [PATCH 006/245] Use built-in check_output (mostly) Replace one check_output to check_call since we don't use the output. --- setup.py | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/setup.py b/setup.py index f8409799a..d854cd141 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ from distutils.spawn import find_executable from distutils import log from platform import architecture -from subprocess import Popen, CalledProcessError, PIPE, check_call +from subprocess import check_output, check_call from glob import glob import fnmatch import sys @@ -179,7 +179,7 @@ def build_extension(self, ext): interop_file = _get_interop_filename() if not os.path.exists(interop_file): geninterop = os.path.join("tools", "geninterop", "geninterop.py") - _check_output([sys.executable, geninterop, interop_file]) + check_call([sys.executable, geninterop, interop_file]) cmd = [ _xbuild, @@ -285,18 +285,9 @@ def run(self): return install_data.run(self) -def _check_output(*popenargs, **kwargs): - """subprocess.check_output from python 2.7. - Added here to support building for earlier versions of Python. - """ - process = Popen(stdout=PIPE, *popenargs, **kwargs) - output, unused_err = process.communicate() - retcode = process.poll() - if retcode: - cmd = kwargs.get("args") - if cmd is None: - cmd = popenargs[0] - raise CalledProcessError(retcode, cmd, output=output) +def _check_output(*args, **kwargs): + """Check output wrapper for py2/py3 compatibility""" + output = check_output(*args, **kwargs) if sys.version_info[0] > 2: return output.decode("ascii") return output From 9143b5491e27f2146159179beb0cb3432f98ee90 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 27 Jan 2017 10:45:45 -0700 Subject: [PATCH 007/245] Rename build classes, and PLATFORM to ARCH --- setup.py | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/setup.py b/setup.py index d854cd141..992030ae2 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ CONFIG = "Release" # Release or Debug DEVTOOLS = "MsDev" if sys.platform == "win32" else "Mono" VERBOSITY = "minimal" # quiet, minimal, normal, detailed, diagnostic -PLATFORM = "x64" if architecture()[0] == "64bit" else "x86" +ARCH = "x64" if architecture()[0] == "64bit" else "x86" def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): @@ -41,7 +41,7 @@ def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): if use_windows_sdk: sdks_root = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows" kits_root = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots" - kits_suffix = os.path.join("bin", PLATFORM) + kits_suffix = os.path.join("bin", ARCH) keys_to_check.extend([ ("Windows Kit 10.0", kits_root, "KitsRoot10", kits_suffix), ("Windows Kit 8.1", kits_root, "KitsRoot81", kits_suffix), @@ -91,7 +91,7 @@ def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): if use_windows_sdk: localappdata = os.environ["LOCALAPPDATA"] pywinsdk = localappdata + r"\Programs\Common\Microsoft\Visual C++ for Python\9.0\WinSDK\Bin" - if PLATFORM == "x64": + if ARCH == "x64": pywinsdk += r"\x64" paths_to_check.append(("Visual C++ for Python", pywinsdk)) @@ -119,7 +119,7 @@ def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): "DevTools %s not supported (use MsDev or Mono)" % DEVTOOLS) -class PythonNET_BuildExt(build_ext): +class BuildExtPythonnet(build_ext): def build_extension(self, ext): """Builds the .pyd file using msbuild or xbuild""" if ext.name != "clr": @@ -185,7 +185,7 @@ def build_extension(self, ext): _xbuild, "pythonnet.sln", "/p:Configuration=%s" % _config, - "/p:Platform=%s" % PLATFORM, + "/p:Platform=%s" % ARCH, "/p:DefineConstants=\"%s\"" % _defines_sep.join(defines), "/p:PythonBuildDir=\"%s\"" % os.path.abspath(dest_dir), "/p:PythonInteropFile=\"%s\"" % os.path.basename(interop_file), @@ -250,7 +250,7 @@ def _install_packages(self): check_call(cmd, shell=use_shell) -class PythonNET_InstallLib(install_lib): +class InstallLibPythonnet(install_lib): def install(self): if not os.path.isdir(self.build_dir): self.warn("'%s' does not exist -- no Python modules to install" % @@ -262,16 +262,18 @@ def install(self): # only copy clr.pyd/.so for srcfile in glob(os.path.join(self.build_dir, "clr.*")): - destfile = os.path.join(self.install_dir, os.path.basename(srcfile)) + destfile = os.path.join( + self.install_dir, os.path.basename(srcfile)) self.copy_file(srcfile, destfile) -class PythonNET_InstallData(install_data): +class InstallDataPythonnet(install_data): def run(self): build_cmd = self.get_finalized_command("build_ext") install_cmd = self.get_finalized_command("install") build_lib = os.path.abspath(build_cmd.build_lib) - install_platlib = os.path.relpath(install_cmd.install_platlib, self.install_dir) + install_platlib = os.path.relpath( + install_cmd.install_platlib, self.install_dir) for i, data_files in enumerate(self.data_files): if isinstance(data_files, str): @@ -313,7 +315,8 @@ def _get_interop_filename(): sources.extend(glob("*" + ext)) for root, dirnames, filenames in os.walk("src"): - for ext in (".cs", ".csproj", ".sln", ".snk", ".config", ".il", ".py", ".c", ".h", ".ico"): + for ext in (".cs", ".csproj", ".sln", ".snk", ".config", ".il", + ".py", ".c", ".h", ".ico"): for filename in fnmatch.filter(filenames, "*" + ext): sources.append(os.path.join(root, filename)) @@ -360,9 +363,9 @@ def _get_interop_filename(): ], zip_safe=False, cmdclass={ - "build_ext": PythonNET_BuildExt, - "install_lib": PythonNET_InstallLib, - "install_data": PythonNET_InstallData, + "build_ext": BuildExtPythonnet, + "install_lib": InstallLibPythonnet, + "install_data": InstallDataPythonnet, }, setup_requires=setup_requires ) From 53590980202b62dc9854a1a21c0c43303722bdca Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 27 Jan 2017 10:50:13 -0700 Subject: [PATCH 008/245] Organize imports --- setup.py | 75 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 37 insertions(+), 38 deletions(-) diff --git a/setup.py b/setup.py index 992030ae2..30f3719fb 100644 --- a/setup.py +++ b/setup.py @@ -6,36 +6,35 @@ an egg or wheel. """ -from setuptools import setup, Extension -from distutils.command.build_ext import build_ext -from distutils.command.install_lib import install_lib -from distutils.command.install_data import install_data -from distutils.sysconfig import get_config_var -from distutils.spawn import find_executable -from distutils import log -from platform import architecture -from subprocess import check_output, check_call -from glob import glob import fnmatch -import sys +import glob import os +import platform +import subprocess +import sys +import sysconfig +from distutils import log, spawn +from distutils.command import build_ext, install_data, install_lib + +from setuptools import Extension, setup CONFIG = "Release" # Release or Debug -DEVTOOLS = "MsDev" if sys.platform == "win32" else "Mono" VERBOSITY = "minimal" # quiet, minimal, normal, detailed, diagnostic -ARCH = "x64" if architecture()[0] == "64bit" else "x86" + +DEVTOOLS = "MsDev" if sys.platform == "win32" else "Mono" +ARCH = "x64" if platform.architecture()[0] == "64bit" else "x86" def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): """Return full path to one of the Microsoft build tools""" - path = find_executable(tool) + path = spawn.find_executable(tool) if path: return path - try: - import _winreg - except ImportError: - import winreg as _winreg + try: # PY2 + import _winreg as winreg + except ImportError: # PY3 + import winreg keys_to_check = [] if use_windows_sdk: @@ -64,16 +63,16 @@ def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): # read the possible tools paths from the various registry locations paths_to_check = [] - hreg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) + hreg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: for key_to_check in keys_to_check: sdk_name, key, value_name = key_to_check[:3] suffix = key_to_check[3] if len(key_to_check) > 3 else None hkey = None try: - hkey = _winreg.OpenKey(hreg, key) - val, type_ = _winreg.QueryValueEx(hkey, value_name) - if type_ != _winreg.REG_SZ: + hkey = winreg.OpenKey(hreg, key) + val, type_ = winreg.QueryValueEx(hkey, value_name) + if type_ != winreg.REG_SZ: continue if suffix: val = os.path.join(val, suffix) @@ -119,11 +118,11 @@ def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): "DevTools %s not supported (use MsDev or Mono)" % DEVTOOLS) -class BuildExtPythonnet(build_ext): +class BuildExtPythonnet(build_ext.build_ext): def build_extension(self, ext): """Builds the .pyd file using msbuild or xbuild""" if ext.name != "clr": - return build_ext.build_extension(self, ext) + return build_ext.build_ext.build_extension(self, ext) # install packages using nuget self._install_packages() @@ -157,7 +156,7 @@ def build_extension(self, ext): defines.append("MONO_LINUX") # Check if --enable-shared was set when Python was built - enable_shared = get_config_var("Py_ENABLE_SHARED") + enable_shared = sysconfig.get_config_var("Py_ENABLE_SHARED") if enable_shared: # Double-check if libpython is linked dynamically with python lddout = _check_output(["ldd", sys.executable]) @@ -179,7 +178,7 @@ def build_extension(self, ext): interop_file = _get_interop_filename() if not os.path.exists(interop_file): geninterop = os.path.join("tools", "geninterop", "geninterop.py") - check_call([sys.executable, geninterop, interop_file]) + subprocess.check_call([sys.executable, geninterop, interop_file]) cmd = [ _xbuild, @@ -198,8 +197,8 @@ def build_extension(self, ext): self.announce("Building: %s" % " ".join(cmd)) use_shell = True if DEVTOOLS == "Mono" else False - check_call(" ".join(cmd + ["/t:Clean"]), shell=use_shell) - check_call(" ".join(cmd + ["/t:Build"]), shell=use_shell) + subprocess.check_call(" ".join(cmd + ["/t:Clean"]), shell=use_shell) + subprocess.check_call(" ".join(cmd + ["/t:Build"]), shell=use_shell) if DEVTOOLS == "Mono": self._build_monoclr(ext) @@ -211,7 +210,7 @@ def _get_manifest(self, build_dir): cmd = [mt, '-inputresource:"%s"' % sys.executable, '-out:"%s"' % manifest] self.announce("Extracting manifest from %s" % sys.executable) - check_call(" ".join(cmd), shell=False) + subprocess.check_call(" ".join(cmd), shell=False) return manifest def _build_monoclr(self, ext): @@ -231,7 +230,7 @@ def _build_monoclr(self, ext): extra_compile_args=cflags.split(" "), extra_link_args=libs.split(" ")) - build_ext.build_extension(self, clr_ext) + build_ext.build_ext.build_extension(self, clr_ext) def _install_packages(self): """install packages using nuget""" @@ -243,14 +242,14 @@ def _install_packages(self): cmd = "%s update -self" % nuget self.announce("Updating NuGet: %s" % cmd) - check_call(cmd, shell=use_shell) + subprocess.check_call(cmd, shell=use_shell) cmd = "%s restore pythonnet.sln -o packages" % nuget self.announce("Installing packages: %s" % cmd) - check_call(cmd, shell=use_shell) + subprocess.check_call(cmd, shell=use_shell) -class InstallLibPythonnet(install_lib): +class InstallLibPythonnet(install_lib.install_lib): def install(self): if not os.path.isdir(self.build_dir): self.warn("'%s' does not exist -- no Python modules to install" % @@ -261,13 +260,13 @@ def install(self): self.mkpath(self.install_dir) # only copy clr.pyd/.so - for srcfile in glob(os.path.join(self.build_dir, "clr.*")): + for srcfile in glob.glob(os.path.join(self.build_dir, "clr.*")): destfile = os.path.join( self.install_dir, os.path.basename(srcfile)) self.copy_file(srcfile, destfile) -class InstallDataPythonnet(install_data): +class InstallDataPythonnet(install_data.install_data): def run(self): build_cmd = self.get_finalized_command("build_ext") install_cmd = self.get_finalized_command("install") @@ -284,12 +283,12 @@ def run(self): dest = data_files[0].format(install_platlib=install_platlib) self.data_files[i] = dest, data_files[1] - return install_data.run(self) + return install_data.install_data.run(self) def _check_output(*args, **kwargs): """Check output wrapper for py2/py3 compatibility""" - output = check_output(*args, **kwargs) + output = subprocess.check_output(*args, **kwargs) if sys.version_info[0] > 2: return output.decode("ascii") return output @@ -312,7 +311,7 @@ def _get_interop_filename(): sources = [] for ext in (".sln", ".snk", ".config"): - sources.extend(glob("*" + ext)) + sources.extend(glob.glob("*" + ext)) for root, dirnames, filenames in os.walk("src"): for ext in (".cs", ".csproj", ".sln", ".snk", ".config", ".il", From 0078d7600e0337d2cec77773f7c2aa58f81b90c8 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 27 Jan 2017 13:51:10 -0700 Subject: [PATCH 009/245] Move to appropriate context --- setup.py | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/setup.py b/setup.py index 30f3719fb..c160009af 100644 --- a/setup.py +++ b/setup.py @@ -103,21 +103,6 @@ def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): raise RuntimeError("%s could not be found" % tool) -if DEVTOOLS == "MsDev": - _xbuild = "\"%s\"" % _find_msbuild_tool("msbuild.exe") - _defines_sep = ";" - _config = "%sWin" % CONFIG - -elif DEVTOOLS == "Mono": - _xbuild = "xbuild" - _defines_sep = "," - _config = "%sMono" % CONFIG - -else: - raise NotImplementedError( - "DevTools %s not supported (use MsDev or Mono)" % DEVTOOLS) - - class BuildExtPythonnet(build_ext.build_ext): def build_extension(self, ext): """Builds the .pyd file using msbuild or xbuild""" @@ -180,6 +165,19 @@ def build_extension(self, ext): geninterop = os.path.join("tools", "geninterop", "geninterop.py") subprocess.check_call([sys.executable, geninterop, interop_file]) + if DEVTOOLS == "MsDev": + _xbuild = '"{0}"'.format(_find_msbuild_tool("msbuild.exe")) + _defines_sep = ";" + _config = "{0}Win".format(CONFIG) + + elif DEVTOOLS == "Mono": + _xbuild = "xbuild" + _defines_sep = "," + _config = "{0}Mono".format(CONFIG) + else: + raise NotImplementedError( + "DevTool {0} not supported (use MsDev/Mono)".format(DEVTOOLS)) + cmd = [ _xbuild, "pythonnet.sln", From 8fe702a0907adf123bec849eeddfe7f0ca966c27 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 27 Jan 2017 14:44:00 -0700 Subject: [PATCH 010/245] Refactor registry search Use context manager for closing registries --- setup.py | 128 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 73 insertions(+), 55 deletions(-) diff --git a/setup.py b/setup.py index c160009af..365dc2147 100644 --- a/setup.py +++ b/setup.py @@ -6,6 +6,7 @@ an egg or wheel. """ +import collections import fnmatch import glob import os @@ -24,83 +25,100 @@ DEVTOOLS = "MsDev" if sys.platform == "win32" else "Mono" ARCH = "x64" if platform.architecture()[0] == "64bit" else "x86" +############################################################################### +# Windows Keys Constants for MSBUILD tools +RegKey = collections.namedtuple('RegKey', 'sdk_name key value_name suffix') +vs_python = "Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\WinSDK" +vs_root = "SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\{0}" +sdks_root = "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v{0}Win32Tools" +kits_root = "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots" +kits_suffix = os.path.join("bin", ARCH) +WIN_SDK_KEYS = ( + RegKey(sdk_name="Windows Kit 10.0", key=kits_root, + value_name="KitsRoot10", suffix=kits_suffix), + + RegKey(sdk_name="Windows Kit 8.1", key=kits_root, + value_name="KitsRoot81", suffix=kits_suffix), + + RegKey(sdk_name="Windows Kit 8.0", key=kits_root, + value_name="KitsRoot", suffix=kits_suffix), + + RegKey(sdk_name="Windows SDK 7.1A", key=sdks_root.format("7.1A\\WinSDK-"), + value_name="InstallationFolder", suffix=""), + + RegKey(sdk_name="Windows SDK 7.1", key=sdks_root.format("7.1\\WinSDK"), + value_name="InstallationFolder", suffix=""), + + RegKey(sdk_name="Windows SDK 7.0A", key=sdks_root.format("7.0A\\WinSDK-"), + value_name="InstallationFolder", suffix=""), + + RegKey(sdk_name="Windows SDK 7.0", key=sdks_root.format("7.0\\WinSDK"), + value_name="InstallationFolder", suffix=""), + + RegKey(sdk_name="Windows SDK 6.0A", key=sdks_root.format("6.0A\\WinSDK"), + value_name="InstallationFolder", suffix=""), +) + +VS_KEYS = ( + RegKey(sdk_name="MSBuild 14", key=vs_root.format("14.0"), + value_name="MSBuildToolsPath", suffix=""), + + RegKey(sdk_name="MSBuild 12", key=vs_root.format("12.0"), + value_name="MSBuildToolsPath", suffix=""), + + RegKey(sdk_name="MSBuild 4", key=vs_root.format("4.0"), + value_name="MSBuildToolsPath", suffix=""), + + RegKey(sdk_name="MSBuild 3.5", key=vs_root.format("3.5"), + value_name="MSBuildToolsPath", suffix=""), + + RegKey(sdk_name="MSBuild 2.0", key=vs_root.format("2.0"), + value_name="MSBuildToolsPath", suffix=""), +) + + +############################################################################### def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): """Return full path to one of the Microsoft build tools""" + # Search in PATH first path = spawn.find_executable(tool) if path: return path + # Search within registry to find build tools try: # PY2 import _winreg as winreg except ImportError: # PY3 import winreg - keys_to_check = [] - if use_windows_sdk: - sdks_root = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows" - kits_root = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots" - kits_suffix = os.path.join("bin", ARCH) - keys_to_check.extend([ - ("Windows Kit 10.0", kits_root, "KitsRoot10", kits_suffix), - ("Windows Kit 8.1", kits_root, "KitsRoot81", kits_suffix), - ("Windows Kit 8.0", kits_root, "KitsRoot", kits_suffix), - ("Windows SDK 7.1A", sdks_root + r"\v7.1A\WinSDK-Win32Tools", "InstallationFolder"), - ("Windows SDK 7.1", sdks_root + r"\v7.1\WinSDKWin32Tools", "InstallationFolder"), - ("Windows SDK 7.0A", sdks_root + r"\v7.0A\WinSDK-Win32Tools", "InstallationFolder"), - ("Windows SDK 7.0", sdks_root + r"\v7.0\WinSDKWin32Tools", "InstallationFolder"), - ("Windows SDK 6.0A", sdks_root + r"\v6.0A\WinSDKWin32Tools", "InstallationFolder") - ]) - else: - vs_root = r"SOFTWARE\Microsoft\MSBuild\ToolsVersions" - keys_to_check.extend([ - ("MSBuild 14", vs_root + r"\14.0", "MSBuildToolsPath"), - ("MSBuild 12", vs_root + r"\12.0", "MSBuildToolsPath"), - ("MSBuild 4", vs_root + r"\4.0", "MSBuildToolsPath"), - ("MSBuild 3.5", vs_root + r"\3.5", "MSBuildToolsPath"), - ("MSBuild 2.0", vs_root + r"\2.0", "MSBuildToolsPath") - ]) - - # read the possible tools paths from the various registry locations - paths_to_check = [] - hreg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) - try: - for key_to_check in keys_to_check: - sdk_name, key, value_name = key_to_check[:3] - suffix = key_to_check[3] if len(key_to_check) > 3 else None - hkey = None - try: - hkey = winreg.OpenKey(hreg, key) - val, type_ = winreg.QueryValueEx(hkey, value_name) + keys_to_check = WIN_SDK_KEYS if use_windows_sdk else VS_KEYS + for rkey in keys_to_check: + try: + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, rkey.key) as hkey: + val, type_ = winreg.QueryValueEx(hkey, rkey.value_name) if type_ != winreg.REG_SZ: continue - if suffix: - val = os.path.join(val, suffix) - paths_to_check.append((sdk_name, val)) - except WindowsError: - pass - finally: - if hkey: - hkey.Close() - finally: - hreg.Close() + path = os.path.join(val, rkey.suffix, tool) + if os.path.exists(path): + log.info("Using {0} from {1}".format(tool, rkey.sdk_name)) + return path + except WindowsError: + # Key doesn't exist + pass # Add Visual C++ for Python as a fall-back in case one # of the other Windows SDKs isn't installed if use_windows_sdk: + sdk_name = "Visual C++ for Python" localappdata = os.environ["LOCALAPPDATA"] - pywinsdk = localappdata + r"\Programs\Common\Microsoft\Visual C++ for Python\9.0\WinSDK\Bin" - if ARCH == "x64": - pywinsdk += r"\x64" - paths_to_check.append(("Visual C++ for Python", pywinsdk)) - - for sdk_name, path in paths_to_check: - path = os.path.join(path, tool) + suffix = "Bin\\x64" if ARCH == "x64" else "Bin" + path = os.path.join(localappdata, vs_python, suffix, tool) if os.path.exists(path): - log.info("Using %s from %s" % (tool, sdk_name)) + log.info("Using {0} from {1}".format(tool, sdk_name)) return path - raise RuntimeError("%s could not be found" % tool) + raise RuntimeError("{0} could not be found".format(tool)) class BuildExtPythonnet(build_ext.build_ext): From de630171ef0516fb1a038248674f482027df91ac Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 28 Jan 2017 09:25:57 -0700 Subject: [PATCH 011/245] Format setup.py --- setup.py | 81 +++++++++++++++++++++++++++++--------------------------- 1 file changed, 42 insertions(+), 39 deletions(-) diff --git a/setup.py b/setup.py index 365dc2147..bd048f71f 100644 --- a/setup.py +++ b/setup.py @@ -24,6 +24,8 @@ DEVTOOLS = "MsDev" if sys.platform == "win32" else "Mono" ARCH = "x64" if platform.architecture()[0] == "64bit" else "x86" +PY_MAJOR = sys.version_info[0] +PY_MINOR = sys.version_info[1] ############################################################################### # Windows Keys Constants for MSBUILD tools @@ -144,9 +146,9 @@ def build_extension(self, ext): unicode_width = ctypes.sizeof(ctypes.c_wchar) defines = [ - "PYTHON%d%d" % (sys.version_info[:2]), - "PYTHON%d" % (sys.version_info[:1]), # Python Major Version - "UCS%d" % unicode_width, + "PYTHON{0}{1}".format(PY_MAJOR, PY_MINOR), + "PYTHON{0}".format(PY_MAJOR), # Python Major Version + "UCS{0}".format(unicode_width), ] if CONFIG == "Debug": @@ -185,12 +187,10 @@ def build_extension(self, ext): if DEVTOOLS == "MsDev": _xbuild = '"{0}"'.format(_find_msbuild_tool("msbuild.exe")) - _defines_sep = ";" _config = "{0}Win".format(CONFIG) elif DEVTOOLS == "Mono": _xbuild = "xbuild" - _defines_sep = "," _config = "{0}Mono".format(CONFIG) else: raise NotImplementedError( @@ -198,38 +198,38 @@ def build_extension(self, ext): cmd = [ _xbuild, - "pythonnet.sln", - "/p:Configuration=%s" % _config, - "/p:Platform=%s" % ARCH, - "/p:DefineConstants=\"%s\"" % _defines_sep.join(defines), - "/p:PythonBuildDir=\"%s\"" % os.path.abspath(dest_dir), - "/p:PythonInteropFile=\"%s\"" % os.path.basename(interop_file), - "/verbosity:%s" % VERBOSITY, + 'pythonnet.sln', + '/p:Configuration={}'.format(_config), + '/p:Platform={}'.format(ARCH), + '/p:DefineConstants="{}"'.format(','.join(defines)), + '/p:PythonBuildDir="{}"'.format(os.path.abspath(dest_dir)), + '/p:PythonInteropFile="{}"'.format(os.path.basename(interop_file)), + '/verbosity:{}'.format(VERBOSITY), ] manifest = self._get_manifest(dest_dir) if manifest: - cmd.append("/p:PythonManifest=\"%s\"" % manifest) + cmd.append('/p:PythonManifest="{0}"'.format(manifest)) - self.announce("Building: %s" % " ".join(cmd)) + self.announce("Building: {0}".format(" ".join(cmd))) use_shell = True if DEVTOOLS == "Mono" else False subprocess.check_call(" ".join(cmd + ["/t:Clean"]), shell=use_shell) subprocess.check_call(" ".join(cmd + ["/t:Build"]), shell=use_shell) if DEVTOOLS == "Mono": - self._build_monoclr(ext) + self._build_monoclr() def _get_manifest(self, build_dir): if DEVTOOLS == "MsDev" and sys.version_info[:2] > (2, 5): mt = _find_msbuild_tool("mt.exe", use_windows_sdk=True) manifest = os.path.abspath(os.path.join(build_dir, "app.manifest")) - cmd = [mt, '-inputresource:"%s"' % sys.executable, - '-out:"%s"' % manifest] - self.announce("Extracting manifest from %s" % sys.executable) + cmd = [mt, '-inputresource:"{0}"'.format(sys.executable), + '-out:"{0}"'.format(manifest)] + self.announce("Extracting manifest from {}".format(sys.executable)) subprocess.check_call(" ".join(cmd), shell=False) return manifest - def _build_monoclr(self, ext): + def _build_monoclr(self): mono_libs = _check_output("pkg-config --libs mono-2", shell=True) mono_cflags = _check_output("pkg-config --cflags mono-2", shell=True) glib_libs = _check_output("pkg-config --libs glib-2.0", shell=True) @@ -238,13 +238,15 @@ def _build_monoclr(self, ext): libs = mono_libs.strip() + " " + glib_libs.strip() # build the clr python module - clr_ext = Extension("clr", - sources=[ - "src/monoclr/pynetinit.c", - "src/monoclr/clrmod.c" - ], - extra_compile_args=cflags.split(" "), - extra_link_args=libs.split(" ")) + clr_ext = Extension( + "clr", + sources=[ + "src/monoclr/pynetinit.c", + "src/monoclr/clrmod.c" + ], + extra_compile_args=cflags.split(" "), + extra_link_args=libs.split(" ") + ) build_ext.build_ext.build_extension(self, clr_ext) @@ -253,23 +255,23 @@ def _install_packages(self): nuget = os.path.join("tools", "nuget", "nuget.exe") use_shell = False if DEVTOOLS == "Mono": - nuget = "mono %s" % nuget + nuget = "mono {0}".format(nuget) use_shell = True - cmd = "%s update -self" % nuget - self.announce("Updating NuGet: %s" % cmd) + cmd = "{0} update -self".format(nuget) + self.announce("Updating NuGet: {0}".format(cmd)) subprocess.check_call(cmd, shell=use_shell) - cmd = "%s restore pythonnet.sln -o packages" % nuget - self.announce("Installing packages: %s" % cmd) + cmd = "{0} restore pythonnet.sln -o packages".format(nuget) + self.announce("Installing packages: {0}".format(cmd)) subprocess.check_call(cmd, shell=use_shell) class InstallLibPythonnet(install_lib.install_lib): def install(self): if not os.path.isdir(self.build_dir): - self.warn("'%s' does not exist -- no Python modules to install" % - self.build_dir) + self.warn("'{0}' does not exist -- no Python modules" + " to install".format(self.build_dir)) return if not os.path.exists(self.install_dir): @@ -305,9 +307,9 @@ def run(self): def _check_output(*args, **kwargs): """Check output wrapper for py2/py3 compatibility""" output = subprocess.check_output(*args, **kwargs) - if sys.version_info[0] > 2: - return output.decode("ascii") - return output + if PY_MAJOR == 2: + return output + return output.decode("ascii") def _get_interop_filename(): @@ -316,8 +318,9 @@ def _get_interop_filename(): as most windows users won't have Clang installed, which is required to generate the file. """ - interop_file = "interop%d%d%s.cs" % (sys.version_info[0], sys.version_info[1], getattr(sys, "abiflags", "")) - return os.path.join("src", "runtime", interop_file) + interop_filename = "interop{0}{1}{2}.cs".format( + PY_MAJOR, PY_MINOR, getattr(sys, "abiflags", "")) + return os.path.join("src", "runtime", interop_filename) if __name__ == "__main__": @@ -382,5 +385,5 @@ def _get_interop_filename(): "install_lib": InstallLibPythonnet, "install_data": InstallDataPythonnet, }, - setup_requires=setup_requires + setup_requires=setup_requires, ) From ee210011a7b285e16ce4523f24b6fe5c36c3d01f Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 28 Jan 2017 15:31:02 -0700 Subject: [PATCH 012/245] Organize functions --- setup.py | 141 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 73 insertions(+), 68 deletions(-) diff --git a/setup.py b/setup.py index bd048f71f..847bde9a1 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ import subprocess import sys import sysconfig -from distutils import log, spawn +from distutils import spawn from distutils.command import build_ext, install_data, install_lib from setuptools import Extension, setup @@ -81,46 +81,23 @@ ############################################################################### -def _find_msbuild_tool(tool="msbuild.exe", use_windows_sdk=False): - """Return full path to one of the Microsoft build tools""" - # Search in PATH first - path = spawn.find_executable(tool) - if path: - return path - - # Search within registry to find build tools - try: # PY2 - import _winreg as winreg - except ImportError: # PY3 - import winreg - - keys_to_check = WIN_SDK_KEYS if use_windows_sdk else VS_KEYS - for rkey in keys_to_check: - try: - with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, rkey.key) as hkey: - val, type_ = winreg.QueryValueEx(hkey, rkey.value_name) - if type_ != winreg.REG_SZ: - continue - path = os.path.join(val, rkey.suffix, tool) - if os.path.exists(path): - log.info("Using {0} from {1}".format(tool, rkey.sdk_name)) - return path - except WindowsError: - # Key doesn't exist - pass - - # Add Visual C++ for Python as a fall-back in case one - # of the other Windows SDKs isn't installed - if use_windows_sdk: - sdk_name = "Visual C++ for Python" - localappdata = os.environ["LOCALAPPDATA"] - suffix = "Bin\\x64" if ARCH == "x64" else "Bin" - path = os.path.join(localappdata, vs_python, suffix, tool) - if os.path.exists(path): - log.info("Using {0} from {1}".format(tool, sdk_name)) - return path +def _check_output(*args, **kwargs): + """Check output wrapper for py2/py3 compatibility""" + output = subprocess.check_output(*args, **kwargs) + if PY_MAJOR == 2: + return output + return output.decode("ascii") - raise RuntimeError("{0} could not be found".format(tool)) + +def _get_interop_filename(): + """interopXX.cs is auto-generated as part of the build. + For common windows platforms pre-generated files are included + as most windows users won't have Clang installed, which is + required to generate the file. + """ + interop_filename = "interop{0}{1}{2}.cs".format( + PY_MAJOR, PY_MINOR, getattr(sys, "abiflags", "")) + return os.path.join("src", "runtime", interop_filename) class BuildExtPythonnet(build_ext.build_ext): @@ -139,6 +116,7 @@ def build_extension(self, ext): # Up to Python 3.2 sys.maxunicode is used to determine the size of # Py_UNICODE, but from 3.3 onwards Py_UNICODE is a typedef of wchar_t. + # TODO: Is this doing the right check for Py27? if sys.version_info[:2] <= (3, 2): unicode_width = 2 if sys.maxunicode < 0x10FFFF else 4 else: @@ -186,7 +164,7 @@ def build_extension(self, ext): subprocess.check_call([sys.executable, geninterop, interop_file]) if DEVTOOLS == "MsDev": - _xbuild = '"{0}"'.format(_find_msbuild_tool("msbuild.exe")) + _xbuild = '"{0}"'.format(self._find_msbuild_tool("msbuild.exe")) _config = "{0}Win".format(CONFIG) elif DEVTOOLS == "Mono": @@ -220,14 +198,15 @@ def build_extension(self, ext): self._build_monoclr() def _get_manifest(self, build_dir): - if DEVTOOLS == "MsDev" and sys.version_info[:2] > (2, 5): - mt = _find_msbuild_tool("mt.exe", use_windows_sdk=True) - manifest = os.path.abspath(os.path.join(build_dir, "app.manifest")) - cmd = [mt, '-inputresource:"{0}"'.format(sys.executable), - '-out:"{0}"'.format(manifest)] - self.announce("Extracting manifest from {}".format(sys.executable)) - subprocess.check_call(" ".join(cmd), shell=False) - return manifest + if DEVTOOLS != "MsDev": + return + mt = self._find_msbuild_tool("mt.exe", use_windows_sdk=True) + manifest = os.path.abspath(os.path.join(build_dir, "app.manifest")) + cmd = [mt, '-inputresource:"{0}"'.format(sys.executable), + '-out:"{0}"'.format(manifest)] + self.announce("Extracting manifest from {}".format(sys.executable)) + subprocess.check_call(" ".join(cmd), shell=False) + return manifest def _build_monoclr(self): mono_libs = _check_output("pkg-config --libs mono-2", shell=True) @@ -266,6 +245,50 @@ def _install_packages(self): self.announce("Installing packages: {0}".format(cmd)) subprocess.check_call(cmd, shell=use_shell) + def _find_msbuild_tool(self, tool="msbuild.exe", use_windows_sdk=False): + """Return full path to one of the Microsoft build tools""" + # Search in PATH first + path = spawn.find_executable(tool) + if path: + return path + + # Search within registry to find build tools + try: # PY2 + import _winreg as winreg + except ImportError: # PY3 + import winreg + + keys_to_check = WIN_SDK_KEYS if use_windows_sdk else VS_KEYS + hklm = winreg.HKEY_LOCAL_MACHINE + for rkey in keys_to_check: + try: + with winreg.OpenKey(hklm, rkey.key) as hkey: + val, type_ = winreg.QueryValueEx(hkey, rkey.value_name) + if type_ != winreg.REG_SZ: + continue + path = os.path.join(val, rkey.suffix, tool) + if os.path.exists(path): + self.announce("Using {0} from {1}".format( + tool, rkey.sdk_name)) + return path + except WindowsError: + # Key doesn't exist + pass + + # Add Visual C++ for Python as a fall-back in case one + # of the other Windows SDKs isn't installed. + # TODO: Extend checking by using setuptools/msvc.py? + if use_windows_sdk: + sdk_name = "Visual C++ for Python" + localappdata = os.environ["LOCALAPPDATA"] + suffix = "Bin\\x64" if ARCH == "x64" else "Bin" + path = os.path.join(localappdata, vs_python, suffix, tool) + if os.path.exists(path): + self.announce("Using {0} from {1}".format(tool, sdk_name)) + return path + + raise RuntimeError("{0} could not be found".format(tool)) + class InstallLibPythonnet(install_lib.install_lib): def install(self): @@ -304,25 +327,7 @@ def run(self): return install_data.install_data.run(self) -def _check_output(*args, **kwargs): - """Check output wrapper for py2/py3 compatibility""" - output = subprocess.check_output(*args, **kwargs) - if PY_MAJOR == 2: - return output - return output.decode("ascii") - - -def _get_interop_filename(): - """interopXX.cs is auto-generated as part of the build. - For common windows platforms pre-generated files are included - as most windows users won't have Clang installed, which is - required to generate the file. - """ - interop_filename = "interop{0}{1}{2}.cs".format( - PY_MAJOR, PY_MINOR, getattr(sys, "abiflags", "")) - return os.path.join("src", "runtime", interop_filename) - - +############################################################################### if __name__ == "__main__": setupdir = os.path.dirname(__file__) if setupdir: From b32b4d000000388b9f81aaf0c04f58f1885684ee Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 28 Jan 2017 15:37:34 -0700 Subject: [PATCH 013/245] Create get_source_files function --- setup.py | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/setup.py b/setup.py index 847bde9a1..cc345ac7f 100644 --- a/setup.py +++ b/setup.py @@ -100,6 +100,24 @@ def _get_interop_filename(): return os.path.join("src", "runtime", interop_filename) +def _get_source_files(): + """Walk project and collect the files needed for ext_module""" + for ext in (".sln", ".snk", ".config"): + for path in glob.glob("*" + ext): + yield path + + for root, dirnames, filenames in os.walk("src"): + for ext in (".cs", ".csproj", ".sln", ".snk", ".config", ".il", + ".py", ".c", ".h", ".ico"): + for filename in fnmatch.filter(filenames, "*" + ext): + yield os.path.join(root, filename) + + for root, dirnames, filenames in os.walk("tools"): + for ext in (".exe", ".py", ".c", ".h"): + for filename in fnmatch.filter(filenames, "*" + ext): + yield os.path.join(root, filename) + + class BuildExtPythonnet(build_ext.build_ext): def build_extension(self, ext): """Builds the .pyd file using msbuild or xbuild""" @@ -333,21 +351,6 @@ def run(self): if setupdir: os.chdir(setupdir) - sources = [] - for ext in (".sln", ".snk", ".config"): - sources.extend(glob.glob("*" + ext)) - - for root, dirnames, filenames in os.walk("src"): - for ext in (".cs", ".csproj", ".sln", ".snk", ".config", ".il", - ".py", ".c", ".h", ".ico"): - for filename in fnmatch.filter(filenames, "*" + ext): - sources.append(os.path.join(root, filename)) - - for root, dirnames, filenames in os.walk("tools"): - for ext in (".exe", ".py", ".c", ".h"): - for filename in fnmatch.filter(filenames, "*" + ext): - sources.append(os.path.join(root, filename)) - setup_requires = [] interop_file = _get_interop_filename() if not os.path.exists(interop_file): @@ -377,7 +380,7 @@ def run(self): 'Operating System :: MacOS :: MacOS X', ], ext_modules=[ - Extension("clr", sources=sources) + Extension("clr", sources=list(_get_source_files())) ], data_files=[ ("{install_platlib}", [ From f52082947b655e8c8237687781b1f8a9d89b0953 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 28 Jan 2017 15:55:25 -0700 Subject: [PATCH 014/245] No need to put `setup` in `if __name__==...` --- setup.py | 98 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/setup.py b/setup.py index cc345ac7f..51211e6c7 100644 --- a/setup.py +++ b/setup.py @@ -19,6 +19,8 @@ from setuptools import Extension, setup +# Allow config/verbosity to be set from cli +# http://stackoverflow.com/a/4792601/5208670 CONFIG = "Release" # Release or Debug VERBOSITY = "minimal" # quiet, minimal, normal, detailed, diagnostic @@ -346,52 +348,50 @@ def run(self): ############################################################################### -if __name__ == "__main__": - setupdir = os.path.dirname(__file__) - if setupdir: - os.chdir(setupdir) - - setup_requires = [] - interop_file = _get_interop_filename() - if not os.path.exists(interop_file): - setup_requires.append("pycparser") - - setup( - name="pythonnet", - version="2.2.2", - description=".Net and Mono integration for Python", - url='https://pythonnet.github.io/', - license='MIT', - author="The Python for .Net developers", - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: C#', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Operating System :: Microsoft :: Windows', - 'Operating System :: POSIX :: Linux', - 'Operating System :: MacOS :: MacOS X', - ], - ext_modules=[ - Extension("clr", sources=list(_get_source_files())) - ], - data_files=[ - ("{install_platlib}", [ - "{build_lib}/Python.Runtime.dll", - "Python.Runtime.dll.config"]), - ], - zip_safe=False, - cmdclass={ - "build_ext": BuildExtPythonnet, - "install_lib": InstallLibPythonnet, - "install_data": InstallDataPythonnet, - }, - setup_requires=setup_requires, - ) +setupdir = os.path.dirname(__file__) +if setupdir: + os.chdir(setupdir) + +setup_requires = [] +if not os.path.exists(_get_interop_filename()): + setup_requires.append("pycparser") + +setup( + name="pythonnet", + version="2.2.2", + description=".Net and Mono integration for Python", + url='https://pythonnet.github.io/', + license='MIT', + author="The Python for .Net developers", + setup_requires=setup_requires, + ext_modules=[ + Extension("clr", sources=list(_get_source_files())) + ], + data_files=[ + ("{install_platlib}", [ + "{build_lib}/Python.Runtime.dll", + "Python.Runtime.dll.config"]), + ], + cmdclass={ + "build_ext": BuildExtPythonnet, + "install_lib": InstallLibPythonnet, + "install_data": InstallDataPythonnet, + }, + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: C#', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: POSIX :: Linux', + 'Operating System :: MacOS :: MacOS X', + ], + zip_safe=False, +) From 126e5f0acd74017a67fbab29a9297ab39d30937e Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 28 Jan 2017 16:20:23 -0700 Subject: [PATCH 015/245] Add long_description --- setup.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/setup.py b/setup.py index 51211e6c7..ea20a99d3 100644 --- a/setup.py +++ b/setup.py @@ -120,6 +120,15 @@ def _get_source_files(): yield os.path.join(root, filename) +def _get_long_description(): + """Helper to populate long_description for pypi releases""" + try: + import pypandoc + return pypandoc.convert('README.md', 'rst') + except ImportError: + return '.Net and Mono integration for Python' + + class BuildExtPythonnet(build_ext.build_ext): def build_extension(self, ext): """Builds the .pyd file using msbuild or xbuild""" @@ -364,6 +373,7 @@ def run(self): license='MIT', author="The Python for .Net developers", setup_requires=setup_requires, + long_description=_get_long_description(), ext_modules=[ Extension("clr", sources=list(_get_source_files())) ], From ccf96cbe8edcbb73a0f45269d5349e7431828bd3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 28 Jan 2017 17:28:21 -0700 Subject: [PATCH 016/245] Clean-up getinterop --- tools/geninterop/geninterop.py | 46 ++++++++++++++++------------------ 1 file changed, 21 insertions(+), 25 deletions(-) diff --git a/tools/geninterop/geninterop.py b/tools/geninterop/geninterop.py index 946e30217..bf5fdb96b 100644 --- a/tools/geninterop/geninterop.py +++ b/tools/geninterop/geninterop.py @@ -15,16 +15,19 @@ from __future__ import print_function -from distutils.sysconfig import get_config_var -from subprocess import Popen, CalledProcessError, PIPE -from pycparser import c_parser, c_ast import logging -import sys import os +import sys +import sysconfig +import subprocess + +from pycparser import c_ast, c_parser _log = logging.getLogger() logging.basicConfig(level=logging.DEBUG) +PY_MAJOR = sys.version_info[0] +PY_MINOR = sys.version_info[1] # rename some members from their C name when generating the C# _typeoffset_member_renames = { @@ -33,6 +36,14 @@ } +def _check_output(*args, **kwargs): + """Check output wrapper for py2/py3 compatibility""" + output = subprocess.check_output(*args, **kwargs) + if PY_MAJOR == 2: + return output + return output.decode("ascii") + + class AstParser(object): """Walk an AST and determine the members of all structs""" @@ -147,23 +158,6 @@ def __get_struct_name(self, node): return node.name or "_struct_%d" % id(node) -def check_output(*popenargs, **kwargs): - """subprocess.check_output from python 2.7. - Added here to support building for earlier versions of Python. - """ - process = Popen(stdout=PIPE, *popenargs, **kwargs) - output, unused_err = process.communicate() - retcode = process.poll() - if retcode: - cmd = kwargs.get("args") - if cmd is None: - cmd = popenargs[0] - raise CalledProcessError(retcode, cmd) - if sys.version_info[0] > 2: - return output.decode("ascii") - return output - - def preprocess_python_headers(): """Return Python.h pre-processed, ready for parsing. Requires clang. @@ -172,7 +166,7 @@ def preprocess_python_headers(): "fake_libc_include") include_dirs = [fake_libc_include] - include_py = get_config_var("INCLUDEPY") + include_py = sysconfig.get_config_var("INCLUDEPY") include_dirs.append(include_py) defines = [ @@ -195,7 +189,7 @@ def preprocess_python_headers(): # normalize as the parser doesn't like windows line endings. lines = [] - for line in check_output(cmd).splitlines(): + for line in _check_output(cmd).splitlines(): if line.startswith("#"): line = line.replace("\\", "/") lines.append(line) @@ -206,7 +200,7 @@ def gen_interop_code(members): """Generate the TypeOffset C# class""" defines = [ - "PYTHON%d%d" % (sys.version_info[:2]) + "PYTHON{0}{1}".format(PY_MAJOR, PY_MINOR) ] if hasattr(sys, "abiflags"): @@ -217,6 +211,8 @@ def gen_interop_code(members): if "u" in sys.abiflags: defines.append("PYTHON_WITH_WIDE_UNICODE") + filename = os.path.basename(__file__) + defines_str = " && ".join(defines) class_definition = """ // Auto-generated by %s. // DO NOT MODIFIY BY HAND. @@ -252,7 +248,7 @@ def gen_interop_code(members): } // Auto-generated from PyHeapTypeObject in Python.h -""" % (os.path.basename(__file__), " && ".join(defines)) +""" % (filename, defines_str) # All the members are sizeof(void*) so we don't need to do any # extra work to determine the size based on the type. From 65210335d2e4b5efffdb9d840503fb402e037752 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 28 Jan 2017 17:38:58 -0700 Subject: [PATCH 017/245] Fix setup.py log messages self.announce is based on an incomplete logger. use debug_print that turns on when env_var DISTUTILS_DEBUG is present --- setup.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/setup.py b/setup.py index ea20a99d3..3ef19afd7 100644 --- a/setup.py +++ b/setup.py @@ -189,6 +189,7 @@ def build_extension(self, ext): # check the interop file exists, and create it if it doesn't interop_file = _get_interop_filename() if not os.path.exists(interop_file): + self.debug_print("Creating {0}".format(interop_file)) geninterop = os.path.join("tools", "geninterop", "geninterop.py") subprocess.check_call([sys.executable, geninterop, interop_file]) @@ -218,7 +219,7 @@ def build_extension(self, ext): if manifest: cmd.append('/p:PythonManifest="{0}"'.format(manifest)) - self.announce("Building: {0}".format(" ".join(cmd))) + self.debug_print("Building: {0}".format(" ".join(cmd))) use_shell = True if DEVTOOLS == "Mono" else False subprocess.check_call(" ".join(cmd + ["/t:Clean"]), shell=use_shell) subprocess.check_call(" ".join(cmd + ["/t:Build"]), shell=use_shell) @@ -233,7 +234,7 @@ def _get_manifest(self, build_dir): manifest = os.path.abspath(os.path.join(build_dir, "app.manifest")) cmd = [mt, '-inputresource:"{0}"'.format(sys.executable), '-out:"{0}"'.format(manifest)] - self.announce("Extracting manifest from {}".format(sys.executable)) + self.debug_print("Extracting manifest from {}".format(sys.executable)) subprocess.check_call(" ".join(cmd), shell=False) return manifest @@ -267,11 +268,11 @@ def _install_packages(self): use_shell = True cmd = "{0} update -self".format(nuget) - self.announce("Updating NuGet: {0}".format(cmd)) + self.debug_print("Updating NuGet: {0}".format(cmd)) subprocess.check_call(cmd, shell=use_shell) cmd = "{0} restore pythonnet.sln -o packages".format(nuget) - self.announce("Installing packages: {0}".format(cmd)) + self.debug_print("Installing packages: {0}".format(cmd)) subprocess.check_call(cmd, shell=use_shell) def _find_msbuild_tool(self, tool="msbuild.exe", use_windows_sdk=False): @@ -297,7 +298,7 @@ def _find_msbuild_tool(self, tool="msbuild.exe", use_windows_sdk=False): continue path = os.path.join(val, rkey.suffix, tool) if os.path.exists(path): - self.announce("Using {0} from {1}".format( + self.debug_print("Using {0} from {1}".format( tool, rkey.sdk_name)) return path except WindowsError: @@ -313,7 +314,7 @@ def _find_msbuild_tool(self, tool="msbuild.exe", use_windows_sdk=False): suffix = "Bin\\x64" if ARCH == "x64" else "Bin" path = os.path.join(localappdata, vs_python, suffix, tool) if os.path.exists(path): - self.announce("Using {0} from {1}".format(tool, sdk_name)) + self.debug_print("Using {0} from {1}".format(tool, sdk_name)) return path raise RuntimeError("{0} could not be found".format(tool)) From ba7f80fff33d42bba6b3f7089bd19a2d6bea4974 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Tue, 24 Jan 2017 15:54:28 +0100 Subject: [PATCH 018/245] Make internals (in particular Runtime.*) visible to the tests. --- src/runtime/assemblyinfo.cs | 22 ++-------------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/src/runtime/assemblyinfo.cs b/src/runtime/assemblyinfo.cs index 1defa851f..1cbd1e749 100644 --- a/src/runtime/assemblyinfo.cs +++ b/src/runtime/assemblyinfo.cs @@ -2,6 +2,7 @@ using System.Reflection; using System.Resources; using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; [assembly: AssemblyProduct("Python for .NET")] [assembly: AssemblyVersion("4.0.0.1")] @@ -11,23 +12,4 @@ [assembly: AssemblyCopyright("MIT License")] [assembly: AssemblyFileVersion("2.0.0.2")] [assembly: NeutralResourcesLanguage("en")] - -#if PYTHON27 -[assembly: AssemblyTitle("Python.Runtime for Python 2.7")] -[assembly: AssemblyDescription("Python Runtime for Python 2.7")] -#elif PYTHON33 -[assembly: AssemblyTitle("Python.Runtime for Python 3.3")] -[assembly: AssemblyDescription("Python Runtime for Python 3.3")] -#elif PYTHON34 -[assembly: AssemblyTitle("Python.Runtime for Python 3.4")] -[assembly: AssemblyDescription("Python Runtime for Python 3.4")] -#elif PYTHON35 -[assembly: AssemblyTitle("Python.Runtime for Python 3.5")] -[assembly: AssemblyDescription("Python Runtime for Python 3.5")] -#elif PYTHON36 -[assembly: AssemblyTitle("Python.Runtime for Python 3.6")] -[assembly: AssemblyDescription("Python Runtime for Python 3.6")] -#elif PYTHON37 -[assembly: AssemblyTitle("Python.Runtime for Python 3.7")] -[assembly: AssemblyDescription("Python Runtime for Python 3.7")] -#endif +[assembly: InternalsVisibleTo("Python.EmbeddingTest")] From 4d8a8e9654d70b518b8e8d11feddb39d03481342 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Tue, 24 Jan 2017 15:56:42 +0100 Subject: [PATCH 019/245] Simplify the `sys.path` setting in the PyImportTests. --- src/embed_tests/pyimport.cs | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index 58da0ac13..c7a567bdf 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using NUnit.Framework; using Python.Runtime; +using System.IO; namespace Python.EmbeddingTest { @@ -17,34 +18,19 @@ public void SetUp() PythonEngine.Initialize(); gs = PythonEngine.AcquireLock(); - //string here = Environment.CurrentDirectory; - //trunk\pythonnet\src\embed_tests\bin\x86\DebugWin - /* * Append the tests directory to sys.path * using reflection to circumvent the private modifires placed on most Runtime methods. */ const string s = @"../../../../tests"; - Type RTClass = typeof(Runtime.Runtime); - - /* pyStrPtr = PyString_FromString(s); */ - MethodInfo PyString_FromString = RTClass.GetMethod("PyString_FromString", - BindingFlags.NonPublic | BindingFlags.Static); - object[] funcArgs = new object[1]; - funcArgs[0] = s; - IntPtr pyStrPtr = (IntPtr)PyString_FromString.Invoke(null, funcArgs); - - /* SysDotPath = sys.path */ - MethodInfo PySys_GetObject = RTClass.GetMethod("PySys_GetObject", - BindingFlags.NonPublic | BindingFlags.Static); - funcArgs[0] = "path"; - IntPtr SysDotPath = (IntPtr)PySys_GetObject.Invoke(null, funcArgs); + var testPath = Path.Combine( + TestContext.CurrentContext.TestDirectory, s + ); - /* SysDotPath.append(*pyStrPtr) */ - MethodInfo PyList_Append = RTClass.GetMethod("PyList_Append", BindingFlags.NonPublic | BindingFlags.Static); - funcArgs = new object[] { SysDotPath, pyStrPtr }; - int r = (int)PyList_Append.Invoke(null, funcArgs); + IntPtr str = Runtime.Runtime.PyString_FromString(testPath); + IntPtr path = Runtime.Runtime.PySys_GetObject("path"); + Runtime.Runtime.PyList_Append(path, str); } [TearDown] From 689c1fcd40b39e727bef9edd2122463a22abd28f Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Tue, 24 Jan 2017 16:05:43 +0100 Subject: [PATCH 020/245] Add Initialize test and update NUnit to 3.5.0 --- src/embed_tests/InitializeTest.cs | 22 +++++++++++++++++++++ src/embed_tests/Python.EmbeddingTest.csproj | 12 ++++++++--- src/embed_tests/packages.config | 3 +-- 3 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 src/embed_tests/InitializeTest.cs diff --git a/src/embed_tests/InitializeTest.cs b/src/embed_tests/InitializeTest.cs new file mode 100644 index 000000000..a9667343c --- /dev/null +++ b/src/embed_tests/InitializeTest.cs @@ -0,0 +1,22 @@ +using NUnit.Framework; +using Python.Runtime; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Python.EmbeddingTest +{ + public class InitializeTest + { + [Test] + public static void Test() + { + PythonEngine.Initialize(); + PythonEngine.Shutdown(); + + PythonEngine.Initialize(); + PythonEngine.Shutdown(); + } + } +} diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 24645f1bd..f2b4dce61 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -128,20 +128,23 @@ false + + ..\..\packages\NUnit.3.5.0\lib\net40\nunit.framework.dll + True + 3.5 - - ..\..\packages\NUnit.2.6.2\lib\nunit.framework.dll - + + Code @@ -172,6 +175,9 @@ Python.Runtime + + + diff --git a/src/embed_tests/packages.config b/src/embed_tests/packages.config index fdc687a35..53d73768d 100644 --- a/src/embed_tests/packages.config +++ b/src/embed_tests/packages.config @@ -1,5 +1,4 @@ - - + From 50bd03db2d5956eb1bc6a579b4551d7c05ec0078 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 30 Jan 2017 16:06:45 -0700 Subject: [PATCH 021/245] Update CHANGELOG for development --- CHANGELOG.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4515cde20..53f75e6af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,22 @@ This project adheres to [Semantic Versioning][]. This document follows the conventions laid out in [Keep a CHANGELOG][]. +## [unreleased][] + +### Added + +- New `Foo` feature + +### Changed + +- Refactored `setup.py` (#337) +- Upgraded NUnit framework to 3.5 (#341) +- Completed refactor of Build Directives on `Runtime.cs` (#339) + +### Fixed + +- Fixed `FooBar` bug + ## [2.2.2][] - 2017-01-29 ### Fixed From 7b76a1bacabf27c2d23eafc93693c3e7f5183d0f Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 30 Jan 2017 16:12:25 -0700 Subject: [PATCH 022/245] Clean-up embedded tests project Remove reference to non-existing file Remove extra property from pyiter Fix typo and final line on files --- src/embed_tests/Python.EmbeddingTest.csproj | 5 +---- src/embed_tests/pyimport.cs | 2 +- src/embed_tests/pyiter.cs | 4 +++- src/embed_tests/pyobject.cs | 2 +- src/embed_tests/pythonexception.cs | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index f2b4dce61..ed85beb51 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -138,7 +138,6 @@ - @@ -146,9 +145,7 @@ - - Code - + diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index c7a567bdf..a6c12d49e 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -20,7 +20,7 @@ public void SetUp() /* * Append the tests directory to sys.path - * using reflection to circumvent the private modifires placed on most Runtime methods. + * using reflection to circumvent the private modifiers placed on most Runtime methods. */ const string s = @"../../../../tests"; diff --git a/src/embed_tests/pyiter.cs b/src/embed_tests/pyiter.cs index 4939e22fe..1a4084474 100644 --- a/src/embed_tests/pyiter.cs +++ b/src/embed_tests/pyiter.cs @@ -33,11 +33,13 @@ public void TestOnPyList() list.Append(new PyString("baz")); List result = new List(); foreach (PyObject item in list) + { result.Add(item.ToString()); + } Assert.AreEqual(3, result.Count); Assert.AreEqual("foo", result[0]); Assert.AreEqual("bar", result[1]); Assert.AreEqual("baz", result[2]); } } -} \ No newline at end of file +} diff --git a/src/embed_tests/pyobject.cs b/src/embed_tests/pyobject.cs index ba267c3a5..c0f18df39 100644 --- a/src/embed_tests/pyobject.cs +++ b/src/embed_tests/pyobject.cs @@ -30,4 +30,4 @@ public void TestUnicode() Assert.AreEqual("foo\u00e9", s.ToString()); } } -} \ No newline at end of file +} diff --git a/src/embed_tests/pythonexception.cs b/src/embed_tests/pythonexception.cs index 359040601..f0bc39def 100644 --- a/src/embed_tests/pythonexception.cs +++ b/src/embed_tests/pythonexception.cs @@ -44,4 +44,4 @@ public void TestNoError() Assert.AreEqual("", e.Message); } } -} \ No newline at end of file +} From d2cafbbea18cf7fc74f1252e86eed5e4342bbb19 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 30 Jan 2017 16:35:14 -0700 Subject: [PATCH 023/245] Clean up AppVeyor config --- appveyor.yml | 63 +++++++++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 2b0408bf9..e61e6dd2c 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,5 @@ version: '{branch}-{build}' +build: off platform: - x86 @@ -6,60 +7,66 @@ platform: environment: global: - PYTHONPATH: "C:\\testdir" - PYTHONWARNINGS: "ignore:::wheel.pep425tags:" - CONDA_BLD_VERSION: "3.5" - CONDA_BLD: "C:\\conda" - NUNIT: "nunit-console" + PYTHONUNBUFFERED: True + PYTHONWARNINGS: 'ignore:::wheel.pep425tags:' + PYTHONPATH: C:\testdir + NUNIT: nunit-console + CONDA_BLD: C:\conda + CONDA_BLD_VERSION: 3.5 # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the # /E:ON and /V:ON options are not enabled in the batch script interpreter # See: http://stackoverflow.com/a/13751649/163740 - CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\ci\\run_with_env.cmd" + CMD_IN_ENV: 'cmd /E:ON /V:ON /C .\ci\run_with_env.cmd' matrix: - - PYTHON_VERSION: "2.7" - - PYTHON_VERSION: "3.3" - - PYTHON_VERSION: "3.4" - - PYTHON_VERSION: "3.5" - - PYTHON_VERSION: "3.6" + - PYTHON_VERSION: 2.7 + - PYTHON_VERSION: 3.3 + - PYTHON_VERSION: 3.4 + - PYTHON_VERSION: 3.5 + - PYTHON_VERSION: 3.6 init: # Prepare environment - mkdir C:\testdir # Set environment variables depending based on build cfg - - SET CONDA_PY=%PYTHON_VERSION:.=% - - SET CONDA_BLD_ARCH=%PLATFORM:x=% - - SET PYTHON=C:\PYTHON%CONDA_PY% - - IF %PLATFORM%==x86 (SET CONDA_BLD_ARCH=32) - - IF %PLATFORM%==x86 (SET NUNIT=%NUNIT%-x86) - - IF %PLATFORM%==x64 (SET PYTHON=%PYTHON%-x64) + - set CONDA_PY=%PYTHON_VERSION:.=% + - set CONDA_BLD_ARCH=%PLATFORM:x=% + - set PYTHON=C:\PYTHON%PYTHON_VERSION:.=% + - if %PLATFORM%==x86 (set CONDA_BLD_ARCH=32) + - if %PLATFORM%==x86 (set NUNIT=%NUNIT%-x86) + - if %PLATFORM%==x64 (set PYTHON=%PYTHON%-x64) + + # Prepend newly installed Python to the PATH of this build + - set PATH=%PYTHON%;%PYTHON%\Scripts;%PATH% + + # Check that we have the expected version, architecture for Python + - python --version + - python -c "import struct; print(struct.calcsize('P') * 8)" + - python -c "import ctypes; print(ctypes.sizeof(ctypes.c_wchar))" install: # install conda and deps - ps: .\ci\install_miniconda.ps1 # install for wheels - - "%PYTHON%\\python.exe -m pip install --upgrade pip" - - "%PYTHON%\\python.exe -m pip install wheel" - - "%PYTHON%\\python.exe -m pip install six" + - pip install --upgrade pip wheel six build_script: # build clean sdist & wheel - - "%PYTHON%\\python.exe setup.py sdist bdist_wheel" + - python setup.py sdist bdist_wheel # build and dist conda package - - cmd: "%CMD_IN_ENV% %CONDA_BLD%\\Scripts\\conda build conda.recipe" - - ps: $CONDA_PKG=(& "$env:CONDA_BLD\\Scripts\\conda" build conda.recipe --output -q) - - ps: copy-item $CONDA_PKG "$env:APPVEYOR_BUILD_FOLDER\\dist\\" + - '%CMD_IN_ENV% %CONDA_BLD%\Scripts\conda build conda.recipe' + - ps: $CONDA_PKG=(&"$env:CONDA_BLD\Scripts\conda" build conda.recipe --output -q) + - ps: Copy-Item $CONDA_PKG "$env:APPVEYOR_BUILD_FOLDER\dist\" test_script: - - ps: '& "$env:PYTHON\\Scripts\\pip.exe" install --no-cache-dir --force-reinstall --ignore-installed ("dist\\" + (gci dist\*.whl)[0].Name)' - - ps: copy-item (gci -path build -re -include Python.Test.dll)[0].FullName C:\testdir - - "%PYTHON%\\python.exe src\\tests\\runtests.py" + - pip install --no-index --find-links=.\dist\ pythonnet + - ps: Copy-Item (Resolve-Path .\build\*\Python.Test.dll) C:\testdir + - python src\tests\runtests.py # - "%NUNIT% src/embed_tests/bin/%PLATFORM%/ReleaseWin/Python.EmbeddingTest.dll" artifacts: - # bdist_wheel puts your built wheel in the dist directory - path: dist\* From ef133a334227a1241d5f586fdbd1a4cb59ef45e3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 30 Jan 2017 16:36:29 -0700 Subject: [PATCH 024/245] Remove duplicate reference from EmbeddingTest --- src/embed_tests/Python.EmbeddingTest.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index ed85beb51..4afb131d3 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -140,7 +140,6 @@ - From ffa282b7283ad51671b3a019ec3b9bcdb233506d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 26 Jan 2017 22:17:55 -0700 Subject: [PATCH 025/245] Travis - Speed up, use containers --- .travis.yml | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/.travis.yml b/.travis.yml index b24531f93..035a267af 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ -sudo: required -language: python +sudo: false +language: python python: - 2.7 - 3.3 @@ -8,14 +8,21 @@ python: - 3.5 - 3.6 -before_install: - - sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu/ trusty main universe" - - sudo apt-get install software-properties-common - - sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF - - echo "deb http://download.mono-project.com/repo/debian wheezy/snapshots/4.2.4.4 main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list - - echo "deb http://download.mono-project.com/repo/debian wheezy-libtiff-compat main" | sudo tee -a /etc/apt/sources.list.d/mono-xamarin.list - - sudo apt-get update - - sudo DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confnew" install mono-devel mono-complete referenceassemblies-pcl ca-certificates-mono nunit-console +env: + global: + - LD_PRELOAD=/lib/x86_64-linux-gnu/libSegFault.so + - SEGFAULT_SIGNALS=all + - PYTHONUNBUFFERED=True + +addons: + apt: + sources: + - mono + - mono-libtiff-compat + packages: + - mono-devel + - ca-certificates-mono + - nunit-console install: - pip install six From 5cdc0b4ef959b0e45f3898423e244b9114364ba9 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 26 Jan 2017 23:07:57 -0700 Subject: [PATCH 026/245] Build conda recipe on Pull Requests --- appveyor.yml | 11 +++-------- ci/appveyor_build_recipe.ps1 | 6 ++++++ conda.recipe/README.md | 5 +++++ 3 files changed, 14 insertions(+), 8 deletions(-) create mode 100644 ci/appveyor_build_recipe.ps1 create mode 100644 conda.recipe/README.md diff --git a/appveyor.yml b/appveyor.yml index e61e6dd2c..524e75969 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -47,9 +47,6 @@ init: - python -c "import ctypes; print(ctypes.sizeof(ctypes.c_wchar))" install: - # install conda and deps - - ps: .\ci\install_miniconda.ps1 - # install for wheels - pip install --upgrade pip wheel six @@ -57,16 +54,14 @@ build_script: # build clean sdist & wheel - python setup.py sdist bdist_wheel - # build and dist conda package - - '%CMD_IN_ENV% %CONDA_BLD%\Scripts\conda build conda.recipe' - - ps: $CONDA_PKG=(&"$env:CONDA_BLD\Scripts\conda" build conda.recipe --output -q) - - ps: Copy-Item $CONDA_PKG "$env:APPVEYOR_BUILD_FOLDER\dist\" - test_script: - pip install --no-index --find-links=.\dist\ pythonnet - ps: Copy-Item (Resolve-Path .\build\*\Python.Test.dll) C:\testdir - python src\tests\runtests.py # - "%NUNIT% src/embed_tests/bin/%PLATFORM%/ReleaseWin/Python.EmbeddingTest.dll" + # Build conda-recipe on Pull Requests + - ps: .\ci\appveyor_build_recipe.ps1 + artifacts: - path: dist\* diff --git a/ci/appveyor_build_recipe.ps1 b/ci/appveyor_build_recipe.ps1 new file mode 100644 index 000000000..0c885d88d --- /dev/null +++ b/ci/appveyor_build_recipe.ps1 @@ -0,0 +1,6 @@ +if ($env:APPVEYOR_PULL_REQUEST_NUMBER) { + Invoke-Expression .\ci\install_miniconda.ps1 + &"$env:CONDA_BLD\Scripts\conda" build conda.recipe --dirty -q + $CONDA_PKG=(&"$env:CONDA_BLD\Scripts\conda" build conda.recipe --output -q) + Copy-Item $CONDA_PKG "$env:APPVEYOR_BUILD_FOLDER\dist\" +} diff --git a/conda.recipe/README.md b/conda.recipe/README.md new file mode 100644 index 000000000..42241999f --- /dev/null +++ b/conda.recipe/README.md @@ -0,0 +1,5 @@ +# Conda Recipe + +The files here are needed to build Python.Net with conda + +http://conda.pydata.org/docs/building/recipe.html From dee134c4939be63e1d4c9dbe407740c64e08f4bc Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 27 Jan 2017 00:42:31 -0700 Subject: [PATCH 027/245] Add coverage --- .travis.yml | 12 +++++++++--- README.md | 3 +++ appveyor.yml | 22 ++++++++++++++-------- ci/appveyor_run_tests.ps1 | 33 +++++++++++++++++++++++++++++++++ src/embed_tests/packages.config | 1 + 5 files changed, 60 insertions(+), 11 deletions(-) create mode 100644 ci/appveyor_run_tests.ps1 diff --git a/.travis.yml b/.travis.yml index 035a267af..418e50cfc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,14 +25,20 @@ addons: - nunit-console install: - - pip install six - - pip install pycparser - - python setup.py build_ext --inplace + - pip install pycparser coverage codecov six + - coverage run setup.py build_ext --inplace script: - export PYTHONPATH=`pwd`:$PYTHONPATH - python src/tests/runtests.py # - nunit-console src/embed_tests/bin/x64/ReleaseMono/Python.EmbeddingTest.dll +after_success: + # Uncomment if need to geninterop, ie. py37 final + # - python tools/geninterop/geninterop.py + + # Waiting on mono-cov support or SharpCover + - codecov + notifications: email: false diff --git a/README.md b/README.md index 0b6abe756..d4640a925 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ [![appveyor shield][]](https://ci.appveyor.com/project/pythonnet/pythonnet/branch/master) [![travis shield][]](https://travis-ci.org/pythonnet/pythonnet) +[![codecov shield][]](https://codecov.io/github/pythonnet/pythonnet) [![license shield][]](./LICENSE) [![pypi package version][]](https://pypi.python.org/pypi/pythonnet) [![python supported shield][]](https://pypi.python.org/pypi/pythonnet) @@ -80,6 +81,8 @@ int32 [appveyor shield]: https://img.shields.io/appveyor/ci/pythonnet/pythonnet/master.svg?label=AppVeyor +[codecov shield]: https://img.shields.io/codecov/c/github/pythonnet/pythonnet/pytest.svg?label=codecov + [license shield]: https://img.shields.io/badge/license-MIT-blue.svg [pypi package version]: https://img.shields.io/pypi/v/pythonnet.svg diff --git a/appveyor.yml b/appveyor.yml index 524e75969..a8827aee7 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -10,7 +10,6 @@ environment: PYTHONUNBUFFERED: True PYTHONWARNINGS: 'ignore:::wheel.pep425tags:' PYTHONPATH: C:\testdir - NUNIT: nunit-console CONDA_BLD: C:\conda CONDA_BLD_VERSION: 3.5 @@ -35,7 +34,6 @@ init: - set CONDA_BLD_ARCH=%PLATFORM:x=% - set PYTHON=C:\PYTHON%PYTHON_VERSION:.=% - if %PLATFORM%==x86 (set CONDA_BLD_ARCH=32) - - if %PLATFORM%==x86 (set NUNIT=%NUNIT%-x86) - if %PLATFORM%==x64 (set PYTHON=%PYTHON%-x64) # Prepend newly installed Python to the PATH of this build @@ -47,21 +45,29 @@ init: - python -c "import ctypes; print(ctypes.sizeof(ctypes.c_wchar))" install: - # install for wheels - - pip install --upgrade pip wheel six + # install for wheels & coverage + - pip install --upgrade pip wheel coverage codecov six + + # Install OpenCover. Can't put on packages.config; not Linux/Mono compatible + - .\tools\nuget\nuget.exe install OpenCover -OutputDirectory packages build_script: - # build clean sdist & wheel - - python setup.py sdist bdist_wheel + # build clean sdist & wheel with coverage of setup.py, install local wheel + - coverage run setup.py sdist bdist_wheel test_script: - pip install --no-index --find-links=.\dist\ pythonnet - ps: Copy-Item (Resolve-Path .\build\*\Python.Test.dll) C:\testdir - - python src\tests\runtests.py - # - "%NUNIT% src/embed_tests/bin/%PLATFORM%/ReleaseWin/Python.EmbeddingTest.dll" + + # Test runner + - ps: .\ci\appveyor_run_tests.ps1 # Build conda-recipe on Pull Requests - ps: .\ci\appveyor_build_recipe.ps1 +on_finish: + # Upload coverage + - codecov + artifacts: - path: dist\* diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 new file mode 100644 index 000000000..9f9a470bd --- /dev/null +++ b/ci/appveyor_run_tests.ps1 @@ -0,0 +1,33 @@ +# Script to simplify appveyor configuration and resolve path to tools + +# Executable paths for OpenCover +# Note if OpenCover fails, it won't affect the exit codes. +$OPENCOVER = Resolve-Path .\packages\OpenCover.*\tools\OpenCover.Console.exe +$NUNIT = Resolve-Path .\packages\NUnit.ConsoleRunner*\tools\nunit3-console.exe +$PY = Get-Command python + +# Can't use ".\build\*\Python.EmbeddingTest.dll". Missing framework files. +$CS_TESTS = Resolve-Path .\src\embed_tests\bin\*\*\Python.EmbeddingTest.dll +$RUNTIME_DIR = Resolve-Path .\src\runtime\bin\*\ReleaseWin\ + +# Run python tests with C# coverage +# why `2>&1 | %{ "$_" }`? see: http://stackoverflow.com/a/20950421/5208670 +.$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:py.coverage -target:"$PY" -targetargs:src\tests\runtests.py -returntargetcode 2>&1 | %{ "$_" } +$PYTHON_STATUS = $LastExitCode +if ($PYTHON_STATUS -ne 0) { + Write-Host "Python tests failed, continuing to embedded tests" -ForegroundColor "Red" +} + +# Run Embedded tests with C# coverage +# .$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:cs.coverage -target:"$NUNIT" -targetargs:"$CS_TESTS" -returntargetcode +# $NUNIT_STATUS = $LastExitCode +# if ($NUNIT_STATUS -ne 0) { +# Write-Host "Embedded tests failed" -ForegroundColor "Red" +# } + +# Embedded tests failing due to open issues, pass/fail only on Python exit code +# if ($PYTHON_STATUS -ne 0 -or $NUNIT_STATUS -ne 0) { +if ($PYTHON_STATUS -ne 0) { + Write-Host "Tests failed" -ForegroundColor "Red" + $host.SetShouldExit(1) +} diff --git a/src/embed_tests/packages.config b/src/embed_tests/packages.config index 53d73768d..8ab5202ce 100644 --- a/src/embed_tests/packages.config +++ b/src/embed_tests/packages.config @@ -1,4 +1,5 @@ + From 1145a4472c03dc4bdafed03f9b934c5f813b99fe Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 27 Jan 2017 01:47:52 -0700 Subject: [PATCH 028/245] Add tox for quicker local testing --- tox.ini | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 tox.ini diff --git a/tox.ini b/tox.ini new file mode 100644 index 000000000..1cc666ae3 --- /dev/null +++ b/tox.ini @@ -0,0 +1,42 @@ +[tox] +skipsdist=True +skip_missing_interpreters=True +envlist = + py27 + py33 + py34 + py35 + py36 + check + +[testenv] +recreate=True +basepython = + py27: {env:TOXPYTHON:python2.7} + py33: {env:TOXPYTHON:python3.3} + py34: {env:TOXPYTHON:python3.4} + py35: {env:TOXPYTHON:python3.5} + py36: {env:TOXPYTHON:python3.6} + check: python3.5 +setenv = + PYTHONUNBUFFERED=True + DISTUTILS_DEBUG= +passenv = + * +commands = + python --version + python -c "import struct; print('ARCH: %d' % (struct.calcsize('P') * 8))" + python -c "import ctypes; print('UCS%d' % ctypes.sizeof(ctypes.c_wchar))" + python setup.py bdist_wheel + pip install --no-index --find-links=dist/ pythonnet + {posargs:python src\tests\runtests.py} + +[testenv:check] +ignore_errors=True +deps = + check-manifest + flake8 +commands = + check-manifest {toxinidir} + flake8 src setup.py + python setup.py check --strict --metadata From 9912712981867df79493832e32665127359f23dd Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Thu, 26 Jan 2017 17:34:46 +0100 Subject: [PATCH 029/245] Make RunString safer and more standard. --- src/runtime/pythonengine.cs | 59 +++++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 4c676d375..c296f1b87 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -411,33 +411,54 @@ public static PyObject ModuleFromString(string name, string code) /// executing the code string as a PyObject instance, or null if /// an exception was raised. /// - public static PyObject RunString(string code) + public static PyObject RunString( + string code, IntPtr? globals = null, IntPtr? locals = null + ) { - IntPtr globals = Runtime.PyEval_GetGlobals(); - IntPtr locals = Runtime.PyDict_New(); - - IntPtr builtins = Runtime.PyEval_GetBuiltins(); - Runtime.PyDict_SetItemString(locals, "__builtins__", builtins); + bool borrowedGlobals = true; + if (globals == null) + { + globals = Runtime.PyEval_GetGlobals(); + if (globals == IntPtr.Zero) + { + globals = Runtime.PyDict_New(); + Runtime.PyDict_SetItemString( + globals.Value, "__builtins__", + Runtime.PyEval_GetBuiltins() + ); + borrowedGlobals = false; + } + } - IntPtr flag = (IntPtr)257; /* Py_file_input */ - IntPtr result = Runtime.PyRun_String(code, flag, globals, locals); - Runtime.XDecref(locals); - if (result == IntPtr.Zero) + bool borrowedLocals = true; + if (locals == null) { - return null; + locals = Runtime.PyDict_New(); + borrowedLocals = false; } - return new PyObject(result); - } - public static PyObject RunString(string code, IntPtr globals, IntPtr locals) - { IntPtr flag = (IntPtr)257; /* Py_file_input */ - IntPtr result = Runtime.PyRun_String(code, flag, globals, locals); - if (result == IntPtr.Zero) + + try { - return null; + IntPtr result = Runtime.PyRun_String( + code, flag, globals.Value, locals.Value + ); + + if (Runtime.PyErr_Occurred() != 0) + { + throw new PythonException(); + } + + return new PyObject(result); + } + finally + { + if (!borrowedLocals) + Runtime.XDecref(locals.Value); + if (!borrowedGlobals) + Runtime.XDecref(globals.Value); } - return new PyObject(result); } } From 4c8048084e45d0db7d00e52205c274eb78139417 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 10:04:15 -0700 Subject: [PATCH 030/245] Fix Codecov shield branch --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d4640a925..cb9a0f910 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ int32 [appveyor shield]: https://img.shields.io/appveyor/ci/pythonnet/pythonnet/master.svg?label=AppVeyor -[codecov shield]: https://img.shields.io/codecov/c/github/pythonnet/pythonnet/pytest.svg?label=codecov +[codecov shield]: https://img.shields.io/codecov/c/github/pythonnet/pythonnet/master.svg?label=codecov [license shield]: https://img.shields.io/badge/license-MIT-blue.svg From 19936aab15d2b0c43608778e3377a0efd227f1d6 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 10:21:57 -0700 Subject: [PATCH 031/245] Remove unused .csproj properties causing build warnings And remove upgrade/oneclick properties. --- src/clrmodule/clrmodule.csproj | 36 ++-------- src/console/Console.csproj | 27 -------- src/embed_tests/Python.EmbeddingTest.csproj | 75 ++------------------- src/runtime/Python.Runtime.csproj | 14 ---- src/testing/Python.Test.csproj | 36 ++-------- 5 files changed, 18 insertions(+), 170 deletions(-) diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index d19646778..9575f521f 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -22,42 +22,30 @@ full x86 prompt - true - true - false - + true bin\x64\DebugMono\ TRACE;DEBUG;PYTHON2 full x64 prompt - true - true - false - + bin\x86\ReleaseMono\ PYTHON2 true pdbonly x86 prompt - true - true - false - + bin\x64\ReleaseMono\ PYTHON2 true pdbonly x64 prompt - true - true - false true @@ -66,42 +54,30 @@ full x86 prompt - true - false - false - + true bin\x64\DebugWin\ TRACE;DEBUG;PYTHON2 full x64 prompt - true - true - false - + bin\x86\ReleaseWin\ PYTHON2 true pdbonly x86 prompt - true - true - false - + bin\x64\ReleaseWin\ PYTHON2 true pdbonly x64 prompt - true - true - false diff --git a/src/console/Console.csproj b/src/console/Console.csproj index d2d396341..53306e47f 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -9,11 +9,6 @@ nPython Python.Runtime OnBuildSuccess - - - - - 3.5 python-clear.ico 10.0.0 2.0 @@ -61,8 +56,6 @@ DEBUG;TRACE full x86 - true - true True 4 False @@ -76,8 +69,6 @@ pdbonly x86 false - true - true 4 @@ -95,8 +86,6 @@ DEBUG;TRACE full x86 - false - false 4 False @@ -115,8 +104,6 @@ DEBUG;TRACE full x86 - true - true 4 False @@ -126,9 +113,6 @@ DEBUG;TRACE full x64 - true - true - false 4 False @@ -140,9 +124,6 @@ pdbonly x64 false - true - true - false 4 @@ -151,9 +132,6 @@ DEBUG;TRACE full x64 - false - false - false 4 False @@ -163,8 +141,6 @@ DEBUG;TRACE full x64 - false - false 4 False @@ -174,9 +150,6 @@ DEBUG;TRACE full x64 - true - true - false 4 False diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 4afb131d3..264afd0ab 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -9,28 +9,6 @@ Python.EmbeddingTest Python.EmbeddingTest OnBuildSuccess - - - - - 3.5 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - 10.0.0 - 2.0 ..\..\ $(SolutionDir) true @@ -42,22 +20,16 @@ full x86 prompt - true - true - false - + true bin\x64\DebugMono\ DEBUG;TRACE full x64 prompt - true - true - false - + bin\x86\ReleaseMono\ @@ -65,11 +37,8 @@ pdbonly x86 prompt - true - true - false - + bin\x64\ReleaseMono\ @@ -77,9 +46,6 @@ pdbonly x64 prompt - true - true - false true @@ -88,22 +54,16 @@ full x86 prompt - true - false - false - + true bin\x64\DebugWin\ DEBUG;TRACE full x64 prompt - true - true - false - + bin\x86\ReleaseWin\ @@ -111,11 +71,8 @@ pdbonly x86 prompt - true - true - false - + bin\x64\ReleaseWin\ @@ -123,9 +80,6 @@ pdbonly x64 prompt - true - true - false @@ -148,23 +102,6 @@ - - - False - .NET Framework 2.0 %28x86%29 - true - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - {097B4AC0-74E9-4C58-BCF8-C69746EC8271} diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 81616448c..98a9552ac 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -18,8 +18,6 @@ true pdbonly x86 - false - true bin\x64\ReleaseMono\ @@ -28,8 +26,6 @@ true pdbonly x64 - false - true bin\x86\ReleaseWin\ @@ -38,8 +34,6 @@ true pdbonly x86 - false - true bin\x64\ReleaseWin\ @@ -48,8 +42,6 @@ true pdbonly x64 - false - true true @@ -59,9 +51,6 @@ false full x86 - false - false - false true @@ -80,9 +69,6 @@ false full x86 - false - false - false true diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index 4566aeccf..1f0134296 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -21,22 +21,16 @@ full x86 prompt - true - true - false - + true bin\x64\DebugMono\ DEBUG;TRACE full x64 prompt - true - true - false - + bin\x86\ReleaseMono\ @@ -44,11 +38,8 @@ pdbonly x86 prompt - true - true - false - + bin\x64\ReleaseMono\ @@ -56,9 +47,6 @@ pdbonly x64 prompt - true - true - false true @@ -67,22 +55,16 @@ full x86 prompt - true - false - false - + true bin\x64\DebugWin\ DEBUG;TRACE full x64 prompt - true - true - false - + bin\x86\ReleaseWin\ @@ -90,11 +72,8 @@ pdbonly x86 prompt - true - true - false - + bin\x64\ReleaseWin\ @@ -102,9 +81,6 @@ pdbonly x64 prompt - true - true - false From 2d1da5de06d272fc12aceb5d6a1c6d1fb664c59a Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 10:25:30 -0700 Subject: [PATCH 032/245] Remove interop26, interop32 Closes #270 --- src/runtime/Python.Runtime.csproj | 2 - src/runtime/interop26.cs | 150 ------------------------------ src/runtime/interop32.cs | 141 ---------------------------- 3 files changed, 293 deletions(-) delete mode 100644 src/runtime/interop26.cs delete mode 100644 src/runtime/interop32.cs diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 98a9552ac..6309bf4a3 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -164,9 +164,7 @@ - - diff --git a/src/runtime/interop26.cs b/src/runtime/interop26.cs deleted file mode 100644 index 71e3c5115..000000000 --- a/src/runtime/interop26.cs +++ /dev/null @@ -1,150 +0,0 @@ -// Auto-generated by geninterop.py. -// DO NOT MODIFIY BY HAND. - - -#if PYTHON26 -using System; -using System.Collections; -using System.Collections.Specialized; -using System.Runtime.InteropServices; -using System.Reflection; -using System.Text; - -namespace Python.Runtime -{ - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - internal class TypeOffset - { - static TypeOffset() - { - Type type = typeof(TypeOffset); - FieldInfo[] fi = type.GetFields(); - int size = IntPtr.Size; - for (int i = 0; i < fi.Length; i++) - { - fi[i].SetValue(null, i * size); - } - } - - public static int magic() - { - return ob_size; - } - - // Auto-generated from PyHeapTypeObject in Python.h - public static int ob_refcnt = 0; - public static int ob_type = 0; - public static int ob_size = 0; - public static int tp_name = 0; - public static int tp_basicsize = 0; - public static int tp_itemsize = 0; - public static int tp_dealloc = 0; - public static int tp_print = 0; - public static int tp_getattr = 0; - public static int tp_setattr = 0; - public static int tp_compare = 0; - public static int tp_repr = 0; - public static int tp_as_number = 0; - public static int tp_as_sequence = 0; - public static int tp_as_mapping = 0; - public static int tp_hash = 0; - public static int tp_call = 0; - public static int tp_str = 0; - public static int tp_getattro = 0; - public static int tp_setattro = 0; - public static int tp_as_buffer = 0; - public static int tp_flags = 0; - public static int tp_doc = 0; - public static int tp_traverse = 0; - public static int tp_clear = 0; - public static int tp_richcompare = 0; - public static int tp_weaklistoffset = 0; - public static int tp_iter = 0; - public static int tp_iternext = 0; - public static int tp_methods = 0; - public static int tp_members = 0; - public static int tp_getset = 0; - public static int tp_base = 0; - public static int tp_dict = 0; - public static int tp_descr_get = 0; - public static int tp_descr_set = 0; - public static int tp_dictoffset = 0; - public static int tp_init = 0; - public static int tp_alloc = 0; - public static int tp_new = 0; - public static int tp_free = 0; - public static int tp_is_gc = 0; - public static int tp_bases = 0; - public static int tp_mro = 0; - public static int tp_cache = 0; - public static int tp_subclasses = 0; - public static int tp_weaklist = 0; - public static int tp_del = 0; - public static int tp_version_tag = 0; - public static int nb_add = 0; - public static int nb_subtract = 0; - public static int nb_multiply = 0; - public static int nb_divide = 0; - public static int nb_remainder = 0; - public static int nb_divmod = 0; - public static int nb_power = 0; - public static int nb_negative = 0; - public static int nb_positive = 0; - public static int nb_absolute = 0; - public static int nb_nonzero = 0; - public static int nb_invert = 0; - public static int nb_lshift = 0; - public static int nb_rshift = 0; - public static int nb_and = 0; - public static int nb_xor = 0; - public static int nb_or = 0; - public static int nb_coerce = 0; - public static int nb_int = 0; - public static int nb_long = 0; - public static int nb_float = 0; - public static int nb_oct = 0; - public static int nb_hex = 0; - public static int nb_inplace_add = 0; - public static int nb_inplace_subtract = 0; - public static int nb_inplace_multiply = 0; - public static int nb_inplace_divide = 0; - public static int nb_inplace_remainder = 0; - public static int nb_inplace_power = 0; - public static int nb_inplace_lshift = 0; - public static int nb_inplace_rshift = 0; - public static int nb_inplace_and = 0; - public static int nb_inplace_xor = 0; - public static int nb_inplace_or = 0; - public static int nb_floor_divide = 0; - public static int nb_true_divide = 0; - public static int nb_inplace_floor_divide = 0; - public static int nb_inplace_true_divide = 0; - public static int nb_index = 0; - public static int mp_length = 0; - public static int mp_subscript = 0; - public static int mp_ass_subscript = 0; - public static int sq_length = 0; - public static int sq_concat = 0; - public static int sq_repeat = 0; - public static int sq_item = 0; - public static int sq_slice = 0; - public static int sq_ass_item = 0; - public static int sq_ass_slice = 0; - public static int sq_contains = 0; - public static int sq_inplace_concat = 0; - public static int sq_inplace_repeat = 0; - public static int bf_getreadbuffer = 0; - public static int bf_getwritebuffer = 0; - public static int bf_getsegcount = 0; - public static int bf_getcharbuffer = 0; - public static int bf_getbuffer = 0; - public static int bf_releasebuffer = 0; - public static int name = 0; - public static int ht_slots = 0; - - /* here are optional user slots, followed by the members. */ - public static int members = 0; - } -} - -#endif diff --git a/src/runtime/interop32.cs b/src/runtime/interop32.cs deleted file mode 100644 index 2f7464233..000000000 --- a/src/runtime/interop32.cs +++ /dev/null @@ -1,141 +0,0 @@ -// Auto-generated by geninterop.py. -// DO NOT MODIFIY BY HAND. - - -#if PYTHON32 -using System; -using System.Collections; -using System.Collections.Specialized; -using System.Runtime.InteropServices; -using System.Reflection; -using System.Text; - -namespace Python.Runtime -{ - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - internal class TypeOffset - { - static TypeOffset() - { - Type type = typeof(TypeOffset); - FieldInfo[] fi = type.GetFields(); - int size = IntPtr.Size; - for (int i = 0; i < fi.Length; i++) - { - fi[i].SetValue(null, i * size); - } - } - - public static int magic() - { - return ob_size; - } - - // Auto-generated from PyHeapTypeObject in Python.h - public static int ob_refcnt = 0; - public static int ob_type = 0; - public static int ob_size = 0; - public static int tp_name = 0; - public static int tp_basicsize = 0; - public static int tp_itemsize = 0; - public static int tp_dealloc = 0; - public static int tp_print = 0; - public static int tp_getattr = 0; - public static int tp_setattr = 0; - public static int tp_reserved = 0; - public static int tp_repr = 0; - public static int tp_as_number = 0; - public static int tp_as_sequence = 0; - public static int tp_as_mapping = 0; - public static int tp_hash = 0; - public static int tp_call = 0; - public static int tp_str = 0; - public static int tp_getattro = 0; - public static int tp_setattro = 0; - public static int tp_as_buffer = 0; - public static int tp_flags = 0; - public static int tp_doc = 0; - public static int tp_traverse = 0; - public static int tp_clear = 0; - public static int tp_richcompare = 0; - public static int tp_weaklistoffset = 0; - public static int tp_iter = 0; - public static int tp_iternext = 0; - public static int tp_methods = 0; - public static int tp_members = 0; - public static int tp_getset = 0; - public static int tp_base = 0; - public static int tp_dict = 0; - public static int tp_descr_get = 0; - public static int tp_descr_set = 0; - public static int tp_dictoffset = 0; - public static int tp_init = 0; - public static int tp_alloc = 0; - public static int tp_new = 0; - public static int tp_free = 0; - public static int tp_is_gc = 0; - public static int tp_bases = 0; - public static int tp_mro = 0; - public static int tp_cache = 0; - public static int tp_subclasses = 0; - public static int tp_weaklist = 0; - public static int tp_del = 0; - public static int tp_version_tag = 0; - public static int nb_add = 0; - public static int nb_subtract = 0; - public static int nb_multiply = 0; - public static int nb_remainder = 0; - public static int nb_divmod = 0; - public static int nb_power = 0; - public static int nb_negative = 0; - public static int nb_positive = 0; - public static int nb_absolute = 0; - public static int nb_bool = 0; - public static int nb_invert = 0; - public static int nb_lshift = 0; - public static int nb_rshift = 0; - public static int nb_and = 0; - public static int nb_xor = 0; - public static int nb_or = 0; - public static int nb_int = 0; - public static int nb_reserved = 0; - public static int nb_float = 0; - public static int nb_inplace_add = 0; - public static int nb_inplace_subtract = 0; - public static int nb_inplace_multiply = 0; - public static int nb_inplace_remainder = 0; - public static int nb_inplace_power = 0; - public static int nb_inplace_lshift = 0; - public static int nb_inplace_rshift = 0; - public static int nb_inplace_and = 0; - public static int nb_inplace_xor = 0; - public static int nb_inplace_or = 0; - public static int nb_floor_divide = 0; - public static int nb_true_divide = 0; - public static int nb_inplace_floor_divide = 0; - public static int nb_inplace_true_divide = 0; - public static int nb_index = 0; - public static int mp_length = 0; - public static int mp_subscript = 0; - public static int mp_ass_subscript = 0; - public static int sq_length = 0; - public static int sq_concat = 0; - public static int sq_repeat = 0; - public static int sq_item = 0; - public static int was_sq_slice = 0; - public static int sq_ass_item = 0; - public static int was_sq_ass_slice = 0; - public static int sq_contains = 0; - public static int sq_inplace_concat = 0; - public static int sq_inplace_repeat = 0; - public static int bf_getbuffer = 0; - public static int bf_releasebuffer = 0; - public static int name = 0; - public static int ht_slots = 0; - - /* here are optional user slots, followed by the members. */ - public static int members = 0; - } -} - -#endif From af6d37f268a2ab5d9f460d4b09ddfa8a6cd800fc Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Thu, 26 Jan 2017 17:53:57 +0100 Subject: [PATCH 033/245] Fix the shutdown issue by keeping PyMethodDef. Keeping the PyMethodDef around like the documentation (https://docs.python.org/3.6/c-api/module.html#c.PyModuleDef) suggests fixes issue #262. --- src/runtime/importhook.cs | 24 +++++++++++------------- src/runtime/interop.cs | 2 +- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index bdef98c27..dca5a53b4 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -16,7 +16,13 @@ internal class ImportHook #if PYTHON3 static IntPtr py_clr_module; - static IntPtr module_def; + static IntPtr module_def = IntPtr.Zero; + + internal static void InitializeModuleDef() + { + if (module_def == IntPtr.Zero) + module_def = ModuleDefOffset.AllocModuleDef("clr"); + } #endif //=================================================================== @@ -44,8 +50,8 @@ internal static void Initialize() root = new CLRModule(); #if PYTHON3 - // create a python module with the same methods as the clr module-like object - module_def = ModuleDefOffset.AllocModuleDef("clr"); + // create a python module with the same methods as the clr module-like object + InitializeModuleDef(); py_clr_module = Runtime.PyModule_Create2(module_def, 3); // both dicts are borrowed references @@ -70,21 +76,13 @@ internal static void Initialize() internal static void Shutdown() { -#if PYTHON3 if (0 != Runtime.Py_IsInitialized()) { +#if PYTHON3 Runtime.XDecref(py_clr_module); - Runtime.XDecref(root.pyHandle); - } - ModuleDefOffset.FreeModuleDef(module_def); #elif PYTHON2 - if (0 != Runtime.Py_IsInitialized()) - { - Runtime.XDecref(root.pyHandle); Runtime.XDecref(root.pyHandle); - } #endif - if (0 != Runtime.Py_IsInitialized()) - { + Runtime.XDecref(root.pyHandle); Runtime.XDecref(py_import); } } diff --git a/src/runtime/interop.cs b/src/runtime/interop.cs index 0657bc3e6..3dc5ad827 100644 --- a/src/runtime/interop.cs +++ b/src/runtime/interop.cs @@ -227,7 +227,7 @@ public static IntPtr AllocModuleDef(string modulename) { byte[] ascii = Encoding.ASCII.GetBytes(modulename); int size = name + ascii.Length + 1; IntPtr ptr = Marshal.AllocHGlobal(size); - for (int i = 0; i <= m_free; i += IntPtr.Size) + for (int i = 0; i < m_free; i += IntPtr.Size) Marshal.WriteIntPtr(ptr, i, IntPtr.Zero); Marshal.Copy(ascii, 0, (IntPtr)(ptr + name), ascii.Length); Marshal.WriteIntPtr(ptr, m_name, (IntPtr)(ptr + name)); From 402bfcf5d7432f30219650f64bb9c91ca2bbefc3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 21 Jan 2017 17:11:02 -0700 Subject: [PATCH 034/245] Clean-up tests & remove warnfilter Ensure they are using the same functions in py2/py3 Ensure py2/py3 compat Misc. cleanup Add _compat The unittest module has been also updated to use the 'default' filter while running tests. DeprecationWarnings are ignored by default https://docs.python.org/3.3/library/warnings.html#updating-code-for-new-versions-of-python https://docs.python.org/3.3/library/warnings.html#default-warning-filters --- src/tests/PyImportTest/__init__.py | 1 + src/tests/PyImportTest/test/__init__.py | 1 + src/tests/PyImportTest/test/one.py | 1 + src/tests/__init__.py | 1 + src/tests/_compat.py | 65 +++++++++++++++++++ src/tests/leaktest.py | 53 ++++++++------- src/tests/profile.py | 20 ++++-- src/tests/runtests.py | 30 ++++++--- src/tests/stress.py | 40 ++++++++---- src/tests/stresstest.py | 51 ++++++++++----- src/tests/test_array.py | 4 +- src/tests/test_class.py | 6 +- src/tests/test_compat.py | 5 +- src/tests/test_constructors.py | 4 +- src/tests/test_conversion.py | 4 +- src/tests/test_delegate.py | 5 +- src/tests/test_docstring.py | 2 + src/tests/test_engine.py | 11 ++-- src/tests/test_enum.py | 5 +- src/tests/test_event.py | 4 +- src/tests/test_exceptions.py | 5 +- src/tests/test_field.py | 17 +++-- src/tests/test_generic.py | 4 +- src/tests/test_indexer.py | 4 +- src/tests/test_interface.py | 5 +- src/tests/test_method.py | 20 +++--- src/tests/test_module.py | 6 +- src/tests/test_property.py | 13 ++-- src/tests/test_subclass.py | 4 +- src/tests/test_suite/__init__.py | 9 ++- src/tests/test_suite/_missing_import.py | 3 +- src/tests/test_suite/test_callback.py | 12 +++- src/tests/test_suite/test_import.py | 10 ++- ...ursiveTypes.py => test_recursive_types.py} | 12 +++- src/tests/test_thread.py | 16 +++-- src/tests/warnfilter.py | 11 ---- 36 files changed, 327 insertions(+), 137 deletions(-) create mode 100644 src/tests/__init__.py create mode 100644 src/tests/_compat.py rename src/tests/test_suite/{test_recursiveTypes.py => test_recursive_types.py} (77%) delete mode 100644 src/tests/warnfilter.py diff --git a/src/tests/PyImportTest/__init__.py b/src/tests/PyImportTest/__init__.py index e69de29bb..40a96afc6 100644 --- a/src/tests/PyImportTest/__init__.py +++ b/src/tests/PyImportTest/__init__.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- diff --git a/src/tests/PyImportTest/test/__init__.py b/src/tests/PyImportTest/test/__init__.py index e69de29bb..40a96afc6 100644 --- a/src/tests/PyImportTest/test/__init__.py +++ b/src/tests/PyImportTest/test/__init__.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- diff --git a/src/tests/PyImportTest/test/one.py b/src/tests/PyImportTest/test/one.py index e69de29bb..40a96afc6 100644 --- a/src/tests/PyImportTest/test/one.py +++ b/src/tests/PyImportTest/test/one.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- diff --git a/src/tests/__init__.py b/src/tests/__init__.py new file mode 100644 index 000000000..40a96afc6 --- /dev/null +++ b/src/tests/__init__.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- diff --git a/src/tests/_compat.py b/src/tests/_compat.py new file mode 100644 index 000000000..3a9d48c7e --- /dev/null +++ b/src/tests/_compat.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- + +"""Python 2.7, 3.3+ compatibility module. + +Using Python 3 syntax to encourage upgrade unless otherwise noted. +""" + +import operator +import sys +import types + +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 + +if PY3: + import _thread as thread # Using PY2 name + import pickle + from collections import UserList + + indexbytes = operator.getitem + input = input + + string_types = str, + binary_type = bytes + text_type = str + + DictProxyType = type(object.__dict__) + ClassType = type + + # No PY3 equivalents, use PY2 name + long = int + unichr = chr + unicode = str + + # from nowhere import Nothing + cmp = lambda a, b: (a > b) - (a < b) # No Py3 equivalent + map = map + range = range + zip = zip + +elif PY2: + import thread # Using PY2 name + import cPickle as pickle + from UserList import UserList + + indexbytes = lambda buf, i: ord(buf[i]) + input = raw_input + + string_types = str, unicode + bytes_type = str + text_type = unicode + + DictProxyType = types.DictProxyType + ClassType = types.ClassType + + # No PY3 equivalents, use PY2 name + long = long + unichr = unichr + unicode = unicode + + from itertools import izip, imap + cmp = cmp + map = imap + range = xrange + zip = izip diff --git a/src/tests/leaktest.py b/src/tests/leaktest.py index 383da87c8..43a0e83a7 100644 --- a/src/tests/leaktest.py +++ b/src/tests/leaktest.py @@ -1,9 +1,18 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# FIXME: TypeError: 'EventBinding' object is not callable + from __future__ import print_function -import System + +import clr import gc +import System + +from _compat import range + -class LeakTest: +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 @@ -54,7 +63,7 @@ def report(self): def testModules(self): self.notify("Running module leak check...") - for i in xrange(self.count): + for i in range(self.count): if i == 10: self.start_test() @@ -73,7 +82,7 @@ def testClasses(self): self.notify("Running class leak check...") - for i in xrange(self.count): + for i in range(self.count): if i == 10: self.start_test() @@ -86,7 +95,7 @@ def testClasses(self): del x # Delegate type - x = StringDelegate(hello) + x = StringDelegate(hello_func) del x self.end_test() @@ -96,7 +105,7 @@ def testEnumerations(self): self.notify("Running enum leak check...") - for i in xrange(self.count): + for i in range(self.count): if i == 10: self.start_test() @@ -131,7 +140,7 @@ def testEvents(self): self.notify("Running event leak check...") - for i in xrange(self.count): + for i in range(self.count): if i == 10: self.start_test() @@ -210,13 +219,13 @@ def testDelegates(self): self.notify("Running delegate leak check...") - for i in xrange(self.count): + for i in range(self.count): if i == 10: self.start_test() # Delegate from function testob = DelegateTest() - d = StringDelegate(hello) + d = StringDelegate(hello_func) testob.CallStringDelegate(d) testob.stringDelegate = d testob.stringDelegate() @@ -225,7 +234,7 @@ def testDelegates(self): del d # Delegate from instance method - inst = Hello() + inst = HelloClass() testob = DelegateTest() d = StringDelegate(inst.hello) testob.CallStringDelegate(d) @@ -238,7 +247,7 @@ def testDelegates(self): # Delegate from static method testob = DelegateTest() - d = StringDelegate(Hello.s_hello) + d = StringDelegate(HelloClass.s_hello) testob.CallStringDelegate(d) testob.stringDelegate = d testob.stringDelegate() @@ -248,7 +257,7 @@ def testDelegates(self): # Delegate from class method testob = DelegateTest() - d = StringDelegate(Hello.c_hello) + d = StringDelegate(HelloClass.c_hello) testob.CallStringDelegate(d) testob.stringDelegate = d testob.stringDelegate() @@ -257,7 +266,7 @@ def testDelegates(self): del d # Delegate from callable object - inst = Hello() + inst = HelloClass() testob = DelegateTest() d = StringDelegate(inst) testob.CallStringDelegate(d) @@ -290,7 +299,7 @@ def testDelegates(self): # Nested delegates testob = DelegateTest() - d1 = StringDelegate(hello) + d1 = StringDelegate(hello_func) d2 = StringDelegate(d1) testob.CallStringDelegate(d2) testob.stringDelegate = d2 @@ -302,8 +311,8 @@ def testDelegates(self): # Multicast delegates testob = DelegateTest() - d1 = StringDelegate(hello) - d2 = StringDelegate(hello) + d1 = StringDelegate(hello_func) + d2 = StringDelegate(hello_func) md = System.Delegate.Combine(d1, d2) testob.CallStringDelegate(md) testob.stringDelegate = md @@ -317,7 +326,7 @@ def testDelegates(self): self.end_test() -class GenericHandler: +class GenericHandler(object): """A generic handler to test event callbacks.""" def __init__(self): @@ -327,7 +336,7 @@ def handler(self, sender, args): self.value = args.value -class VariableArgsHandler: +class VariableArgsHandler(object): """A variable args handler to test event callbacks.""" def __init__(self): @@ -338,7 +347,7 @@ def handler(self, *args): self.value = eventargs.value -class CallableHandler: +class CallableHandler(object): """A callable handler to test event callbacks.""" def __init__(self): @@ -348,7 +357,7 @@ def __call__(self, sender, args): self.value = args.value -class VarCallableHandler: +class VarCallableHandler(object): """A variable args callable handler to test event callbacks.""" def __init__(self): @@ -381,7 +390,7 @@ def handler(cls, sender, args): handler = classmethod(handler) -class Hello: +class HelloClass(object): def hello(self): return "hello" @@ -399,7 +408,7 @@ def c_hello(cls): c_hello = classmethod(c_hello) -def hello(): +def hello_func(): return "hello" diff --git a/src/tests/profile.py b/src/tests/profile.py index 6117b9616..ddc076e7b 100644 --- a/src/tests/profile.py +++ b/src/tests/profile.py @@ -1,14 +1,25 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# 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 +import gc +import os +import sys +import time -def main(): - import sys, os, gc, time +import runtests +from _compat import range + +def main(): dirname = os.path.split(__file__) sys.path.append(dirname) - import runtests gc.set_debug(gc.DEBUG_LEAK) @@ -28,4 +39,3 @@ def main(): if __name__ == '__main__': main() - sys.exit(0) diff --git a/src/tests/runtests.py b/src/tests/runtests.py index 660d3442d..57d2e0767 100644 --- a/src/tests/runtests.py +++ b/src/tests/runtests.py @@ -1,11 +1,15 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + """Run all of the unit tests for this package.""" +from __future__ import print_function + import os import sys import unittest -import warnfilter -warnfilter.addClrWarnfilter() +from _compat import input try: import System @@ -14,16 +18,17 @@ import clr test_modules = ( - 'test_module', # Passes on its own, but not here if + # Passes on its own, but not here if # other test modules that import System.Windows.Forms # run first. They must not do module level import/AddReference() # of the System.Windows.Forms namespace. + 'test_module', + 'test_suite', 'test_event', 'test_constructors', 'test_enum', 'test_method', - 'test_exceptions', 'test_compat', 'test_generic', @@ -35,11 +40,18 @@ 'test_indexer', 'test_delegate', 'test_array', - 'test_thread' + 'test_thread', + 'test_docstring', + + # FIXME: Fails due to unhandled exception + # 'test_engine', + + # FIXME: Fails in Linux + # 'test_subclass', ) -def removePyc(): +def remove_pyc(): path = os.path.dirname(os.path.abspath(__file__)) for name in test_modules: pyc = os.path.join(path, "%s.pyc" % name) @@ -48,7 +60,7 @@ def removePyc(): def main(verbosity=1): - removePyc() + remove_pyc() suite = unittest.TestSuite() @@ -62,7 +74,7 @@ def main(verbosity=1): if __name__ == '__main__': - main(1) + main() if '--pause' in sys.argv: print("Press enter to continue") - raw_input() + input() diff --git a/src/tests/stress.py b/src/tests/stress.py index dba74a6df..ebc975d38 100644 --- a/src/tests/stress.py +++ b/src/tests/stress.py @@ -1,15 +1,32 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# FIXME: FAIL: testImplicitAssemblyLoad AssertionError: 0 != 1 + """ Run all of the unit tests for this package multiple times in a highly -multithreaded way to stress the system. This makes it possible to look +multi-threaded way to stress the system. This makes it possible to look for memory leaks and threading issues and provides a good target for a profiler to accumulate better data. """ + from __future__ import print_function -import sys, os, gc, time, threading, thread +import gc +import os +import sys +import threading +import time + +from _compat import range, thread -class StressTest: +def dprint(msg): + # Debugging helper to trace thread-related tests. + if 1: + print(msg) + + +class StressTest(object): def __init__(self): self.dirname = os.path.split(__file__)[0] sys.path.append(self.dirname) @@ -18,10 +35,6 @@ def __init__(self): self.module = runtests self.done = [] - def dprint(self, msg): - # Debugging helper to trace thread-related tests. - if 1: print(msg) - def markStart(self): self._start = time.clock() @@ -37,23 +50,23 @@ def printGCReport(self): def runThread(self, iterations): thread_id = thread.get_ident() - self.dprint("thread %s starting..." % thread_id) + dprint("thread %s starting..." % thread_id) time.sleep(0.1) for i in range(iterations): - self.dprint("thread %s iter %d start" % (thread_id, i)) + dprint("thread %s iter %d start" % (thread_id, i)) self.module.main() - self.dprint("thread %s iter %d end" % (thread_id, i)) + dprint("thread %s iter %d end" % (thread_id, i)) self.done.append(None) - self.dprint("thread %s done" % thread_id) + dprint("thread %s done" % thread_id) def stressTest(self, iterations=1, threads=1): args = (iterations,) self.markStart() - for i in range(threads): + for _ in range(threads): thread = threading.Thread(target=self.runThread, args=args) thread.start() while len(self.done) < (iterations * threads): - self.dprint(len(self.done)) + dprint(len(self.done)) time.sleep(0.1) self.markFinish() took = self.elapsed() @@ -67,4 +80,3 @@ def main(): if __name__ == '__main__': main() - sys.exit(0) diff --git a/src/tests/stresstest.py b/src/tests/stresstest.py index bdb7c3e70..6a4d6684a 100644 --- a/src/tests/stresstest.py +++ b/src/tests/stresstest.py @@ -1,36 +1,53 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# FIXME: FAIL: testImplicitAssemblyLoad AssertionError: 0 != 1 + """Basic stress test.""" +from __future__ import print_function + +import gc +import time +import unittest +# import pdb + +from _compat import range + +try: + import System +except ImportError: + print("Load clr import hook") + import clr + def main(): - import time start = time.clock() for i in range(2000): print(i) for name in ( - 'test_module', - 'test_conversion', - # 'test_class', - 'test_interface', - 'test_enum', - 'test_field', - 'test_property', - 'test_indexer', - 'test_event', - 'test_method', - # 'test_delegate', - 'test_array', + 'test_module', + 'test_conversion', + # 'test_class', + 'test_interface', + 'test_enum', + 'test_field', + 'test_property', + 'test_indexer', + 'test_event', + 'test_method', + # 'test_delegate', + 'test_array', ): module = __import__(name) - module.main() + unittest.TextTestRunner().run(module.test_suite()) - # import pdb; pdb.set_trace() + # pdb.set_trace() stop = time.clock() took = str(stop - start) - print 'Total Time: %s' % took + print('Total Time: %s' % took) - import gc for i in gc.get_objects(): print(i) diff --git a/src/tests/test_array.py b/src/tests/test_array.py index 9e396d7ed..4e9a7ac5e 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -1,4 +1,6 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import unittest import Python.Test as Test import System import six diff --git a/src/tests/test_class.py b/src/tests/test_class.py index 9e2af14da..494f59a9a 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + import clr import types import unittest @@ -202,7 +204,7 @@ def __setitem__(self, key, value): self.assertTrue(table.Count == 3) def testAddAndRemoveClassAttribute(self): - + from System import TimeSpan for i in range(100): @@ -260,7 +262,7 @@ def DoCallback(self): def PyCallback(self, self2): self.PyCallbackWasCalled = True self.SameReference = self == self2 - + testobj = CallbackUser() testobj.DoCallback() self.assertTrue(testobj.PyCallbackWasCalled) diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index 8c74b855a..84dcc6884 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -1,4 +1,7 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import unittest +import types import six if six.PY3: diff --git a/src/tests/test_constructors.py b/src/tests/test_constructors.py index 6e02528bb..e8cbe1ea7 100644 --- a/src/tests/test_constructors.py +++ b/src/tests/test_constructors.py @@ -1,4 +1,6 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import unittest import clr clr.AddReference("Python.Test") diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index a00a91c48..92bad1dcc 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -1,4 +1,6 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import unittest from Python.Test import ConversionTest import System import six diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index 26b85ec5e..ac3d73a91 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + import clr clr.AddReference('Python.Test') @@ -5,7 +7,8 @@ from Python.Test import DelegateTest, PublicDelegate from Python.Test import StringDelegate, ObjectDelegate from Python.Test import BoolDelegate -import sys, os, string, unittest, types +import unittest +import types import Python.Test as Test import System import six diff --git a/src/tests/test_docstring.py b/src/tests/test_docstring.py index 9eaea09bb..ac0512d10 100644 --- a/src/tests/test_docstring.py +++ b/src/tests/test_docstring.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + import unittest import clr diff --git a/src/tests/test_engine.py b/src/tests/test_engine.py index 43437c779..6c0928720 100644 --- a/src/tests/test_engine.py +++ b/src/tests/test_engine.py @@ -1,4 +1,7 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import sys +import unittest from Python.Runtime import PythonEngine @@ -9,9 +12,9 @@ class EngineTests(unittest.TestCase): def testMultipleCallsToInitialize(self): """Test that multiple initialize calls are harmless.""" - PythonEngine.Initialize(); - PythonEngine.Initialize(); - PythonEngine.Initialize(); + PythonEngine.Initialize() + PythonEngine.Initialize() + PythonEngine.Initialize() def testImportModule(self): """Test module import.""" diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index fae32bbe6..34a70db45 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -1,4 +1,7 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import unittest +import types from System import DayOfWeek from Python import Test import six diff --git a/src/tests/test_event.py b/src/tests/test_event.py index c68f9629a..874b37b54 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -1,8 +1,10 @@ +# -*- coding: utf-8 -*- + import clr clr.AddReference('Python.Test') -import sys, os, string, unittest, types +import unittest from Python.Test import EventTest, TestEventHandler from Python.Test import TestEventArgs diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index eedf2aa61..2c89e1351 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -1,4 +1,7 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import sys +import unittest import System import six diff --git a/src/tests/test_field.py b/src/tests/test_field.py index d765e3888..0b6163ebd 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -1,4 +1,7 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import unittest +import types from Python.Test import FieldTest from Python.Test import ShortEnum import System @@ -15,7 +18,7 @@ class FieldTests(unittest.TestCase): def testPublicInstanceField(self): """Test public instance fields.""" - object = FieldTest(); + object = FieldTest() self.assertTrue(object.PublicField == 0) object.PublicField = 1 @@ -28,7 +31,7 @@ def test(): def testPublicStaticField(self): """Test public static fields.""" - object = FieldTest(); + object = FieldTest() self.assertTrue(FieldTest.PublicStaticField == 0) FieldTest.PublicStaticField = 1 @@ -50,7 +53,7 @@ def test(): def testProtectedInstanceField(self): """Test protected instance fields.""" - object = FieldTest(); + object = FieldTest() self.assertTrue(object.ProtectedField == 0) object.ProtectedField = 1 @@ -63,7 +66,7 @@ def test(): def testProtectedStaticField(self): """Test protected static fields.""" - object = FieldTest(); + object = FieldTest() self.assertTrue(FieldTest.ProtectedStaticField == 0) FieldTest.ProtectedStaticField = 1 @@ -99,7 +102,7 @@ def test(): def testReadOnlyStaticField(self): """Test readonly static fields.""" - object = FieldTest(); + object = FieldTest() self.assertTrue(FieldTest.ReadOnlyStaticField == 0) self.assertTrue(object.ReadOnlyStaticField == 0) @@ -126,7 +129,7 @@ def test(): def testConstantField(self): """Test const fields.""" - object = FieldTest(); + object = FieldTest() self.assertTrue(FieldTest.ConstField == 0) self.assertTrue(object.ConstField == 0) diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index 1e8b58f21..92e028e47 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -1,9 +1,11 @@ +# -*- coding: utf-8 -*- + import clr clr.AddReference('Python.Test') from System.Collections.Generic import Dictionary, List -import sys, os, string, unittest, types +import unittest import Python.Test as Test import System import six diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index 5e74c76f0..23a722291 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -1,4 +1,6 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import unittest import clr clr.AddReference("Python.Test") diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index 1e495fe25..58b9ac56f 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -1,5 +1,8 @@ +# -*- coding: utf-8 -*- + from Python.Test import InterfaceTest -import sys, os, string, unittest, types +import unittest +import types import Python.Test as Test import System import six diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 4728d13e4..6429bd246 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -1,4 +1,6 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +import unittest import clr clr.AddReference("Python.Test") @@ -63,23 +65,23 @@ def test(): def testPublicInstanceMethod(self): """Test public instance method visibility.""" - object = MethodTest(); + object = MethodTest() self.assertTrue(object.PublicMethod() == "public") def testPublicStaticMethod(self): """Test public static method visibility.""" - object = MethodTest(); + object = MethodTest() self.assertTrue(MethodTest.PublicStaticMethod() == "public static") self.assertTrue(object.PublicStaticMethod() == "public static") def testProtectedInstanceMethod(self): """Test protected instance method visibility.""" - object = MethodTest(); + object = MethodTest() self.assertTrue(object.ProtectedMethod() == "protected") def testProtectedStaticMethod(self): """Test protected static method visibility.""" - object = MethodTest(); + object = MethodTest() result = "protected static" self.assertTrue(MethodTest.ProtectedStaticMethod() == result) self.assertTrue(object.ProtectedStaticMethod() == result) @@ -141,7 +143,7 @@ def test(): self.assertRaises(TypeError, test) - object = MethodTestSub(); + object = MethodTestSub() self.assertTrue(MethodTestSub.PublicMethod(object) == "public") self.assertTrue(MethodTestSub.PublicMethod(object, "echo") == "echo") @@ -162,7 +164,7 @@ def test(): self.assertRaises(TypeError, test) - object = MethodTestSub(); + object = MethodTestSub() self.assertTrue(object.PublicMethod() == "public") self.assertTrue(object.PublicMethod("echo") == "echo") @@ -761,14 +763,14 @@ def test(): def testWeCanBindToEncodingGetString(self): """Check that we can bind to the Encoding.GetString method with variables.""" - + from System.Text import Encoding from System.IO import MemoryStream myBytes = Encoding.UTF8.GetBytes('Some testing string') stream = MemoryStream() stream.Write(myBytes, 0, myBytes.Length) stream.Position = 0 - + buff = System.Array.CreateInstance(System.Byte, 3) buff.Initialize() data = [] diff --git a/src/tests/test_module.py b/src/tests/test_module.py index fff044f0c..fc0877265 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + import clr clr.AddReference('Python.Test') @@ -5,7 +7,9 @@ # testImplicitAssemblyLoad() passes on deprecation warning; perfect! # ##clr.AddReference('System.Windows.Forms') -import sys, os, string, unittest, types, warnings +import unittest +import types +import warnings from fnmatch import fnmatch import six diff --git a/src/tests/test_property.py b/src/tests/test_property.py index 5bb653848..64bc7e946 100644 --- a/src/tests/test_property.py +++ b/src/tests/test_property.py @@ -1,4 +1,7 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- +# +import unittest +import types from Python.Test import PropertyTest import six @@ -13,7 +16,7 @@ class PropertyTests(unittest.TestCase): def testPublicInstanceProperty(self): """Test public instance properties.""" - object = PropertyTest(); + object = PropertyTest() self.assertTrue(object.PublicProperty == 0) object.PublicProperty = 1 @@ -26,7 +29,7 @@ def test(): def testPublicStaticProperty(self): """Test public static properties.""" - object = PropertyTest(); + object = PropertyTest() self.assertTrue(PropertyTest.PublicStaticProperty == 0) PropertyTest.PublicStaticProperty = 1 @@ -48,7 +51,7 @@ def test(): def testProtectedInstanceProperty(self): """Test protected instance properties.""" - object = PropertyTest(); + object = PropertyTest() self.assertTrue(object.ProtectedProperty == 0) object.ProtectedProperty = 1 @@ -61,7 +64,7 @@ def test(): def testProtectedStaticProperty(self): """Test protected static properties.""" - object = PropertyTest(); + object = PropertyTest() self.assertTrue(PropertyTest.ProtectedStaticProperty == 0) PropertyTest.ProtectedStaticProperty = 1 diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index c486a0fc3..a6eedb101 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -1,9 +1,11 @@ +# -*- coding: utf-8 -*- + import clr clr.AddReference('Python.Test') clr.AddReference('System') -import sys, os, string, unittest, types +import unittest from Python.Test import TestFunctions, SubClassTest, IInterfaceTest, TestEventArgs from System.Collections.Generic import List from System import NotImplementedException diff --git a/src/tests/test_suite/__init__.py b/src/tests/test_suite/__init__.py index 5b1cc4ae4..16a3a4cf8 100644 --- a/src/tests/test_suite/__init__.py +++ b/src/tests/test_suite/__init__.py @@ -1,14 +1,17 @@ +# -*- coding: utf-8 -*- + import unittest __all__ = ['test_suite'] from .test_import import test_suite as import_tests from .test_callback import test_suite as callback_tests -from .test_recursiveTypes import test_suite as recursiveTypes_tests +from .test_recursive_types import test_suite as recursive_types_tests + def test_suite(): suite = unittest.TestSuite() suite.addTests((import_tests(),)) suite.addTests((callback_tests(),)) - suite.addTests((recursiveTypes_tests(),)) - return suite \ No newline at end of file + suite.addTests((recursive_types_tests(),)) + return suite diff --git a/src/tests/test_suite/_missing_import.py b/src/tests/test_suite/_missing_import.py index 629ff95be..a104cda49 100644 --- a/src/tests/test_suite/_missing_import.py +++ b/src/tests/test_suite/_missing_import.py @@ -1,2 +1,3 @@ +# -*- coding: utf-8 -*- -import this_package_should_never_exist_ever \ No newline at end of file +import this_package_should_never_exist_ever diff --git a/src/tests/test_suite/test_callback.py b/src/tests/test_suite/test_callback.py index 16c45914d..96070012f 100644 --- a/src/tests/test_suite/test_callback.py +++ b/src/tests/test_suite/test_callback.py @@ -1,15 +1,21 @@ -import unittest, sys +# -*- coding: utf-8 -*- + +import unittest +import sys import clr this_module = sys.modules[__name__] clr.AddReference("Python.Test") import Python.Test as Test from Python.Test import CallbackTest + test_instance = CallbackTest() -def simpleDefaultArg(arg = 'test'): + +def simpleDefaultArg(arg='test'): return arg + class CallbackTests(unittest.TestCase): """Test that callbacks from C# into python work.""" @@ -25,6 +31,6 @@ def testDefaultForNone(self): pythonRetVal = simpleDefaultArg() self.assertEquals(retVal, pythonRetVal) + def test_suite(): return unittest.makeSuite(CallbackTests) - diff --git a/src/tests/test_suite/test_import.py b/src/tests/test_suite/test_import.py index b6d155af3..f3ffbc870 100644 --- a/src/tests/test_suite/test_import.py +++ b/src/tests/test_suite/test_import.py @@ -1,10 +1,15 @@ +# -*- coding: utf-8 -*- + import unittest + class ImportTests(unittest.TestCase): """Test the import statement.""" - def testRealtiveMissingImport(self): - """Test that a relative missing import doesn't crash. Some modules use this to check if a package is installed (realtive import in the site-packages folder""" + def testRelativeMissingImport(self): + """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""" try: from . import _missing_import except ImportError: @@ -13,4 +18,3 @@ def testRealtiveMissingImport(self): def test_suite(): return unittest.makeSuite(ImportTests) - diff --git a/src/tests/test_suite/test_recursiveTypes.py b/src/tests/test_suite/test_recursive_types.py similarity index 77% rename from src/tests/test_suite/test_recursiveTypes.py rename to src/tests/test_suite/test_recursive_types.py index 290d7236a..88656f943 100644 --- a/src/tests/test_suite/test_recursiveTypes.py +++ b/src/tests/test_suite/test_recursive_types.py @@ -1,13 +1,20 @@ -import unittest, sys +# -*- coding: utf-8 -*- + +import unittest +import sys import clr this_module = sys.modules[__name__] clr.AddReference("Python.Test") + + class RecursiveTypesTests(unittest.TestCase): """Test if interop with recursive type inheritance works.""" def testRecursiveTypeCreation(self): - """Test that a recursive types don't crash with a StackOverflowException""" + """Test that a recursive types don't crash with a + StackOverflowException""" + import Python.Test as Test from Python.Test import RecursiveInheritance test_instance = RecursiveInheritance.SubClass() @@ -17,4 +24,3 @@ def testRecursiveTypeCreation(self): def test_suite(): return unittest.makeSuite(RecursiveTypesTests) - diff --git a/src/tests/test_thread.py b/src/tests/test_thread.py index 67873d83c..1a0a8963c 100644 --- a/src/tests/test_thread.py +++ b/src/tests/test_thread.py @@ -1,6 +1,12 @@ -import sys, os, string, unittest, types +# -*- coding: utf-8 -*- + +from __future__ import print_function + +import unittest from Python.Test import ThreadTest import six +import threading +import time if six.PY3: import _thread as thread @@ -10,7 +16,8 @@ def dprint(msg): # Debugging helper to trace thread-related tests. - if 0: print(msg) + if 0: + print(msg) class ThreadTests(unittest.TestCase): @@ -34,7 +41,6 @@ def testDoubleCallbackToPython(self): def testPythonThreadCallsToCLR(self): """Test calls by Python-spawned threads into managed code.""" # This test is very likely to hang if something is wrong ;) - import threading, time from System import String done = [] @@ -44,7 +50,7 @@ def run_thread(): time.sleep(0.1) dprint("thread %s %d" % (thread.get_ident(), i)) mstr = String("thread %s %d" % (thread.get_ident(), i)) - pstr = mstr.ToString() + dprint(mstr.ToString()) done.append(None) dprint("thread %s %d done" % (thread.get_ident(), i)) @@ -59,8 +65,6 @@ def start_threads(count): dprint(len(done)) time.sleep(0.1) - return - def test_suite(): return unittest.makeSuite(ThreadTests) diff --git a/src/tests/warnfilter.py b/src/tests/warnfilter.py deleted file mode 100644 index 8e378b86c..000000000 --- a/src/tests/warnfilter.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Warnfilter -""" - -from warnings import filterwarnings -from warnings import resetwarnings - - -def addClrWarnfilter(action="ignore", append=False): - msgs = ["^The CLR module is deprecated.*", "^Importing from the CLR\.\* namespace.*"] - for msg in msgs: - filterwarnings(action, msg, category=DeprecationWarning, append=append) From fb71914e7346c10cc7f2cba0f363b892b53b07ea Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 21 Jan 2017 18:25:42 -0700 Subject: [PATCH 035/245] Sanitize how to run tests * Remove unsupported entry points * Adds reference to Python.Test by default for all tests * Remove redundant add_reference * Avoid some implicit AddReferences that were being done Not all tests added reference to Python.Test consistently. Solve this by making `run_test` the only supported method. --- src/tests/runtests.py | 4 ++++ src/tests/stresstest.py | 4 ++++ src/tests/test_array.py | 8 -------- src/tests/test_class.py | 9 --------- src/tests/test_compat.py | 17 ----------------- src/tests/test_constructors.py | 12 ------------ src/tests/test_conversion.py | 8 -------- src/tests/test_delegate.py | 12 ------------ src/tests/test_docstring.py | 11 ----------- src/tests/test_engine.py | 8 -------- src/tests/test_enum.py | 8 -------- src/tests/test_event.py | 12 ------------ src/tests/test_exceptions.py | 8 -------- src/tests/test_field.py | 8 -------- src/tests/test_generic.py | 11 ----------- src/tests/test_indexer.py | 10 ---------- src/tests/test_interface.py | 8 -------- src/tests/test_method.py | 11 ----------- src/tests/test_module.py | 16 +++------------- src/tests/test_property.py | 8 -------- src/tests/test_subclass.py | 12 ------------ src/tests/test_thread.py | 9 --------- 22 files changed, 11 insertions(+), 203 deletions(-) diff --git a/src/tests/runtests.py b/src/tests/runtests.py index 57d2e0767..3b7ffa08e 100644 --- a/src/tests/runtests.py +++ b/src/tests/runtests.py @@ -16,6 +16,10 @@ except ImportError: print("Load clr import hook") import clr + clr.AddReference("Python.Test") + clr.AddReference("System.Collections") + clr.AddReference("System.Data") + clr.AddReference("System.Management") test_modules = ( # Passes on its own, but not here if diff --git a/src/tests/stresstest.py b/src/tests/stresstest.py index 6a4d6684a..6c02bf566 100644 --- a/src/tests/stresstest.py +++ b/src/tests/stresstest.py @@ -18,6 +18,10 @@ except ImportError: print("Load clr import hook") import clr + clr.AddReference("Python.Test") + clr.AddReference("System.Collections") + clr.AddReference("System.Data") + clr.AddReference("System.Management") def main(): diff --git a/src/tests/test_array.py b/src/tests/test_array.py index 4e9a7ac5e..57034a8da 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -1480,11 +1480,3 @@ def test(): def test_suite(): return unittest.makeSuite(ArrayTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_class.py b/src/tests/test_class.py index 494f59a9a..5ff0c0e77 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- -import clr import types import unittest @@ -280,11 +279,3 @@ def kind(self): def test_suite(): return unittest.makeSuite(ClassTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index 84dcc6884..26852ff72 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -159,9 +159,6 @@ def testDottedNameImportFromWithAlias(self): def testFromModuleImportStar(self): """Test from module import * behavior.""" - import clr - clr.AddReference("System.Management") - count = len(locals().keys()) m = __import__('CLR.System.Management', globals(), locals(), ['*']) self.assertTrue(m.__name__ == 'System.Management') @@ -262,17 +259,3 @@ def test000MultipleImports(self): def test_suite(): return unittest.makeSuite(CompatibilityTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - try: - import System - except ImportError: - print("Load clr import hook") - import clr - - main() diff --git a/src/tests/test_constructors.py b/src/tests/test_constructors.py index e8cbe1ea7..e123c7bdc 100644 --- a/src/tests/test_constructors.py +++ b/src/tests/test_constructors.py @@ -1,10 +1,6 @@ # -*- coding: utf-8 -*- import unittest -import clr - -clr.AddReference("Python.Test") -import Python.Test as Test import System @@ -51,11 +47,3 @@ class sub(System.Exception): def test_suite(): return unittest.makeSuite(ConstructorTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index 92bad1dcc..ba45d8e34 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -836,11 +836,3 @@ def testSByteArrayConversion(self): def test_suite(): return unittest.makeSuite(ConversionTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index ac3d73a91..1123bfdb5 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -1,9 +1,5 @@ # -*- coding: utf-8 -*- -import clr - -clr.AddReference('Python.Test') - from Python.Test import DelegateTest, PublicDelegate from Python.Test import StringDelegate, ObjectDelegate from Python.Test import BoolDelegate @@ -319,11 +315,3 @@ def always_so_negative(): def test_suite(): return unittest.makeSuite(DelegateTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_docstring.py b/src/tests/test_docstring.py index ac0512d10..d1be3c681 100644 --- a/src/tests/test_docstring.py +++ b/src/tests/test_docstring.py @@ -1,9 +1,6 @@ # -*- coding: utf-8 -*- import unittest -import clr - -clr.AddReference('Python.Test') from Python.Test import DocWithCtorTest, DocWithoutCtorTest, DocWithCtorNoDocTest @@ -29,11 +26,3 @@ def testDocWithoutCtor(self): def test_suite(): return unittest.makeSuite(DocStringTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_engine.py b/src/tests/test_engine.py index 6c0928720..c38a471fe 100644 --- a/src/tests/test_engine.py +++ b/src/tests/test_engine.py @@ -39,11 +39,3 @@ def testRunString(self): def test_suite(): return unittest.makeSuite(EngineTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index 34a70db45..6eb7e7592 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -148,11 +148,3 @@ def test(): def test_suite(): return unittest.makeSuite(EnumTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 874b37b54..2ddcc55d8 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -1,9 +1,5 @@ # -*- coding: utf-8 -*- -import clr - -clr.AddReference('Python.Test') - import unittest from Python.Test import EventTest, TestEventHandler from Python.Test import TestEventArgs @@ -678,11 +674,3 @@ def handler(self, sender, args): def test_suite(): return unittest.makeSuite(EventTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index 2c89e1351..9509cef95 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -372,11 +372,3 @@ def testChainedExceptions(self): def test_suite(): return unittest.makeSuite(ExceptionTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_field.py b/src/tests/test_field.py index 0b6163ebd..bafb27598 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -426,11 +426,3 @@ def test(): def test_suite(): return unittest.makeSuite(FieldTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index 92e028e47..c80ff5704 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -1,9 +1,6 @@ # -*- coding: utf-8 -*- import clr - -clr.AddReference('Python.Test') - from System.Collections.Generic import Dictionary, List import unittest import Python.Test as Test @@ -795,11 +792,3 @@ def testNestedGenericClass(self): def test_suite(): return unittest.makeSuite(GenericTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index 23a722291..f9d16a1c3 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -1,9 +1,7 @@ # -*- coding: utf-8 -*- import unittest -import clr -clr.AddReference("Python.Test") import Python.Test as Test import six @@ -679,11 +677,3 @@ def test(): def test_suite(): return unittest.makeSuite(IndexerTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index 58b9ac56f..6c6bb6228 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -77,11 +77,3 @@ def testExplicitCastToInterface(self): def test_suite(): return unittest.makeSuite(InterfaceTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 6429bd246..f6806687c 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -1,9 +1,6 @@ # -*- coding: utf-8 -*- import unittest -import clr - -clr.AddReference("Python.Test") from Python.Test import MethodTest, MethodTestSub import System @@ -786,11 +783,3 @@ def testWeCanBindToEncodingGetString(self): def test_suite(): return unittest.makeSuite(MethodTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_module.py b/src/tests/test_module.py index fc0877265..8eaedf5c9 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -2,11 +2,6 @@ import clr -clr.AddReference('Python.Test') -clr.AddReference('System.Data') - -# testImplicitAssemblyLoad() passes on deprecation warning; perfect! # -##clr.AddReference('System.Windows.Forms') import unittest import types import warnings @@ -18,6 +13,9 @@ else: ClassType = types.ClassType +# testImplicitAssemblyLoad() passes on deprecation warning; perfect! # +# clr.AddReference('System.Windows.Forms') + class ModuleTests(unittest.TestCase): """Test CLR modules and the CLR import hook.""" @@ -383,11 +381,3 @@ def test_AssemblyLoadThreadSafety(self): def test_suite(): return unittest.makeSuite(ModuleTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_property.py b/src/tests/test_property.py index 64bc7e946..9ed2a5207 100644 --- a/src/tests/test_property.py +++ b/src/tests/test_property.py @@ -179,11 +179,3 @@ def testInterfaceProperty(self): def test_suite(): return unittest.makeSuite(PropertyTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index a6eedb101..f99c4cdc6 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -1,10 +1,6 @@ # -*- coding: utf-8 -*- import clr - -clr.AddReference('Python.Test') -clr.AddReference('System') - import unittest from Python.Test import TestFunctions, SubClassTest, IInterfaceTest, TestEventArgs from System.Collections.Generic import List @@ -167,11 +163,3 @@ def test_isinstance(self): def test_suite(): return unittest.makeSuite(SubClassTests) - - -def main(): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() diff --git a/src/tests/test_thread.py b/src/tests/test_thread.py index 1a0a8963c..ba91e3bee 100644 --- a/src/tests/test_thread.py +++ b/src/tests/test_thread.py @@ -68,12 +68,3 @@ def start_threads(count): def test_suite(): return unittest.makeSuite(ThreadTests) - - -def main(): - for i in range(50): - unittest.TextTestRunner().run(test_suite()) - - -if __name__ == '__main__': - main() From a51a4bf8d2e1e63732acaccd007af33e656a6940 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 21 Jan 2017 18:50:36 -0700 Subject: [PATCH 036/245] Remove dependency on six Remove six.u(...), six.b(...) Not needed since dropped older python versions --- .travis.yml | 2 +- appveyor.yml | 2 +- src/tests/test_array.py | 26 +++++----------------- src/tests/test_class.py | 7 +----- src/tests/test_compat.py | 20 +++++++---------- src/tests/test_conversion.py | 42 ++++++++++++++++-------------------- src/tests/test_delegate.py | 8 +------ src/tests/test_enum.py | 9 +------- src/tests/test_exceptions.py | 32 +++++++++++---------------- src/tests/test_field.py | 21 ++++++------------ src/tests/test_generic.py | 29 +++++++++++-------------- src/tests/test_indexer.py | 22 ++++++++----------- src/tests/test_interface.py | 8 +------ src/tests/test_method.py | 19 +++++++--------- src/tests/test_module.py | 27 +++++++++++------------ src/tests/test_property.py | 13 +++-------- src/tests/test_thread.py | 6 +----- 17 files changed, 103 insertions(+), 190 deletions(-) diff --git a/.travis.yml b/.travis.yml index 418e50cfc..1b5806d59 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,7 +25,7 @@ addons: - nunit-console install: - - pip install pycparser coverage codecov six + - pip install pycparser coverage codecov - coverage run setup.py build_ext --inplace script: diff --git a/appveyor.yml b/appveyor.yml index a8827aee7..2795a94f8 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -46,7 +46,7 @@ init: install: # install for wheels & coverage - - pip install --upgrade pip wheel coverage codecov six + - pip install --upgrade pip wheel coverage codecov # Install OpenCover. Can't put on packages.config; not Linux/Mono compatible - .\tools\nuget\nuget.exe install OpenCover -OutputDirectory packages diff --git a/src/tests/test_array.py b/src/tests/test_array.py index 57034a8da..03440ca6e 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -3,11 +3,7 @@ import unittest import Python.Test as Test import System -import six - -if six.PY3: - long = int - unichr = chr +from _compat import UserList, PY2, long, unichr class ArrayTests(unittest.TestCase): @@ -1098,10 +1094,6 @@ def testSequenceArrayConversion(self): """Test conversion of sequence-like objects to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam - if six.PY3: - from collections import UserList - else: - from UserList import UserList items = UserList() for i in range(10): @@ -1115,10 +1107,6 @@ def testSequenceNestedArrayConversion(self): """Test conversion of sequences to array-of-array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam - if six.PY3: - from collections import UserList - else: - from UserList import UserList items = UserList() for i in range(10): @@ -1204,10 +1192,6 @@ def testSequenceArrayConversionTypeChecking(self): """Test error handling for sequence conversion to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam - if six.PY3: - from collections import UserList - else: - from UserList import UserList # This should work, because null / None is a valid value in an # array of reference types. @@ -1322,9 +1306,9 @@ def testSpecialArrayCreation(self): self.assertTrue(value[1] == 127) self.assertTrue(value.Length == 2) - value = Array[System.Char]([six.u('A'), six.u('Z')]) - self.assertTrue(value[0] == six.u('A')) - self.assertTrue(value[1] == six.u('Z')) + value = Array[System.Char]([u'A', u'Z']) + self.assertTrue(value[0] == u'A') + self.assertTrue(value[1] == u'Z') self.assertTrue(value.Length == 2) value = Array[System.Char]([0, 65535]) @@ -1353,7 +1337,7 @@ def testSpecialArrayCreation(self): self.assertTrue(value.Length == 2) # there's no explicit long type in python3, use System.Int64 instead - if not six.PY3: + if PY2: value = Array[long]([0, long(9223372036854775807)]) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == long(9223372036854775807)) diff --git a/src/tests/test_class.py b/src/tests/test_class.py index 5ff0c0e77..30972d111 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -1,18 +1,13 @@ # -*- coding: utf-8 -*- -import types import unittest import Python.Test as Test import System -import six from Python.Test import ClassTest from System.Collections import Hashtable -if six.PY3: - DictProxyType = type(object.__dict__) -else: - DictProxyType = types.DictProxyType +from _compat import DictProxyType class ClassTests(unittest.TestCase): diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index 26852ff72..571d54717 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -2,12 +2,7 @@ import unittest import types -import six - -if six.PY3: - ClassType = type -else: - ClassType = types.ClassType +from _compat import PY2, PY3, ClassType class CompatibilityTests(unittest.TestCase): @@ -19,10 +14,11 @@ def isCLRModule(self, object): return type(object).__name__ == 'ModuleObject' def isCLRRootModule(self, object): - if six.PY3: + if PY3: # in Python 3 the clr module is a normal python module return object.__name__ == "clr" - return type(object).__name__ == 'CLRModule' + elif PY2: + return type(object).__name__ == 'CLRModule' def isCLRClass(self, object): return type(object).__name__ == 'CLR Metatype' # for now @@ -39,12 +35,12 @@ def testSimpleImport(self): self.assertTrue(type(sys) == types.ModuleType) self.assertTrue(sys.__name__ == 'sys') - if six.PY3: + if PY3: import http.client self.assertTrue(type(http.client) == types.ModuleType) self.assertTrue(http.client.__name__ == 'http.client') - else: + elif PY2: import httplib self.assertTrue(type(httplib) == types.ModuleType) self.assertTrue(httplib.__name__ == 'httplib') @@ -59,12 +55,12 @@ def testSimpleImportWithAlias(self): self.assertTrue(type(mySys) == types.ModuleType) self.assertTrue(mySys.__name__ == 'sys') - if six.PY3: + if PY3: import http.client as myHttplib self.assertTrue(type(myHttplib) == types.ModuleType) self.assertTrue(myHttplib.__name__ == 'http.client') - else: + elif PY2: import httplib as myHttplib self.assertTrue(type(myHttplib) == types.ModuleType) self.assertTrue(myHttplib.__name__ == 'httplib') diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index ba45d8e34..9aceb9c11 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -3,11 +3,7 @@ import unittest from Python.Test import ConversionTest import System -import six - -if six.PY3: - long = int - unichr = chr +from _compat import indexbytes, long, unichr class ConversionTests(unittest.TestCase): @@ -171,16 +167,16 @@ def testCharConversion(self): self.assertTrue(System.Char.MinValue == unichr(0)) object = ConversionTest() - self.assertTrue(object.CharField == six.u('A')) + self.assertTrue(object.CharField == u'A') object.CharField = 'B' - self.assertTrue(object.CharField == six.u('B')) + self.assertTrue(object.CharField == u'B') - object.CharField = six.u('B') - self.assertTrue(object.CharField == six.u('B')) + object.CharField = u'B' + self.assertTrue(object.CharField == u'B') object.CharField = 67 - self.assertTrue(object.CharField == six.u('C')) + self.assertTrue(object.CharField == u'C') def test(): ConversionTest().CharField = 65536 @@ -644,25 +640,25 @@ def testStringConversion(self): object = ConversionTest() self.assertTrue(object.StringField == "spam") - self.assertTrue(object.StringField == six.u("spam")) + self.assertTrue(object.StringField == u"spam") object.StringField = "eggs" self.assertTrue(object.StringField == "eggs") - self.assertTrue(object.StringField == six.u("eggs")) + self.assertTrue(object.StringField == u"eggs") - object.StringField = six.u("spam") + object.StringField = u"spam" self.assertTrue(object.StringField == "spam") - self.assertTrue(object.StringField == six.u("spam")) + self.assertTrue(object.StringField == u"spam") - object.StringField = six.u('\uffff\uffff') - self.assertTrue(object.StringField == six.u('\uffff\uffff')) + object.StringField = u'\uffff\uffff' + self.assertTrue(object.StringField == u'\uffff\uffff') object.StringField = System.String("spam") self.assertTrue(object.StringField == "spam") - self.assertTrue(object.StringField == six.u("spam")) + self.assertTrue(object.StringField == u"spam") - object.StringField = System.String(six.u('\uffff\uffff')) - self.assertTrue(object.StringField == six.u('\uffff\uffff')) + object.StringField = System.String(u'\uffff\uffff') + self.assertTrue(object.StringField == u'\uffff\uffff') object.StringField = None self.assertTrue(object.StringField == None) @@ -809,11 +805,11 @@ def testByteArrayConversion(self): self.assertTrue(array[0] == 0) self.assertTrue(array[4] == 4) - value = six.b("testing") + value = b"testing" object.ByteArrayField = value array = object.ByteArrayField for i in range(len(value)): - self.assertTrue(array[i] == six.indexbytes(value, i)) + self.assertTrue(array[i] == indexbytes(value, i)) def testSByteArrayConversion(self): """Test sbyte array conversion.""" @@ -827,11 +823,11 @@ def testSByteArrayConversion(self): self.assertTrue(array[0] == 0) self.assertTrue(array[4] == 4) - value = six.b("testing") + value = b"testing" object.SByteArrayField = value array = object.SByteArrayField for i in range(len(value)): - self.assertTrue(array[i] == six.indexbytes(value, i)) + self.assertTrue(array[i] == indexbytes(value, i)) def test_suite(): diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index 1123bfdb5..c9816da03 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -4,15 +4,9 @@ from Python.Test import StringDelegate, ObjectDelegate from Python.Test import BoolDelegate import unittest -import types import Python.Test as Test import System -import six - -if six.PY3: - DictProxyType = type(object.__dict__) -else: - DictProxyType = types.DictProxyType +from _compat import DictProxyType class DelegateTests(unittest.TestCase): diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index 6eb7e7592..dfc55a655 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -1,16 +1,9 @@ # -*- coding: utf-8 -*- import unittest -import types from System import DayOfWeek from Python import Test -import six - -if six.PY3: - DictProxyType = type(object.__dict__) - long = int -else: - DictProxyType = types.DictProxyType +from _compat import DictProxyType, long class EnumTests(unittest.TestCase): diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index 9509cef95..0c4078fb5 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -3,10 +3,7 @@ import sys import unittest import System -import six - -if six.PY3: - unicode = str +from _compat import PY2, PY3, pickle, text_type class ExceptionTests(unittest.TestCase): @@ -17,7 +14,7 @@ def testUnifiedExceptionSemantics(self): from System import Exception, Object e = Exception('Something bad happened') - if not six.PY3: + if PY2: import exceptions self.assertTrue(isinstance(e, exceptions.Exception)) self.assertTrue(isinstance(e, Exception)) @@ -212,9 +209,9 @@ def testCatchExceptionManagedClass(self): def testCatchExceptionPythonClass(self): """Test catching the python class of an exception.""" from System import OverflowException - if six.PY3: + if PY3: from builtins import Exception - else: + elif PY2: from exceptions import Exception try: @@ -288,8 +285,8 @@ def testStrOfException(self): Convert.ToDateTime('this will fail') except FormatException: e = sys.exc_info()[1] - msg = unicode(e).encode("utf8") # fix for international installation - self.assertTrue(msg.find(unicode('System.Convert.ToDateTime').encode("utf8")) > -1, msg) + msg = text_type(e).encode("utf8") # fix for international installation + self.assertTrue(msg.find(text_type('System.Convert.ToDateTime').encode("utf8")) > -1, msg) def testPythonCompatOfManagedExceptions(self): """Test if managed exceptions are compatible with Python's implementation @@ -299,14 +296,14 @@ def testPythonCompatOfManagedExceptions(self): e = OverflowException(msg) self.assertEqual(str(e), msg) - self.assertEqual(unicode(e), msg) + self.assertEqual(text_type(e), msg) self.assertEqual(e.args, (msg,)) self.assertTrue(isinstance(e.args, tuple)) - if six.PY2: - self.assertEqual(repr(e), "OverflowException(u'A simple message',)") - else: + if PY3: self.assertEqual(repr(e), "OverflowException('A simple message',)") + elif PY2: + self.assertEqual(repr(e), "OverflowException(u'A simple message',)") def testExceptionIsInstanceOfSystemObject(self): """Test behavior of isinstance(, System.Object).""" @@ -337,10 +334,6 @@ def testExceptionIsInstanceOfSystemObject(self): def testPicklingExceptions(self): from System import Exception - try: - import cPickle as pickle - except ImportError: - import pickle exc = Exception("test") dumped = pickle.dumps(exc) @@ -349,7 +342,8 @@ def testPicklingExceptions(self): self.assertEqual(exc.args, loaded.args) def testChainedExceptions(self): - if six.PY3: + # TODO: Why is this test PY3 only? + if PY3: from Python.Test import ExceptionTest try: @@ -358,7 +352,7 @@ def testChainedExceptions(self): msgs = [ "Outer exception", "Inner exception", - "Innermost exception" + "Innermost exception", ] for msg in msgs: diff --git a/src/tests/test_field.py b/src/tests/test_field.py index bafb27598..3cd7eb83e 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -1,16 +1,9 @@ # -*- coding: utf-8 -*- import unittest -import types from Python.Test import FieldTest from Python.Test import ShortEnum import System -import six - -if six.PY3: - IntType = int -else: - IntType = types.IntType class FieldTests(unittest.TestCase): @@ -203,15 +196,15 @@ def testFieldDescriptorGetSet(self): self.assertTrue(object.PublicStaticField == 0) descriptor = FieldTest.__dict__['PublicStaticField'] - self.assertTrue(type(descriptor) != IntType) + self.assertTrue(type(descriptor) != int) object.PublicStaticField = 0 descriptor = FieldTest.__dict__['PublicStaticField'] - self.assertTrue(type(descriptor) != IntType) + self.assertTrue(type(descriptor) != int) FieldTest.PublicStaticField = 0 descriptor = FieldTest.__dict__['PublicStaticField'] - self.assertTrue(type(descriptor) != IntType) + self.assertTrue(type(descriptor) != int) def testFieldDescriptorWrongType(self): """Test setting a field using a value of the wrong type.""" @@ -272,15 +265,15 @@ def testByteField(self): def testCharField(self): """Test char fields.""" object = FieldTest() - self.assertTrue(object.CharField == six.u('A')) + self.assertTrue(object.CharField == u'A') self.assertTrue(object.CharField == 'A') object.CharField = 'B' - self.assertTrue(object.CharField == six.u('B')) + self.assertTrue(object.CharField == u'B') self.assertTrue(object.CharField == 'B') - object.CharField = six.u('C') - self.assertTrue(object.CharField == six.u('C')) + object.CharField = u'C' + self.assertTrue(object.CharField == u'C') self.assertTrue(object.CharField == 'C') def testInt16Field(self): diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index c80ff5704..eb87c5271 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -5,12 +5,7 @@ import unittest import Python.Test as Test import System -import six - -if six.PY3: - long = int - unichr = chr - unicode = str +from _compat import PY2, long, unichr, unicode class GenericTests(unittest.TestCase): @@ -171,13 +166,13 @@ def testGenericTypeBinding(self): self._testGenericWrapperByType(bool, True) self._testGenericWrapperByType(System.Byte, 255) self._testGenericWrapperByType(System.SByte, 127) - self._testGenericWrapperByType(System.Char, six.u('A')) + self._testGenericWrapperByType(System.Char, u'A') self._testGenericWrapperByType(System.Int16, 32767) self._testGenericWrapperByType(System.Int32, 2147483647) self._testGenericWrapperByType(int, 2147483647) self._testGenericWrapperByType(System.Int64, long(9223372036854775807)) # Python 3 has no explicit long type, use System.Int64 instead - if not six.PY3: + if PY2: self._testGenericWrapperByType(long, long(9223372036854775807)) self._testGenericWrapperByType(System.UInt16, 65000) self._testGenericWrapperByType(System.UInt32, long(4294967295)) @@ -318,12 +313,12 @@ def testGenericMethodTypeHandling(self): self._testGenericMethodByType(bool, True) self._testGenericMethodByType(System.Byte, 255) self._testGenericMethodByType(System.SByte, 127) - self._testGenericMethodByType(System.Char, six.u('A')) + self._testGenericMethodByType(System.Char, u'A') self._testGenericMethodByType(System.Int16, 32767) self._testGenericMethodByType(System.Int32, 2147483647) self._testGenericMethodByType(int, 2147483647) # Python 3 has no explicit long type, use System.Int64 instead - if not six.PY3: + if PY2: self._testGenericMethodByType(System.Int64, long(9223372036854775807)) self._testGenericMethodByType(long, long(9223372036854775807)) self._testGenericMethodByType(System.UInt32, long(4294967295)) @@ -367,7 +362,7 @@ def testCorrectOverloadSelection(self): atype(value2)) == Math.Max.__overloads__[atype, atype]( atype(value1), atype(value2))) - if (atype is Int64) and six.PY2: + if PY2 and atype is Int64: value2 = long(value2) self.assertTrue( Math.Max(atype(value1), @@ -490,9 +485,9 @@ def testMethodOverloadSelectionWithGenericTypes(self): self.assertTrue(value.value == 127) vtype = GenericWrapper[System.Char] - input = vtype(six.u('A')) + input = vtype(u'A') value = MethodTest.Overloaded.__overloads__[vtype](input) - self.assertTrue(value.value == six.u('A')) + self.assertTrue(value.value == u'A') vtype = GenericWrapper[System.Char] input = vtype(65535) @@ -520,7 +515,7 @@ def testMethodOverloadSelectionWithGenericTypes(self): self.assertTrue(value.value == long(9223372036854775807)) # Python 3 has no explicit long type, use System.Int64 instead - if not six.PY3: + if PY2: vtype = GenericWrapper[long] input = vtype(long(9223372036854775807)) value = MethodTest.Overloaded.__overloads__[vtype](input) @@ -633,9 +628,9 @@ def testOverloadSelectionWithArraysOfGenericTypes(self): gtype = GenericWrapper[System.Char] vtype = System.Array[gtype] - input = vtype([gtype(six.u('A')), gtype(six.u('A'))]) + input = vtype([gtype(u'A'), gtype(u'A')]) value = MethodTest.Overloaded.__overloads__[vtype](input) - self.assertTrue(value[0].value == six.u('A')) + self.assertTrue(value[0].value == u'A') self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Char] @@ -675,7 +670,7 @@ def testOverloadSelectionWithArraysOfGenericTypes(self): self.assertTrue(value.Length == 2) # Python 3 has no explicit long type, use System.Int64 instead - if not six.PY3: + if PY2: gtype = GenericWrapper[long] vtype = System.Array[gtype] input = vtype([gtype(long(9223372036854775807)), diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index f9d16a1c3..b241ef366 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -3,11 +3,7 @@ import unittest import Python.Test as Test -import six - -if six.PY3: - long = int - unichr = chr +from _compat import long, unichr class IndexerTests(unittest.TestCase): @@ -413,19 +409,19 @@ def testStringIndexer(self): object = Test.StringIndexerTest() self.assertTrue(object["spam"] == None) - self.assertTrue(object[six.u("spam")] == None) + self.assertTrue(object[u"spam"] == None) object["spam"] = "spam" self.assertTrue(object["spam"] == "spam") - self.assertTrue(object["spam"] == six.u("spam")) - self.assertTrue(object[six.u("spam")] == "spam") - self.assertTrue(object[six.u("spam")] == six.u("spam")) + self.assertTrue(object["spam"] == u"spam") + self.assertTrue(object[u"spam"] == "spam") + self.assertTrue(object[u"spam"] == u"spam") - object[six.u("eggs")] = six.u("eggs") + object[u"eggs"] = u"eggs" self.assertTrue(object["eggs"] == "eggs") - self.assertTrue(object["eggs"] == six.u("eggs")) - self.assertTrue(object[six.u("eggs")] == "eggs") - self.assertTrue(object[six.u("eggs")] == six.u("eggs")) + self.assertTrue(object["eggs"] == u"eggs") + self.assertTrue(object[u"eggs"] == "eggs") + self.assertTrue(object[u"eggs"] == u"eggs") def test(): object = Test.StringIndexerTest() diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index 6c6bb6228..13878efbf 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -2,15 +2,9 @@ from Python.Test import InterfaceTest import unittest -import types import Python.Test as Test import System -import six - -if six.PY3: - DictProxyType = type(object.__dict__) -else: - DictProxyType = types.DictProxyType +from _compat import DictProxyType class InterfaceTests(unittest.TestCase): diff --git a/src/tests/test_method.py b/src/tests/test_method.py index f6806687c..67cb9d4a1 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -4,11 +4,8 @@ from Python.Test import MethodTest, MethodTestSub import System -import six -if six.PY3: - long = int - unichr = chr +from _compat import PY2, long, unichr class MethodTests(unittest.TestCase): @@ -495,8 +492,8 @@ def testExplicitOverloadSelection(self): value = MethodTest.Overloaded.__overloads__[System.SByte](127) self.assertTrue(value == 127) - value = MethodTest.Overloaded.__overloads__[System.Char](six.u('A')) - self.assertTrue(value == six.u('A')) + value = MethodTest.Overloaded.__overloads__[System.Char](u'A') + self.assertTrue(value == u'A') value = MethodTest.Overloaded.__overloads__[System.Char](65535) self.assertTrue(value == unichr(65535)) @@ -516,7 +513,7 @@ def testExplicitOverloadSelection(self): self.assertTrue(value == long(9223372036854775807)) # Python 3 has no explicit long type, use System.Int64 instead - if not six.PY3: + if PY2: value = MethodTest.Overloaded.__overloads__[long]( long(9223372036854775807) ) @@ -612,10 +609,10 @@ def testOverloadSelectionWithArrayTypes(self): self.assertTrue(value[1] == 127) vtype = Array[System.Char] - input = vtype([six.u('A'), six.u('Z')]) + input = vtype([u'A', u'Z']) value = MethodTest.Overloaded.__overloads__[vtype](input) - self.assertTrue(value[0] == six.u('A')) - self.assertTrue(value[1] == six.u('Z')) + self.assertTrue(value[0] == u'A') + self.assertTrue(value[1] == u'Z') vtype = Array[System.Char] input = vtype([0, 65535]) @@ -648,7 +645,7 @@ def testOverloadSelectionWithArrayTypes(self): self.assertTrue(value[1] == long(9223372036854775807)) # Python 3 has no explicit long type, use System.Int64 instead - if not six.PY3: + if PY2: vtype = Array[long] input = vtype([0, long(9223372036854775807)]) value = MethodTest.Overloaded.__overloads__[vtype](input) diff --git a/src/tests/test_module.py b/src/tests/test_module.py index 8eaedf5c9..caa94b1d5 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -6,12 +6,8 @@ import types import warnings from fnmatch import fnmatch -import six -if six.PY3: - ClassType = type -else: - ClassType = types.ClassType +from _compat import ClassType, PY2, PY3 # testImplicitAssemblyLoad() passes on deprecation warning; perfect! # # clr.AddReference('System.Windows.Forms') @@ -24,10 +20,11 @@ def isCLRModule(self, object): return type(object).__name__ == 'ModuleObject' def isCLRRootModule(self, object): - if six.PY3: + if PY3: # in Python 3 the clr module is a normal python module return object.__name__ == "clr" - return type(object).__name__ == 'CLRModule' + elif PY2: + return type(object).__name__ == 'CLRModule' def isCLRClass(self, object): return type(object).__name__ == 'CLR Metatype' # for now @@ -90,11 +87,11 @@ def testSimpleImport(self): self.assertTrue(type(sys) == types.ModuleType) self.assertTrue(sys.__name__ == 'sys') - if six.PY3: + if PY3: import http.client as httplib self.assertTrue(type(httplib) == types.ModuleType) self.assertTrue(httplib.__name__ == 'http.client') - else: + elif PY2: import httplib self.assertTrue(type(httplib) == types.ModuleType) self.assertTrue(httplib.__name__ == 'httplib') @@ -109,11 +106,11 @@ def testSimpleImportWithAlias(self): self.assertTrue(type(mySys) == types.ModuleType) self.assertTrue(mySys.__name__ == 'sys') - if six.PY3: + if PY3: import http.client as myHttplib self.assertTrue(type(myHttplib) == types.ModuleType) self.assertTrue(myHttplib.__name__ == 'http.client') - else: + elif PY2: import httplib as myHttplib self.assertTrue(type(myHttplib) == types.ModuleType) self.assertTrue(myHttplib.__name__ == 'httplib') @@ -346,10 +343,10 @@ def test_ClrListAssemblies(self): from clr import ListAssemblies verbose = list(ListAssemblies(True)) short = list(ListAssemblies(False)) - self.assertTrue(six.u('mscorlib') in short) - self.assertTrue(six.u('System') in short) - self.assertTrue(six.u('Culture=') in verbose[0]) - self.assertTrue(six.u('Version=') in verbose[0]) + self.assertTrue(u'mscorlib' in short) + self.assertTrue(u'System' in short) + self.assertTrue(u'Culture=' in verbose[0]) + self.assertTrue(u'Version=' in verbose[0]) def test_ClrAddReference(self): from clr import AddReference diff --git a/src/tests/test_property.py b/src/tests/test_property.py index 9ed2a5207..1358f0fe5 100644 --- a/src/tests/test_property.py +++ b/src/tests/test_property.py @@ -1,14 +1,7 @@ # -*- coding: utf-8 -*- # import unittest -import types from Python.Test import PropertyTest -import six - -if six.PY3: - IntType = int -else: - IntType = types.IntType class PropertyTests(unittest.TestCase): @@ -133,15 +126,15 @@ def testPropertyDescriptorGetSet(self): self.assertTrue(object.PublicStaticProperty == 0) descriptor = PropertyTest.__dict__['PublicStaticProperty'] - self.assertTrue(type(descriptor) != IntType) + self.assertTrue(type(descriptor) != int) object.PublicStaticProperty = 0 descriptor = PropertyTest.__dict__['PublicStaticProperty'] - self.assertTrue(type(descriptor) != IntType) + self.assertTrue(type(descriptor) != int) PropertyTest.PublicStaticProperty = 0 descriptor = PropertyTest.__dict__['PublicStaticProperty'] - self.assertTrue(type(descriptor) != IntType) + self.assertTrue(type(descriptor) != int) def testPropertyDescriptorWrongType(self): """Test setting a property using a value of the wrong type.""" diff --git a/src/tests/test_thread.py b/src/tests/test_thread.py index ba91e3bee..09104a91a 100644 --- a/src/tests/test_thread.py +++ b/src/tests/test_thread.py @@ -4,14 +4,10 @@ import unittest from Python.Test import ThreadTest -import six import threading import time -if six.PY3: - import _thread as thread -else: - import thread +from _compat import thread def dprint(msg): From b7bfd2def801e9988bea45c2eaa0aa4e63cebca5 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 21 Jan 2017 19:30:25 -0700 Subject: [PATCH 037/245] Clean-up imports - Fix py2/py3 range/zip behavior - Ensure same functions being used - Fix Exception/System.Exception name clashes --- src/tests/test_array.py | 4 +- src/tests/test_class.py | 31 ++++++++----- src/tests/test_compat.py | 5 ++- src/tests/test_constructors.py | 1 + src/tests/test_conversion.py | 6 ++- src/tests/test_delegate.py | 11 +++-- src/tests/test_docstring.py | 8 +++- src/tests/test_engine.py | 5 ++- src/tests/test_enum.py | 12 ++++- src/tests/test_event.py | 10 +++-- src/tests/test_exceptions.py | 18 +++----- src/tests/test_field.py | 6 ++- src/tests/test_generic.py | 46 ++++++++------------ src/tests/test_indexer.py | 1 + src/tests/test_interface.py | 18 +++++--- src/tests/test_method.py | 5 ++- src/tests/test_module.py | 8 ++-- src/tests/test_property.py | 1 + src/tests/test_subclass.py | 26 ++++++----- src/tests/test_suite/__init__.py | 4 +- src/tests/test_suite/test_callback.py | 15 +++---- src/tests/test_suite/test_recursive_types.py | 9 +--- src/tests/test_thread.py | 19 ++++---- 23 files changed, 151 insertions(+), 118 deletions(-) diff --git a/src/tests/test_array.py b/src/tests/test_array.py index 03440ca6e..0a4270636 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -1,9 +1,11 @@ # -*- coding: utf-8 -*- import unittest + import Python.Test as Test import System -from _compat import UserList, PY2, long, unichr + +from _compat import PY2, UserList, long, range, unichr class ArrayTests(unittest.TestCase): diff --git a/src/tests/test_class.py b/src/tests/test_class.py index 30972d111..169683883 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -4,10 +4,8 @@ import Python.Test as Test import System -from Python.Test import ClassTest -from System.Collections import Hashtable -from _compat import DictProxyType +from _compat import DictProxyType, range class ClassTests(unittest.TestCase): @@ -25,6 +23,8 @@ def testBasicValueType(self): def testClassStandardAttrs(self): """Test standard class attributes.""" + from Python.Test import ClassTest + self.assertTrue(ClassTest.__name__ == 'ClassTest') self.assertTrue(ClassTest.__module__ == 'Python.Test') self.assertTrue(type(ClassTest.__dict__) == DictProxyType) @@ -32,6 +32,8 @@ def testClassStandardAttrs(self): def testClassDocstrings(self): """Test standard class docstring generation""" + from Python.Test import ClassTest + value = 'Void .ctor()' self.assertTrue(ClassTest.__doc__ == value) @@ -47,7 +49,6 @@ def testClassDefaultRepr(self): def testNonPublicClass(self): """Test that non-public classes are inaccessible.""" - from Python import Test def test(): from Python.Test import InternalClass @@ -61,6 +62,7 @@ def test(): def testBasicSubclass(self): """Test basic subclass of a managed class.""" + from System.Collections import Hashtable class MyTable(Hashtable): def howMany(self): @@ -141,12 +143,14 @@ def testStructConstruction(self): def testIEnumerableIteration(self): """Test iteration over objects supporting IEnumerable.""" - list = Test.ClassTest.GetArrayList() + from Python.Test import ClassTest + + list = ClassTest.GetArrayList() for item in list: self.assertTrue((item > -1) and (item < 10)) - dict = Test.ClassTest.GetHashtable() + dict = ClassTest.GetHashtable() for item in dict: cname = item.__class__.__name__ @@ -154,13 +158,16 @@ def testIEnumerableIteration(self): def testIEnumeratorIteration(self): """Test iteration over objects supporting IEnumerator.""" - chars = Test.ClassTest.GetEnumerator() + from Python.Test import ClassTest + + chars = ClassTest.GetEnumerator() for item in chars: self.assertTrue(item in 'test string') def testOverrideGetItem(self): """Test managed subclass overriding __getitem__.""" + from System.Collections import Hashtable class MyTable(Hashtable): def __getitem__(self, key): @@ -180,6 +187,7 @@ def __getitem__(self, key): def testOverrideSetItem(self): """Test managed subclass overriding __setitem__.""" + from System.Collections import Hashtable class MyTable(Hashtable): def __setitem__(self, key, value): @@ -198,10 +206,9 @@ def __setitem__(self, key, value): self.assertTrue(table.Count == 3) def testAddAndRemoveClassAttribute(self): - from System import TimeSpan - for i in range(100): + for _ in range(100): TimeSpan.new_method = lambda self: self.TotalMinutes ts = TimeSpan.FromHours(1) self.assertTrue(ts.new_method() == 60) @@ -210,6 +217,7 @@ def testAddAndRemoveClassAttribute(self): def testComparisons(self): from System import DateTimeOffset + from Python.Test import ClassTest d1 = DateTimeOffset.Parse("2016-11-14") d2 = DateTimeOffset.Parse("2016-11-15") @@ -247,12 +255,14 @@ def testComparisons(self): self.assertRaises(TypeError, lambda: c1 < c2) def testSelfCallback(self): - """ Test calling back and forth between this and a c# baseclass.""" + """Test calling back and forth between this and a c# baseclass.""" + class CallbackUser(Test.SelfCallbackTest): def DoCallback(self): self.PyCallbackWasCalled = False self.SameReference = False return self.Callback(self) + def PyCallback(self, self2): self.PyCallbackWasCalled = True self.SameReference = self == self2 @@ -262,6 +272,7 @@ def PyCallback(self, self2): self.assertTrue(testobj.PyCallbackWasCalled) self.assertTrue(testobj.SameReference) + class ClassicClass: def kind(self): return 'classic' diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index 571d54717..f89aceece 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -1,8 +1,9 @@ # -*- coding: utf-8 -*- -import unittest import types -from _compat import PY2, PY3, ClassType +import unittest + +from _compat import ClassType, PY2, PY3, range class CompatibilityTests(unittest.TestCase): diff --git a/src/tests/test_constructors.py b/src/tests/test_constructors.py index e123c7bdc..b1cf6d438 100644 --- a/src/tests/test_constructors.py +++ b/src/tests/test_constructors.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- import unittest + import System diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index 9aceb9c11..7af3ee65e 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -1,9 +1,11 @@ # -*- coding: utf-8 -*- import unittest -from Python.Test import ConversionTest + import System -from _compat import indexbytes, long, unichr +from Python.Test import ConversionTest + +from _compat import indexbytes, long, range, unichr class ConversionTests(unittest.TestCase): diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index c9816da03..df371ca9a 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -1,11 +1,12 @@ # -*- coding: utf-8 -*- +# TODO: Add test for ObjectDelegate -from Python.Test import DelegateTest, PublicDelegate -from Python.Test import StringDelegate, ObjectDelegate -from Python.Test import BoolDelegate import unittest + import Python.Test as Test import System +from Python.Test import DelegateTest, StringDelegate + from _compat import DictProxyType @@ -14,6 +15,8 @@ class DelegateTests(unittest.TestCase): def testDelegateStandardAttrs(self): """Test standard delegate attributes.""" + from Python.Test import PublicDelegate + self.assertTrue(PublicDelegate.__name__ == 'PublicDelegate') self.assertTrue(PublicDelegate.__module__ == 'Python.Test') self.assertTrue(type(PublicDelegate.__dict__) == DictProxyType) @@ -264,6 +267,7 @@ def count(self): def testSubclassDelegateFails(self): """Test that subclassing of a delegate type fails.""" + from Python.Test import PublicDelegate def test(): class Boom(PublicDelegate): @@ -284,6 +288,7 @@ def sayhello(): def testBoolDelegate(self): """Test boolean delegate.""" + from Python.Test import BoolDelegate def always_so_negative(): return 0 diff --git a/src/tests/test_docstring.py b/src/tests/test_docstring.py index d1be3c681..afbd1062f 100644 --- a/src/tests/test_docstring.py +++ b/src/tests/test_docstring.py @@ -2,23 +2,27 @@ import unittest -from Python.Test import DocWithCtorTest, DocWithoutCtorTest, DocWithCtorNoDocTest - class DocStringTests(unittest.TestCase): """Test doc strings support.""" def testDocWithCtor(self): + from Python.Test import DocWithCtorTest + self.assertEqual(DocWithCtorTest.__doc__, 'DocWithCtorTest Class') self.assertEqual(DocWithCtorTest.TestMethod.__doc__, 'DocWithCtorTest TestMethod') self.assertEqual(DocWithCtorTest.StaticTestMethod.__doc__, 'DocWithCtorTest StaticTestMethod') def testDocWithCtorNoDoc(self): + from Python.Test import DocWithCtorNoDocTest + self.assertEqual(DocWithCtorNoDocTest.__doc__, 'Void .ctor(Boolean)') self.assertEqual(DocWithCtorNoDocTest.TestMethod.__doc__, 'Void TestMethod(Double, Int32)') self.assertEqual(DocWithCtorNoDocTest.StaticTestMethod.__doc__, 'Void StaticTestMethod(Double, Int32)') def testDocWithoutCtor(self): + from Python.Test import DocWithoutCtorTest + self.assertEqual(DocWithoutCtorTest.__doc__, 'DocWithoutCtorTest Class') self.assertEqual(DocWithoutCtorTest.TestMethod.__doc__, 'DocWithoutCtorTest TestMethod') self.assertEqual(DocWithoutCtorTest.StaticTestMethod.__doc__, 'DocWithoutCtorTest StaticTestMethod') diff --git a/src/tests/test_engine.py b/src/tests/test_engine.py index c38a471fe..274dfb704 100644 --- a/src/tests/test_engine.py +++ b/src/tests/test_engine.py @@ -1,11 +1,12 @@ # -*- coding: utf-8 -*- +# FIXME: This test module fails due to unhandled exceptions import sys import unittest -from Python.Runtime import PythonEngine +import System +from Python.Runtime import PythonEngine -# XXX This test module isn't used! class EngineTests(unittest.TestCase): """Test PythonEngine embedding APIs.""" diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index dfc55a655..589fc1796 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -1,8 +1,9 @@ # -*- coding: utf-8 -*- import unittest -from System import DayOfWeek -from Python import Test + +import Python.Test as Test + from _compat import DictProxyType, long @@ -11,6 +12,8 @@ class EnumTests(unittest.TestCase): def testEnumStandardAttrs(self): """Test standard enum attributes.""" + from System import DayOfWeek + self.assertTrue(DayOfWeek.__name__ == 'DayOfWeek') self.assertTrue(DayOfWeek.__module__ == 'System') self.assertTrue(type(DayOfWeek.__dict__) == DictProxyType) @@ -18,6 +21,8 @@ def testEnumStandardAttrs(self): def testEnumGetMember(self): """Test access to enum members.""" + from System import DayOfWeek + self.assertTrue(DayOfWeek.Sunday == 0) self.assertTrue(DayOfWeek.Monday == 1) self.assertTrue(DayOfWeek.Tuesday == 2) @@ -76,6 +81,7 @@ def testULongEnum(self): def testInstantiateEnumFails(self): """Test that instantiation of an enum class fails.""" + from System import DayOfWeek def test(): ob = DayOfWeek() @@ -84,6 +90,7 @@ def test(): def testSubclassEnumFails(self): """Test that subclassing of an enumeration fails.""" + from System import DayOfWeek def test(): class Boom(DayOfWeek): @@ -93,6 +100,7 @@ class Boom(DayOfWeek): def testEnumSetMemberFails(self): """Test that setattr operations on enumerations fail.""" + from System import DayOfWeek def test(): DayOfWeek.Sunday = 13 diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 2ddcc55d8..5417b4a8f 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -1,8 +1,10 @@ # -*- coding: utf-8 -*- import unittest -from Python.Test import EventTest, TestEventHandler -from Python.Test import TestEventArgs + +from Python.Test import EventTest, TestEventArgs + +from _compat import range class EventTests(unittest.TestCase): @@ -515,7 +517,7 @@ def test(): object.PublicEvent -= handler.handler def testIncorrectInvokation(self): - """Test incorrect invokation of events.""" + """Test incorrect invocation of events.""" object = EventTest() handler = GenericHandler() @@ -535,6 +537,8 @@ def test(): def testExplicitCLSEventRegistration(self): """Test explicit CLS event registration.""" + from Python.Test import TestEventHandler + object = EventTest() handler = GenericHandler() diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index 0c4078fb5..647106a70 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -2,7 +2,9 @@ import sys import unittest + import System + from _compat import PY2, PY3, pickle, text_type @@ -11,13 +13,9 @@ class ExceptionTests(unittest.TestCase): def testUnifiedExceptionSemantics(self): """Test unified exception semantics.""" - from System import Exception, Object - - e = Exception('Something bad happened') - if PY2: - import exceptions - self.assertTrue(isinstance(e, exceptions.Exception)) + e = System.Exception('Something bad happened') self.assertTrue(isinstance(e, Exception)) + self.assertTrue(isinstance(e, System.Exception)) def testStandardExceptionAttributes(self): """Test accessing standard exception attributes.""" @@ -38,12 +36,12 @@ def testStandardExceptionAttributes(self): def testExtendedExceptionAttributes(self): """Test accessing extended exception attributes.""" from Python.Test import ExceptionTest, ExtendedException - from System import Exception, OverflowException + from System import OverflowException e = ExceptionTest.GetExtendedException() self.assertTrue(isinstance(e, ExtendedException)) self.assertTrue(isinstance(e, OverflowException)) - self.assertTrue(isinstance(e, Exception)) + self.assertTrue(isinstance(e, System.Exception)) self.assertTrue(e.Message == 'error') @@ -333,9 +331,7 @@ def testExceptionIsInstanceOfSystemObject(self): self.assertFalse(isinstance(o, Object)) def testPicklingExceptions(self): - from System import Exception - - exc = Exception("test") + exc = System.Exception("test") dumped = pickle.dumps(exc) loaded = pickle.loads(dumped) diff --git a/src/tests/test_field.py b/src/tests/test_field.py index 3cd7eb83e..8a2c0c67a 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- import unittest -from Python.Test import FieldTest -from Python.Test import ShortEnum + import System +from Python.Test import FieldTest class FieldTests(unittest.TestCase): @@ -385,6 +385,8 @@ def testObjectField(self): def testEnumField(self): """Test enum fields.""" + from Python.Test import ShortEnum + object = FieldTest() self.assertTrue(object.EnumField == ShortEnum.Zero) diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index eb87c5271..67af8acb4 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- import clr -from System.Collections.Generic import Dictionary, List import unittest -import Python.Test as Test + import System -from _compat import PY2, long, unichr, unicode + +from _compat import PY2, long, unicode, unichr, zip class GenericTests(unittest.TestCase): @@ -13,6 +13,8 @@ class GenericTests(unittest.TestCase): def testPythonTypeAliasing(self): """Test python type alias support with generics.""" + from System.Collections.Generic import Dictionary + dict = Dictionary[str, str]() self.assertEquals(dict.Count, 0) dict.Add("one", "one") @@ -66,6 +68,7 @@ def testPythonTypeAliasing(self): def testGenericReferenceType(self): """Test usage of generic reference type definitions.""" from Python.Test import GenericTypeDefinition + inst = GenericTypeDefinition[System.String, System.Int32]("one", 2) self.assertTrue(inst.value1 == "one") self.assertTrue(inst.value2 == 2) @@ -83,9 +86,7 @@ def testGenericDelegate(self): pass def testOpenGenericType(self): - """ - Test behavior of reflected open constructed generic types. - """ + """Test behavior of reflected open constructed generic types.""" from Python.Test import DerivedFromOpenGeneric OpenGenericType = DerivedFromOpenGeneric.__bases__[0] @@ -101,9 +102,7 @@ def test(): self.assertRaises(TypeError, test) def testDerivedFromOpenGenericType(self): - """ - Test a generic type derived from an open generic type. - """ + """Test a generic type derived from an open generic type.""" from Python.Test import DerivedFromOpenGeneric type = DerivedFromOpenGeneric[System.String, System.String] @@ -114,9 +113,7 @@ def testDerivedFromOpenGenericType(self): self.assertTrue(inst.value3 == 'three') def testGenericTypeNameResolution(self): - """ - Test the ability to disambiguate generic type names. - """ + """Test the ability to disambiguate generic type names.""" from Python.Test import GenericNameTest1, GenericNameTest2 # If both a non-generic and generic type exist for a name, the @@ -156,9 +153,7 @@ def _testGenericWrapperByType(self, ptype, value, test_type=0): self.assertTrue(inst.value[1] == value) def testGenericTypeBinding(self): - """ - Test argument conversion / binding for generic methods. - """ + """Test argument conversion / binding for generic methods.""" from Python.Test import InterfaceTest, ISayHello1, ShortEnum import System @@ -300,15 +295,13 @@ def test(): self.assertRaises(TypeError, test) def testGenericMethodTypeHandling(self): - """ - Test argument conversion / binding for generic methods. - """ + """Test argument conversion / binding for generic methods.""" from Python.Test import InterfaceTest, ISayHello1, ShortEnum import System # XXX BUG: The value doesn't fit into Int64 and PythonNet doesn't # recognize it as UInt64 for unknown reasons. - ## self._testGenericMethodByType(System.UInt64, 18446744073709551615L) + # self._testGenericMethodByType(System.UInt64, 18446744073709551615L) self._testGenericMethodByType(System.Boolean, True) self._testGenericMethodByType(bool, True) self._testGenericMethodByType(System.Byte, 255) @@ -337,9 +330,7 @@ def testGenericMethodTypeHandling(self): self._testGenericMethodByType(ISayHello1, InterfaceTest(), 1) def testCorrectOverloadSelection(self): - """ - Test correct overloading selection for common types. - """ + """Test correct overloading selection for common types.""" from System.Drawing import Font from System import (String, Double, Single, @@ -377,10 +368,9 @@ def testCorrectOverloadSelection(self): handler = GCHandle.Alloc(CSArray, GCHandleType.Pinned) def testGenericMethodOverloadSelection(self): - """ - Test explicit overload selection with generic methods. - """ + """Test explicit overload selection with generic methods.""" from Python.Test import GenericMethodTest, GenericStaticMethodTest + type = GenericStaticMethodTest[str] inst = GenericMethodTest[str]() @@ -462,6 +452,7 @@ def testMethodOverloadSelectionWithGenericTypes(self): """Check method overload selection using generic types.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from Python.Test import MethodTest, GenericWrapper + inst = InterfaceTest() vtype = GenericWrapper[System.Boolean] @@ -596,6 +587,7 @@ def testOverloadSelectionWithArraysOfGenericTypes(self): """Check overload selection using arrays of generic types.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from Python.Test import MethodTest, GenericWrapper + inst = InterfaceTest() gtype = GenericWrapper[System.Boolean] @@ -776,12 +768,12 @@ def testOverloadSelectionWithArraysOfGenericTypes(self): def testGenericOverloadSelectionMagicNameOnly(self): """Test using only __overloads__ to select on type & sig""" - # XXX NotImplemented + # TODO NotImplemented pass def testNestedGenericClass(self): """Check nested generic classes.""" - # XXX NotImplemented + # TODO NotImplemented pass diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index b241ef366..74c9b1876 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -3,6 +3,7 @@ import unittest import Python.Test as Test + from _compat import long, unichr diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index 13878efbf..6bc05fd5f 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- -from Python.Test import InterfaceTest import unittest + import Python.Test as Test -import System + from _compat import DictProxyType @@ -12,14 +12,16 @@ class InterfaceTests(unittest.TestCase): def testInterfaceStandardAttrs(self): """Test standard class attributes.""" - from Python.Test import IPublicInterface as ip - self.assertTrue(ip.__name__ == 'IPublicInterface') - self.assertTrue(ip.__module__ == 'Python.Test') - self.assertTrue(type(ip.__dict__) == DictProxyType) + from Python.Test import IPublicInterface + + self.assertTrue(IPublicInterface.__name__ == 'IPublicInterface') + self.assertTrue(IPublicInterface.__module__ == 'Python.Test') + self.assertTrue(type(IPublicInterface.__dict__) == DictProxyType) def testGlobalInterfaceVisibility(self): """Test visibility of module-level interfaces.""" from Python.Test import IPublicInterface + self.assertTrue(IPublicInterface.__name__ == 'IPublicInterface') def test(): @@ -34,6 +36,8 @@ def test(): def testNestedInterfaceVisibility(self): """Test visibility of nested interfaces.""" + from Python.Test import InterfaceTest + ob = InterfaceTest.IPublic self.assertTrue(ob.__name__ == 'IPublic') @@ -52,6 +56,8 @@ def test(): def testExplicitCastToInterface(self): """Test explicit cast to an interface.""" + from Python.Test import InterfaceTest + ob = InterfaceTest() self.assertTrue(type(ob).__name__ == 'InterfaceTest') self.assertTrue(hasattr(ob, 'HelloProperty')) diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 67cb9d4a1..88652cd71 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -2,8 +2,8 @@ import unittest -from Python.Test import MethodTest, MethodTestSub import System +from Python.Test import MethodTest from _compat import PY2, long, unichr @@ -128,6 +128,7 @@ def test(): def testUnboundManagedMethodCall(self): """Test calling unbound managed methods.""" + from Python.Test import MethodTestSub object = MethodTest() self.assertTrue(MethodTest.PublicMethod(object) == "public") @@ -148,6 +149,7 @@ def test(): def testOverloadedMethodInheritance(self): """Test that overloads are inherited properly.""" + from Python.Test import MethodTestSub object = MethodTest() self.assertTrue(object.PublicMethod() == "public") @@ -778,5 +780,6 @@ def testWeCanBindToEncodingGetString(self): data = ''.join(data) self.assertEqual(data, 'Some testing string') + def test_suite(): return unittest.makeSuite(MethodTests) diff --git a/src/tests/test_module.py b/src/tests/test_module.py index caa94b1d5..a2624fc4c 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -1,13 +1,13 @@ # -*- coding: utf-8 -*- import clr - -import unittest import types +import unittest import warnings from fnmatch import fnmatch -from _compat import ClassType, PY2, PY3 +from _compat import ClassType, PY2, PY3, range + # testImplicitAssemblyLoad() passes on deprecation warning; perfect! # # clr.AddReference('System.Windows.Forms') @@ -372,7 +372,7 @@ def test_AssemblyLoadThreadSafety(self): from System import DateTime from System import Guid from System.Collections.Generic import Dictionary - dict = Dictionary[Guid,DateTime]() + dict = Dictionary[Guid, DateTime]() ModuleTest.JoinThreads() diff --git a/src/tests/test_property.py b/src/tests/test_property.py index 1358f0fe5..e5d7112ef 100644 --- a/src/tests/test_property.py +++ b/src/tests/test_property.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- # import unittest + from Python.Test import PropertyTest diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index f99c4cdc6..20938ba88 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -1,10 +1,14 @@ # -*- coding: utf-8 -*- +# FIXME: This test module fails on Linux -import clr import unittest -from Python.Test import TestFunctions, SubClassTest, IInterfaceTest, TestEventArgs + +import System +from Python.Test import (IInterfaceTest, SubClassTest, TestEventArgs, + TestFunctions) from System.Collections.Generic import List -from System import NotImplementedException + +from _compat import range # class that implements the test interface @@ -137,7 +141,8 @@ def handler(self, x, args): self.assertEqual(event_handler.value, 1) i = InterfaceTestClass() - self.assertRaises(NotImplementedException, TestFunctions.test_event, i, 2) + with self.assertRaises(System.NotImplementedException): + TestFunctions.test_event(i, 2) d = DerivedEventTest() d.add_TestEvent(event_handler.handler) @@ -146,19 +151,16 @@ def handler(self, x, args): self.assertEqual(len(d.event_handlers), 1) def test_isinstance(self): - from System import Object - from System import String - a = [str(x) for x in range(0, 1000)] - b = [String(x) for x in a] + b = [System.String(x) for x in a] for x in a: - self.assertFalse(isinstance(x, Object)) - self.assertFalse(isinstance(x, String)) + self.assertFalse(isinstance(x, System.Object)) + self.assertFalse(isinstance(x, System.String)) for x in b: - self.assertTrue(isinstance(x, Object)) - self.assertTrue(isinstance(x, String)) + self.assertTrue(isinstance(x, System.Object)) + self.assertTrue(isinstance(x, System.String)) def test_suite(): diff --git a/src/tests/test_suite/__init__.py b/src/tests/test_suite/__init__.py index 16a3a4cf8..ecc1c858f 100644 --- a/src/tests/test_suite/__init__.py +++ b/src/tests/test_suite/__init__.py @@ -2,10 +2,8 @@ import unittest -__all__ = ['test_suite'] - -from .test_import import test_suite as import_tests from .test_callback import test_suite as callback_tests +from .test_import import test_suite as import_tests from .test_recursive_types import test_suite as recursive_types_tests diff --git a/src/tests/test_suite/test_callback.py b/src/tests/test_suite/test_callback.py index 96070012f..7a5e473be 100644 --- a/src/tests/test_suite/test_callback.py +++ b/src/tests/test_suite/test_callback.py @@ -1,15 +1,6 @@ # -*- coding: utf-8 -*- import unittest -import sys -import clr - -this_module = sys.modules[__name__] -clr.AddReference("Python.Test") -import Python.Test as Test -from Python.Test import CallbackTest - -test_instance = CallbackTest() def simpleDefaultArg(arg='test'): @@ -21,12 +12,18 @@ class CallbackTests(unittest.TestCase): def testDefaultForNull(self): """Test that C# can use null for an optional python argument""" + from Python.Test import CallbackTest + + test_instance = CallbackTest() retVal = test_instance.Call_simpleDefaultArg_WithNull(__name__) pythonRetVal = simpleDefaultArg(None) self.assertEquals(retVal, pythonRetVal) def testDefaultForNone(self): """Test that C# can use no argument for an optional python argument""" + from Python.Test import CallbackTest + + test_instance = CallbackTest() retVal = test_instance.Call_simpleDefaultArg_WithEmptyArgs(__name__) pythonRetVal = simpleDefaultArg() self.assertEquals(retVal, pythonRetVal) diff --git a/src/tests/test_suite/test_recursive_types.py b/src/tests/test_suite/test_recursive_types.py index 88656f943..32bcad26e 100644 --- a/src/tests/test_suite/test_recursive_types.py +++ b/src/tests/test_suite/test_recursive_types.py @@ -1,11 +1,6 @@ # -*- coding: utf-8 -*- import unittest -import sys -import clr - -this_module = sys.modules[__name__] -clr.AddReference("Python.Test") class RecursiveTypesTests(unittest.TestCase): @@ -14,12 +9,10 @@ class RecursiveTypesTests(unittest.TestCase): def testRecursiveTypeCreation(self): """Test that a recursive types don't crash with a StackOverflowException""" - - import Python.Test as Test from Python.Test import RecursiveInheritance + test_instance = RecursiveInheritance.SubClass() test_instance.SomeMethod() - pass def test_suite(): diff --git a/src/tests/test_thread.py b/src/tests/test_thread.py index 09104a91a..5f395d9aa 100644 --- a/src/tests/test_thread.py +++ b/src/tests/test_thread.py @@ -2,12 +2,11 @@ from __future__ import print_function -import unittest -from Python.Test import ThreadTest import threading import time +import unittest -from _compat import thread +from _compat import range, thread def dprint(msg): @@ -21,6 +20,8 @@ class ThreadTests(unittest.TestCase): def testSimpleCallbackToPython(self): """Test a call to managed code that then calls back into Python.""" + from Python.Test import ThreadTest + dprint("thread %s SimpleCallBack" % thread.get_ident()) result = ThreadTest.CallEchoString("spam") self.assertTrue(result == "spam") @@ -29,6 +30,8 @@ def testSimpleCallbackToPython(self): def testDoubleCallbackToPython(self): """Test a call to managed code that then calls back into Python that then calls managed code that then calls Python again.""" + from Python.Test import ThreadTest + dprint("thread %s DoubleCallBack" % thread.get_ident()) result = ThreadTest.CallEchoString2("spam") self.assertTrue(result == "spam") @@ -37,7 +40,7 @@ def testDoubleCallbackToPython(self): def testPythonThreadCallsToCLR(self): """Test calls by Python-spawned threads into managed code.""" # This test is very likely to hang if something is wrong ;) - from System import String + import System done = [] @@ -45,15 +48,15 @@ def run_thread(): for i in range(10): time.sleep(0.1) dprint("thread %s %d" % (thread.get_ident(), i)) - mstr = String("thread %s %d" % (thread.get_ident(), i)) + mstr = System.String("thread %s %d" % (thread.get_ident(), i)) dprint(mstr.ToString()) done.append(None) dprint("thread %s %d done" % (thread.get_ident(), i)) def start_threads(count): - for i in range(count): - thread = threading.Thread(target=run_thread) - thread.start() + for _ in range(count): + thread_ = threading.Thread(target=run_thread) + thread_.start() start_threads(5) From 429b51652243346e0330e93ce1e875908f91712d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 21 Jan 2017 21:09:45 -0700 Subject: [PATCH 038/245] Fix nameclash object --- src/tests/test_array.py | 368 ++++++++++++------------- src/tests/test_conversion.py | 500 +++++++++++++++++----------------- src/tests/test_enum.py | 8 +- src/tests/test_event.py | 300 ++++++++++----------- src/tests/test_field.py | 232 ++++++++-------- src/tests/test_indexer.py | 510 +++++++++++++++++------------------ src/tests/test_method.py | 60 ++--- src/tests/test_property.py | 56 ++-- src/tests/test_subclass.py | 88 +++--- 9 files changed, 1061 insertions(+), 1061 deletions(-) diff --git a/src/tests/test_array.py b/src/tests/test_array.py index 0a4270636..134b95557 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -13,8 +13,8 @@ class ArrayTests(unittest.TestCase): def testPublicArray(self): """Test public arrays.""" - object = Test.PublicArrayTest() - items = object.items + ob = Test.PublicArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -35,8 +35,8 @@ def testPublicArray(self): def testProtectedArray(self): """Test protected arrays.""" - object = Test.ProtectedArrayTest() - items = object.items + ob = Test.ProtectedArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -59,8 +59,8 @@ def testInternalArray(self): """Test internal arrays.""" def test(): - object = Test.InternalArrayTest() - items = object.items + ob = Test.InternalArrayTest() + items = ob.items self.assertRaises(AttributeError, test) @@ -68,16 +68,16 @@ def testPrivateArray(self): """Test private arrays.""" def test(): - object = Test.PrivateArrayTest() - items = object.items + ob = Test.PrivateArrayTest() + items = ob.items self.assertRaises(AttributeError, test) def testArrayBoundsChecking(self): """Test array bounds checking.""" - object = Test.Int32ArrayTest() - items = object.items + ob = Test.Int32ArrayTest() + items = ob.items self.assertTrue(items[0] == 0) self.assertTrue(items[1] == 1) @@ -92,25 +92,25 @@ def testArrayBoundsChecking(self): self.assertTrue(items[-1] == 4) def test(): - object = Test.Int32ArrayTest() - object.items[5] + ob = Test.Int32ArrayTest() + ob.items[5] self.assertRaises(IndexError, test) def test(): - object = Test.Int32ArrayTest() - object.items[5] = 0 + ob = Test.Int32ArrayTest() + ob.items[5] = 0 self.assertRaises(IndexError, test) def test(): - object = Test.Int32ArrayTest() + ob = Test.Int32ArrayTest() items[-6] self.assertRaises(IndexError, test) def test(): - object = Test.Int32ArrayTest() + ob = Test.Int32ArrayTest() items[-6] = 0 self.assertRaises(IndexError, test) @@ -118,8 +118,8 @@ def test(): def testArrayContains(self): """Test array support for __contains__.""" - object = Test.Int32ArrayTest() - items = object.items + ob = Test.Int32ArrayTest() + items = ob.items self.assertTrue(0 in items) self.assertTrue(1 in items) @@ -134,8 +134,8 @@ def testArrayContains(self): def testBooleanArray(self): """Test boolean arrays.""" - object = Test.BooleanArrayTest() - items = object.items + ob = Test.BooleanArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -152,21 +152,21 @@ def testBooleanArray(self): self.assertTrue(items[0] == True) def test(): - object = Test.ByteArrayTest() - v = object.items["wrong"] + ob = Test.ByteArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.ByteArrayTest() - object[0] = "wrong" + ob = Test.ByteArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testByteArray(self): """Test byte arrays.""" - object = Test.ByteArrayTest() - items = object.items + ob = Test.ByteArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -189,33 +189,33 @@ def testByteArray(self): self.assertTrue(items[-1] == min) def test(): - object = Test.ByteArrayTest() - object.items[0] = max + 1 + ob = Test.ByteArrayTest() + ob.items[0] = max + 1 self.assertRaises(OverflowError, test) def test(): - object = Test.ByteArrayTest() - object.items[0] = min - 1 + ob = Test.ByteArrayTest() + ob.items[0] = min - 1 self.assertRaises(OverflowError, test) def test(): - object = Test.ByteArrayTest() - v = object.items["wrong"] + ob = Test.ByteArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.ByteArrayTest() - object[0] = "wrong" + ob = Test.ByteArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testSByteArray(self): """Test sbyte arrays.""" - object = Test.SByteArrayTest() - items = object.items + ob = Test.SByteArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -238,33 +238,33 @@ def testSByteArray(self): self.assertTrue(items[-1] == min) def test(): - object = Test.SByteArrayTest() - object.items[0] = max + 1 + ob = Test.SByteArrayTest() + ob.items[0] = max + 1 self.assertRaises(OverflowError, test) def test(): - object = Test.SByteArrayTest() - object.items[0] = min - 1 + ob = Test.SByteArrayTest() + ob.items[0] = min - 1 self.assertRaises(OverflowError, test) def test(): - object = Test.SByteArrayTest() - v = object.items["wrong"] + ob = Test.SByteArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.SByteArrayTest() - object[0] = "wrong" + ob = Test.SByteArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testCharArray(self): """Test char arrays.""" - object = Test.CharArrayTest() - items = object.items + ob = Test.CharArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -287,21 +287,21 @@ def testCharArray(self): self.assertTrue(items[-1] == min) def test(): - object = Test.CharArrayTest() - v = object.items["wrong"] + ob = Test.CharArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.CharArrayTest() - object[0] = "wrong" + ob = Test.CharArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testInt16Array(self): """Test Int16 arrays.""" - object = Test.Int16ArrayTest() - items = object.items + ob = Test.Int16ArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -324,33 +324,33 @@ def testInt16Array(self): self.assertTrue(items[-1] == min) def test(): - object = Test.Int16ArrayTest() - object.items[0] = max + 1 + ob = Test.Int16ArrayTest() + ob.items[0] = max + 1 self.assertRaises(OverflowError, test) def test(): - object = Test.Int16ArrayTest() - object.items[0] = min - 1 + ob = Test.Int16ArrayTest() + ob.items[0] = min - 1 self.assertRaises(OverflowError, test) def test(): - object = Test.Int16ArrayTest() - v = object.items["wrong"] + ob = Test.Int16ArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.Int16ArrayTest() - object[0] = "wrong" + ob = Test.Int16ArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testInt32Array(self): """Test Int32 arrays.""" - object = Test.Int32ArrayTest() - items = object.items + ob = Test.Int32ArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -373,33 +373,33 @@ def testInt32Array(self): self.assertTrue(items[-1] == min) def test(): - object = Test.Int32ArrayTest() - object.items[0] = max + 1 + ob = Test.Int32ArrayTest() + ob.items[0] = max + 1 self.assertRaises(OverflowError, test) def test(): - object = Test.Int32ArrayTest() - object.items[0] = min - 1 + ob = Test.Int32ArrayTest() + ob.items[0] = min - 1 self.assertRaises(OverflowError, test) def test(): - object = Test.Int32ArrayTest() - v = object.items["wrong"] + ob = Test.Int32ArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.Int32ArrayTest() - object[0] = "wrong" + ob = Test.Int32ArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testInt64Array(self): """Test Int64 arrays.""" - object = Test.Int64ArrayTest() - items = object.items + ob = Test.Int64ArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -422,33 +422,33 @@ def testInt64Array(self): self.assertTrue(items[-1] == min) def test(): - object = Test.Int64ArrayTest() - object.items[0] = max + 1 + ob = Test.Int64ArrayTest() + ob.items[0] = max + 1 self.assertRaises(OverflowError, test) def test(): - object = Test.Int64ArrayTest() - object.items[0] = min - 1 + ob = Test.Int64ArrayTest() + ob.items[0] = min - 1 self.assertRaises(OverflowError, test) def test(): - object = Test.Int64ArrayTest() - v = object.items["wrong"] + ob = Test.Int64ArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.Int64ArrayTest() - object[0] = "wrong" + ob = Test.Int64ArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testUInt16Array(self): """Test UInt16 arrays.""" - object = Test.UInt16ArrayTest() - items = object.items + ob = Test.UInt16ArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -471,33 +471,33 @@ def testUInt16Array(self): self.assertTrue(items[-1] == min) def test(): - object = Test.UInt16ArrayTest() - object.items[0] = max + 1 + ob = Test.UInt16ArrayTest() + ob.items[0] = max + 1 self.assertRaises(OverflowError, test) def test(): - object = Test.UInt16ArrayTest() - object.items[0] = min - 1 + ob = Test.UInt16ArrayTest() + ob.items[0] = min - 1 self.assertRaises(OverflowError, test) def test(): - object = Test.UInt16ArrayTest() - v = object.items["wrong"] + ob = Test.UInt16ArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.UInt16ArrayTest() - object[0] = "wrong" + ob = Test.UInt16ArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testUInt32Array(self): """Test UInt32 arrays.""" - object = Test.UInt32ArrayTest() - items = object.items + ob = Test.UInt32ArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -520,33 +520,33 @@ def testUInt32Array(self): self.assertTrue(items[-1] == min) def test(): - object = Test.UInt32ArrayTest() - object.items[0] = max + 1 + ob = Test.UInt32ArrayTest() + ob.items[0] = max + 1 self.assertRaises(OverflowError, test) def test(): - object = Test.UInt32ArrayTest() - object.items[0] = min - 1 + ob = Test.UInt32ArrayTest() + ob.items[0] = min - 1 self.assertRaises(OverflowError, test) def test(): - object = Test.UInt32ArrayTest() - v = object.items["wrong"] + ob = Test.UInt32ArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.UInt32ArrayTest() - object[0] = "wrong" + ob = Test.UInt32ArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testUInt64Array(self): """Test UInt64 arrays.""" - object = Test.UInt64ArrayTest() - items = object.items + ob = Test.UInt64ArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -569,33 +569,33 @@ def testUInt64Array(self): self.assertTrue(items[-1] == min) def test(): - object = Test.UInt64ArrayTest() - object.items[0] = max + 1 + ob = Test.UInt64ArrayTest() + ob.items[0] = max + 1 self.assertRaises(OverflowError, test) def test(): - object = Test.UInt64ArrayTest() - object.items[0] = min - 1 + ob = Test.UInt64ArrayTest() + ob.items[0] = min - 1 self.assertRaises(OverflowError, test) def test(): - object = Test.UInt64ArrayTest() - v = object.items["wrong"] + ob = Test.UInt64ArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.UInt64ArrayTest() - object[0] = "wrong" + ob = Test.UInt64ArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testSingleArray(self): """Test Single arrays.""" - object = Test.SingleArrayTest() - items = object.items + ob = Test.SingleArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -618,21 +618,21 @@ def testSingleArray(self): self.assertTrue(items[-1] == min) def test(): - object = Test.SingleArrayTest() - v = object.items["wrong"] + ob = Test.SingleArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.SingleArrayTest() - object[0] = "wrong" + ob = Test.SingleArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testDoubleArray(self): """Test Double arrays.""" - object = Test.DoubleArrayTest() - items = object.items + ob = Test.DoubleArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -655,21 +655,21 @@ def testDoubleArray(self): self.assertTrue(items[-1] == min) def test(): - object = Test.DoubleArrayTest() - v = object.items["wrong"] + ob = Test.DoubleArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.DoubleArrayTest() - object[0] = "wrong" + ob = Test.DoubleArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testDecimalArray(self): """Test Decimal arrays.""" - object = Test.DecimalArrayTest() - items = object.items + ob = Test.DecimalArrayTest() + items = ob.items from System import Decimal max_d = Decimal.Parse("79228162514264337593543950335") @@ -693,21 +693,21 @@ def testDecimalArray(self): self.assertTrue(items[-1] == min_d) def test(): - object = Test.DecimalArrayTest() - v = object.items["wrong"] + ob = Test.DecimalArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.DecimalArrayTest() - object[0] = "wrong" + ob = Test.DecimalArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testStringArray(self): """Test String arrays.""" - object = Test.StringArrayTest() - items = object.items + ob = Test.StringArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -727,22 +727,22 @@ def testStringArray(self): self.assertTrue(items[-1] == "eggs") def test(): - object = Test.StringArrayTest() - v = object.items["wrong"] + ob = Test.StringArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.Int64ArrayTest() - object[0] = 0 + ob = Test.Int64ArrayTest() + ob[0] = 0 self.assertRaises(TypeError, test) def testEnumArray(self): """Test enum arrays.""" from Python.Test import ShortEnum - object = Test.EnumArrayTest() - items = object.items + ob = Test.EnumArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -762,28 +762,28 @@ def testEnumArray(self): self.assertTrue(items[-1] == ShortEnum.Zero) def test(): - object = Test.EnumArrayTest() - object.items[0] = 99 + ob = Test.EnumArrayTest() + ob.items[0] = 99 self.assertRaises(ValueError, test) def test(): - object = Test.EnumArrayTest() - v = object.items["wrong"] + ob = Test.EnumArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.EnumArrayTest() - object[0] = "wrong" + ob = Test.EnumArrayTest() + ob[0] = "wrong" self.assertRaises(TypeError, test) def testObjectArray(self): - """Test object arrays.""" + """Test ob arrays.""" from Python.Test import Spam - object = Test.ObjectArrayTest() - items = object.items + ob = Test.ObjectArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -809,21 +809,21 @@ def testObjectArray(self): self.assertTrue(items[0] == None) def test(): - object = Test.ObjectArrayTest() - v = object.items["wrong"] + ob = Test.ObjectArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.ObjectArrayTest() - object.items["wrong"] = "wrong" + ob = Test.ObjectArrayTest() + ob.items["wrong"] = "wrong" self.assertRaises(TypeError, test) def testNullArray(self): """Test null arrays.""" - object = Test.NullArrayTest() - items = object.items + ob = Test.NullArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -842,20 +842,20 @@ def testNullArray(self): items[-1] = None self.assertTrue(items[-1] == None) - empty = object.empty + empty = ob.empty self.assertTrue(len(empty) == 0) def test(): - object = Test.NullArrayTest() - v = object.items["wrong"] + ob = Test.NullArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def testInterfaceArray(self): """Test interface arrays.""" from Python.Test import Spam - object = Test.InterfaceArrayTest() - items = object.items + ob = Test.InterfaceArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -878,28 +878,28 @@ def testInterfaceArray(self): self.assertTrue(items[0] == None) def test(): - object = Test.InterfaceArrayTest() - object.items[0] = 99 + ob = Test.InterfaceArrayTest() + ob.items[0] = 99 self.assertRaises(TypeError, test) def test(): - object = Test.InterfaceArrayTest() - v = object.items["wrong"] + ob = Test.InterfaceArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.InterfaceArrayTest() - object.items["wrong"] = "wrong" + ob = Test.InterfaceArrayTest() + ob.items["wrong"] = "wrong" self.assertRaises(TypeError, test) def testTypedArray(self): """Test typed arrays.""" from Python.Test import Spam - object = Test.TypedArrayTest() - items = object.items + ob = Test.TypedArrayTest() + items = ob.items self.assertTrue(len(items) == 5) @@ -922,27 +922,27 @@ def testTypedArray(self): self.assertTrue(items[0] == None) def test(): - object = Test.TypedArrayTest() - object.items[0] = 99 + ob = Test.TypedArrayTest() + ob.items[0] = 99 self.assertRaises(TypeError, test) def test(): - object = Test.TypedArrayTest() - v = object.items["wrong"] + ob = Test.TypedArrayTest() + v = ob.items["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.TypedArrayTest() - object.items["wrong"] = "wrong" + ob = Test.TypedArrayTest() + ob.items["wrong"] = "wrong" self.assertRaises(TypeError, test) def testMultiDimensionalArray(self): """Test multi-dimensional arrays.""" - object = Test.MultiDimensionalArrayTest() - items = object.items + ob = Test.MultiDimensionalArrayTest() + items = ob.items self.assertTrue(len(items) == 25) @@ -988,26 +988,26 @@ def testMultiDimensionalArray(self): self.assertTrue(items[-1, -1] == min) def test(): - object = Test.MultiDimensionalArrayTest() - object.items[0, 0] = max + 1 + ob = Test.MultiDimensionalArrayTest() + ob.items[0, 0] = max + 1 self.assertRaises(OverflowError, test) def test(): - object = Test.MultiDimensionalArrayTest() - object.items[0, 0] = min - 1 + ob = Test.MultiDimensionalArrayTest() + ob.items[0, 0] = min - 1 self.assertRaises(OverflowError, test) def test(): - object = Test.MultiDimensionalArrayTest() - v = object.items["wrong", 0] + ob = Test.MultiDimensionalArrayTest() + v = ob.items["wrong", 0] self.assertRaises(TypeError, test) def test(): - object = Test.MultiDimensionalArrayTest() - object[0, 0] = "wrong" + ob = Test.MultiDimensionalArrayTest() + ob[0, 0] = "wrong" self.assertRaises(TypeError, test) @@ -1093,7 +1093,7 @@ def testListNestedArrayConversion(self): self.assertTrue(result[0][0].__class__ == Spam) def testSequenceArrayConversion(self): - """Test conversion of sequence-like objects to array arguments.""" + """Test conversion of sequence-like obs to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1419,7 +1419,7 @@ def testSpecialArrayCreation(self): def testArrayAbuse(self): """Test array abuse.""" _class = Test.PublicArrayTest - object = Test.PublicArrayTest() + ob = Test.PublicArrayTest() def test(): del _class.__getitem__ @@ -1427,7 +1427,7 @@ def test(): self.assertRaises(AttributeError, test) def test(): - del object.__getitem__ + del ob.__getitem__ self.assertRaises(AttributeError, test) @@ -1437,7 +1437,7 @@ def test(): self.assertRaises(AttributeError, test) def test(): - del object.__setitem__ + del ob.__setitem__ self.assertRaises(AttributeError, test) diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index 7af3ee65e..f03ed96f9 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -13,75 +13,75 @@ class ConversionTests(unittest.TestCase): def testBoolConversion(self): """Test bool conversion.""" - object = ConversionTest() - self.assertTrue(object.BooleanField == False) - self.assertTrue(object.BooleanField is False) - self.assertTrue(object.BooleanField == 0) - - object.BooleanField = True - self.assertTrue(object.BooleanField == True) - self.assertTrue(object.BooleanField is True) - self.assertTrue(object.BooleanField == 1) - - object.BooleanField = False - self.assertTrue(object.BooleanField == False) - self.assertTrue(object.BooleanField is False) - self.assertTrue(object.BooleanField == 0) - - object.BooleanField = 1 - self.assertTrue(object.BooleanField == True) - self.assertTrue(object.BooleanField is True) - self.assertTrue(object.BooleanField == 1) - - object.BooleanField = 0 - self.assertTrue(object.BooleanField == False) - self.assertTrue(object.BooleanField is False) - self.assertTrue(object.BooleanField == 0) - - object.BooleanField = System.Boolean(None) - self.assertTrue(object.BooleanField == False) - self.assertTrue(object.BooleanField is False) - self.assertTrue(object.BooleanField == 0) - - object.BooleanField = System.Boolean('') - self.assertTrue(object.BooleanField == False) - self.assertTrue(object.BooleanField is False) - self.assertTrue(object.BooleanField == 0) - - object.BooleanField = System.Boolean(0) - self.assertTrue(object.BooleanField == False) - self.assertTrue(object.BooleanField is False) - self.assertTrue(object.BooleanField == 0) - - object.BooleanField = System.Boolean(1) - self.assertTrue(object.BooleanField == True) - self.assertTrue(object.BooleanField is True) - self.assertTrue(object.BooleanField == 1) - - object.BooleanField = System.Boolean('a') - self.assertTrue(object.BooleanField == True) - self.assertTrue(object.BooleanField is True) - self.assertTrue(object.BooleanField == 1) + ob = ConversionTest() + self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) + self.assertTrue(ob.BooleanField == 0) + + ob.BooleanField = True + self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) + self.assertTrue(ob.BooleanField == 1) + + ob.BooleanField = False + self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) + self.assertTrue(ob.BooleanField == 0) + + ob.BooleanField = 1 + self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) + self.assertTrue(ob.BooleanField == 1) + + ob.BooleanField = 0 + self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) + self.assertTrue(ob.BooleanField == 0) + + ob.BooleanField = System.Boolean(None) + self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) + self.assertTrue(ob.BooleanField == 0) + + ob.BooleanField = System.Boolean('') + self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) + self.assertTrue(ob.BooleanField == 0) + + ob.BooleanField = System.Boolean(0) + self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) + self.assertTrue(ob.BooleanField == 0) + + ob.BooleanField = System.Boolean(1) + self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) + self.assertTrue(ob.BooleanField == 1) + + ob.BooleanField = System.Boolean('a') + self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) + self.assertTrue(ob.BooleanField == 1) def testSByteConversion(self): """Test sbyte conversion.""" self.assertTrue(System.SByte.MaxValue == 127) self.assertTrue(System.SByte.MinValue == -128) - object = ConversionTest() - self.assertTrue(object.SByteField == 0) + ob = ConversionTest() + self.assertTrue(ob.SByteField == 0) - object.SByteField = 127 - self.assertTrue(object.SByteField == 127) + ob.SByteField = 127 + self.assertTrue(ob.SByteField == 127) - object.SByteField = -128 - self.assertTrue(object.SByteField == -128) + ob.SByteField = -128 + self.assertTrue(ob.SByteField == -128) - object.SByteField = System.SByte(127) - self.assertTrue(object.SByteField == 127) + ob.SByteField = System.SByte(127) + self.assertTrue(ob.SByteField == 127) - object.SByteField = System.SByte(-128) - self.assertTrue(object.SByteField == -128) + ob.SByteField = System.SByte(-128) + self.assertTrue(ob.SByteField == -128) def test(): ConversionTest().SByteField = "spam" @@ -118,20 +118,20 @@ def testByteConversion(self): self.assertTrue(System.Byte.MaxValue == 255) self.assertTrue(System.Byte.MinValue == 0) - object = ConversionTest() - self.assertTrue(object.ByteField == 0) + ob = ConversionTest() + self.assertTrue(ob.ByteField == 0) - object.ByteField = 255 - self.assertTrue(object.ByteField == 255) + ob.ByteField = 255 + self.assertTrue(ob.ByteField == 255) - object.ByteField = 0 - self.assertTrue(object.ByteField == 0) + ob.ByteField = 0 + self.assertTrue(ob.ByteField == 0) - object.ByteField = System.Byte(255) - self.assertTrue(object.ByteField == 255) + ob.ByteField = System.Byte(255) + self.assertTrue(ob.ByteField == 255) - object.ByteField = System.Byte(0) - self.assertTrue(object.ByteField == 0) + ob.ByteField = System.Byte(0) + self.assertTrue(ob.ByteField == 0) def test(): ConversionTest().ByteField = "spam" @@ -168,17 +168,17 @@ def testCharConversion(self): self.assertTrue(System.Char.MaxValue == unichr(65535)) self.assertTrue(System.Char.MinValue == unichr(0)) - object = ConversionTest() - self.assertTrue(object.CharField == u'A') + ob = ConversionTest() + self.assertTrue(ob.CharField == u'A') - object.CharField = 'B' - self.assertTrue(object.CharField == u'B') + ob.CharField = 'B' + self.assertTrue(ob.CharField == u'B') - object.CharField = u'B' - self.assertTrue(object.CharField == u'B') + ob.CharField = u'B' + self.assertTrue(ob.CharField == u'B') - object.CharField = 67 - self.assertTrue(object.CharField == u'C') + ob.CharField = 67 + self.assertTrue(ob.CharField == u'C') def test(): ConversionTest().CharField = 65536 @@ -200,20 +200,20 @@ def testInt16Conversion(self): self.assertTrue(System.Int16.MaxValue == 32767) self.assertTrue(System.Int16.MinValue == -32768) - object = ConversionTest() - self.assertTrue(object.Int16Field == 0) + ob = ConversionTest() + self.assertTrue(ob.Int16Field == 0) - object.Int16Field = 32767 - self.assertTrue(object.Int16Field == 32767) + ob.Int16Field = 32767 + self.assertTrue(ob.Int16Field == 32767) - object.Int16Field = -32768 - self.assertTrue(object.Int16Field == -32768) + ob.Int16Field = -32768 + self.assertTrue(ob.Int16Field == -32768) - object.Int16Field = System.Int16(32767) - self.assertTrue(object.Int16Field == 32767) + ob.Int16Field = System.Int16(32767) + self.assertTrue(ob.Int16Field == 32767) - object.Int16Field = System.Int16(-32768) - self.assertTrue(object.Int16Field == -32768) + ob.Int16Field = System.Int16(-32768) + self.assertTrue(ob.Int16Field == -32768) def test(): ConversionTest().Int16Field = "spam" @@ -250,20 +250,20 @@ def testInt32Conversion(self): self.assertTrue(System.Int32.MaxValue == 2147483647) self.assertTrue(System.Int32.MinValue == -2147483648) - object = ConversionTest() - self.assertTrue(object.Int32Field == 0) + ob = ConversionTest() + self.assertTrue(ob.Int32Field == 0) - object.Int32Field = 2147483647 - self.assertTrue(object.Int32Field == 2147483647) + ob.Int32Field = 2147483647 + self.assertTrue(ob.Int32Field == 2147483647) - object.Int32Field = -2147483648 - self.assertTrue(object.Int32Field == -2147483648) + ob.Int32Field = -2147483648 + self.assertTrue(ob.Int32Field == -2147483648) - object.Int32Field = System.Int32(2147483647) - self.assertTrue(object.Int32Field == 2147483647) + ob.Int32Field = System.Int32(2147483647) + self.assertTrue(ob.Int32Field == 2147483647) - object.Int32Field = System.Int32(-2147483648) - self.assertTrue(object.Int32Field == -2147483648) + ob.Int32Field = System.Int32(-2147483648) + self.assertTrue(ob.Int32Field == -2147483648) def test(): ConversionTest().Int32Field = "spam" @@ -300,20 +300,20 @@ def testInt64Conversion(self): self.assertTrue(System.Int64.MaxValue == long(9223372036854775807)) self.assertTrue(System.Int64.MinValue == long(-9223372036854775808)) - object = ConversionTest() - self.assertTrue(object.Int64Field == 0) + ob = ConversionTest() + self.assertTrue(ob.Int64Field == 0) - object.Int64Field = long(9223372036854775807) - self.assertTrue(object.Int64Field == long(9223372036854775807)) + ob.Int64Field = long(9223372036854775807) + self.assertTrue(ob.Int64Field == long(9223372036854775807)) - object.Int64Field = long(-9223372036854775808) - self.assertTrue(object.Int64Field == long(-9223372036854775808)) + ob.Int64Field = long(-9223372036854775808) + self.assertTrue(ob.Int64Field == long(-9223372036854775808)) - object.Int64Field = System.Int64(long(9223372036854775807)) - self.assertTrue(object.Int64Field == long(9223372036854775807)) + ob.Int64Field = System.Int64(long(9223372036854775807)) + self.assertTrue(ob.Int64Field == long(9223372036854775807)) - object.Int64Field = System.Int64(long(-9223372036854775808)) - self.assertTrue(object.Int64Field == long(-9223372036854775808)) + ob.Int64Field = System.Int64(long(-9223372036854775808)) + self.assertTrue(ob.Int64Field == long(-9223372036854775808)) def test(): ConversionTest().Int64Field = "spam" @@ -350,20 +350,20 @@ def testUInt16Conversion(self): self.assertTrue(System.UInt16.MaxValue == 65535) self.assertTrue(System.UInt16.MinValue == 0) - object = ConversionTest() - self.assertTrue(object.UInt16Field == 0) + ob = ConversionTest() + self.assertTrue(ob.UInt16Field == 0) - object.UInt16Field = 65535 - self.assertTrue(object.UInt16Field == 65535) + ob.UInt16Field = 65535 + self.assertTrue(ob.UInt16Field == 65535) - object.UInt16Field = -0 - self.assertTrue(object.UInt16Field == 0) + ob.UInt16Field = -0 + self.assertTrue(ob.UInt16Field == 0) - object.UInt16Field = System.UInt16(65535) - self.assertTrue(object.UInt16Field == 65535) + ob.UInt16Field = System.UInt16(65535) + self.assertTrue(ob.UInt16Field == 65535) - object.UInt16Field = System.UInt16(0) - self.assertTrue(object.UInt16Field == 0) + ob.UInt16Field = System.UInt16(0) + self.assertTrue(ob.UInt16Field == 0) def test(): ConversionTest().UInt16Field = "spam" @@ -400,20 +400,20 @@ def testUInt32Conversion(self): self.assertTrue(System.UInt32.MaxValue == long(4294967295)) self.assertTrue(System.UInt32.MinValue == 0) - object = ConversionTest() - self.assertTrue(object.UInt32Field == 0) + ob = ConversionTest() + self.assertTrue(ob.UInt32Field == 0) - object.UInt32Field = long(4294967295) - self.assertTrue(object.UInt32Field == long(4294967295)) + ob.UInt32Field = long(4294967295) + self.assertTrue(ob.UInt32Field == long(4294967295)) - object.UInt32Field = -0 - self.assertTrue(object.UInt32Field == 0) + ob.UInt32Field = -0 + self.assertTrue(ob.UInt32Field == 0) - object.UInt32Field = System.UInt32(long(4294967295)) - self.assertTrue(object.UInt32Field == long(4294967295)) + ob.UInt32Field = System.UInt32(long(4294967295)) + self.assertTrue(ob.UInt32Field == long(4294967295)) - object.UInt32Field = System.UInt32(0) - self.assertTrue(object.UInt32Field == 0) + ob.UInt32Field = System.UInt32(0) + self.assertTrue(ob.UInt32Field == 0) def test(): ConversionTest().UInt32Field = "spam" @@ -450,20 +450,20 @@ def testUInt64Conversion(self): self.assertTrue(System.UInt64.MaxValue == long(18446744073709551615)) self.assertTrue(System.UInt64.MinValue == 0) - object = ConversionTest() - self.assertTrue(object.UInt64Field == 0) + ob = ConversionTest() + self.assertTrue(ob.UInt64Field == 0) - object.UInt64Field = long(18446744073709551615) - self.assertTrue(object.UInt64Field == long(18446744073709551615)) + ob.UInt64Field = long(18446744073709551615) + self.assertTrue(ob.UInt64Field == long(18446744073709551615)) - object.UInt64Field = -0 - self.assertTrue(object.UInt64Field == 0) + ob.UInt64Field = -0 + self.assertTrue(ob.UInt64Field == 0) - object.UInt64Field = System.UInt64(long(18446744073709551615)) - self.assertTrue(object.UInt64Field == long(18446744073709551615)) + ob.UInt64Field = System.UInt64(long(18446744073709551615)) + self.assertTrue(ob.UInt64Field == long(18446744073709551615)) - object.UInt64Field = System.UInt64(0) - self.assertTrue(object.UInt64Field == 0) + ob.UInt64Field = System.UInt64(0) + self.assertTrue(ob.UInt64Field == 0) def test(): ConversionTest().UInt64Field = "spam" @@ -500,20 +500,20 @@ def testSingleConversion(self): self.assertTrue(System.Single.MaxValue == 3.402823e38) self.assertTrue(System.Single.MinValue == -3.402823e38) - object = ConversionTest() - self.assertTrue(object.SingleField == 0.0) + ob = ConversionTest() + self.assertTrue(ob.SingleField == 0.0) - object.SingleField = 3.402823e38 - self.assertTrue(object.SingleField == 3.402823e38) + ob.SingleField = 3.402823e38 + self.assertTrue(ob.SingleField == 3.402823e38) - object.SingleField = -3.402823e38 - self.assertTrue(object.SingleField == -3.402823e38) + ob.SingleField = -3.402823e38 + self.assertTrue(ob.SingleField == -3.402823e38) - object.SingleField = System.Single(3.402823e38) - self.assertTrue(object.SingleField == 3.402823e38) + ob.SingleField = System.Single(3.402823e38) + self.assertTrue(ob.SingleField == 3.402823e38) - object.SingleField = System.Single(-3.402823e38) - self.assertTrue(object.SingleField == -3.402823e38) + ob.SingleField = System.Single(-3.402823e38) + self.assertTrue(ob.SingleField == -3.402823e38) def test(): ConversionTest().SingleField = "spam" @@ -550,20 +550,20 @@ def testDoubleConversion(self): self.assertTrue(System.Double.MaxValue == 1.7976931348623157e308) self.assertTrue(System.Double.MinValue == -1.7976931348623157e308) - object = ConversionTest() - self.assertTrue(object.DoubleField == 0.0) + ob = ConversionTest() + self.assertTrue(ob.DoubleField == 0.0) - object.DoubleField = 1.7976931348623157e308 - self.assertTrue(object.DoubleField == 1.7976931348623157e308) + ob.DoubleField = 1.7976931348623157e308 + self.assertTrue(ob.DoubleField == 1.7976931348623157e308) - object.DoubleField = -1.7976931348623157e308 - self.assertTrue(object.DoubleField == -1.7976931348623157e308) + ob.DoubleField = -1.7976931348623157e308 + self.assertTrue(ob.DoubleField == -1.7976931348623157e308) - object.DoubleField = System.Double(1.7976931348623157e308) - self.assertTrue(object.DoubleField == 1.7976931348623157e308) + ob.DoubleField = System.Double(1.7976931348623157e308) + self.assertTrue(ob.DoubleField == 1.7976931348623157e308) - object.DoubleField = System.Double(-1.7976931348623157e308) - self.assertTrue(object.DoubleField == -1.7976931348623157e308) + ob.DoubleField = System.Double(-1.7976931348623157e308) + self.assertTrue(ob.DoubleField == -1.7976931348623157e308) def test(): ConversionTest().DoubleField = "spam" @@ -604,23 +604,23 @@ def testDecimalConversion(self): self.assertTrue(Decimal.ToInt64(Decimal(10)) == long(10)) - object = ConversionTest() - self.assertTrue(object.DecimalField == Decimal(0)) + ob = ConversionTest() + self.assertTrue(ob.DecimalField == Decimal(0)) - object.DecimalField = Decimal(10) - self.assertTrue(object.DecimalField == Decimal(10)) + ob.DecimalField = Decimal(10) + self.assertTrue(ob.DecimalField == Decimal(10)) - object.DecimalField = Decimal.One - self.assertTrue(object.DecimalField == Decimal.One) + ob.DecimalField = Decimal.One + self.assertTrue(ob.DecimalField == Decimal.One) - object.DecimalField = Decimal.Zero - self.assertTrue(object.DecimalField == Decimal.Zero) + ob.DecimalField = Decimal.Zero + self.assertTrue(ob.DecimalField == Decimal.Zero) - object.DecimalField = max_d - self.assertTrue(object.DecimalField == max_d) + ob.DecimalField = max_d + self.assertTrue(ob.DecimalField == max_d) - object.DecimalField = min_d - self.assertTrue(object.DecimalField == min_d) + ob.DecimalField = min_d + self.assertTrue(ob.DecimalField == min_d) def test(): ConversionTest().DecimalField = None @@ -639,31 +639,31 @@ def test(): def testStringConversion(self): """Test string / unicode conversion.""" - object = ConversionTest() + ob = ConversionTest() - self.assertTrue(object.StringField == "spam") - self.assertTrue(object.StringField == u"spam") + self.assertTrue(ob.StringField == "spam") + self.assertTrue(ob.StringField == u"spam") - object.StringField = "eggs" - self.assertTrue(object.StringField == "eggs") - self.assertTrue(object.StringField == u"eggs") + ob.StringField = "eggs" + self.assertTrue(ob.StringField == "eggs") + self.assertTrue(ob.StringField == u"eggs") - object.StringField = u"spam" - self.assertTrue(object.StringField == "spam") - self.assertTrue(object.StringField == u"spam") + ob.StringField = u"spam" + self.assertTrue(ob.StringField == "spam") + self.assertTrue(ob.StringField == u"spam") - object.StringField = u'\uffff\uffff' - self.assertTrue(object.StringField == u'\uffff\uffff') + ob.StringField = u'\uffff\uffff' + self.assertTrue(ob.StringField == u'\uffff\uffff') - object.StringField = System.String("spam") - self.assertTrue(object.StringField == "spam") - self.assertTrue(object.StringField == u"spam") + ob.StringField = System.String("spam") + self.assertTrue(ob.StringField == "spam") + self.assertTrue(ob.StringField == u"spam") - object.StringField = System.String(u'\uffff\uffff') - self.assertTrue(object.StringField == u'\uffff\uffff') + ob.StringField = System.String(u'\uffff\uffff') + self.assertTrue(ob.StringField == u'\uffff\uffff') - object.StringField = None - self.assertTrue(object.StringField == None) + ob.StringField = None + self.assertTrue(ob.StringField == None) def test(): ConversionTest().StringField = 1 @@ -674,57 +674,57 @@ def testInterfaceConversion(self): """Test interface conversion.""" from Python.Test import Spam, ISpam - object = ConversionTest() + ob = ConversionTest() - self.assertTrue(ISpam(object.SpamField).GetValue() == "spam") - self.assertTrue(object.SpamField.GetValue() == "spam") + self.assertTrue(ISpam(ob.SpamField).GetValue() == "spam") + self.assertTrue(ob.SpamField.GetValue() == "spam") - object.SpamField = Spam("eggs") - self.assertTrue(ISpam(object.SpamField).GetValue() == "eggs") - self.assertTrue(object.SpamField.GetValue() == "eggs") + ob.SpamField = Spam("eggs") + self.assertTrue(ISpam(ob.SpamField).GetValue() == "eggs") + self.assertTrue(ob.SpamField.GetValue() == "eggs") # need to test spam subclass here. - object.SpamField = None - self.assertTrue(object.SpamField == None) + ob.SpamField = None + self.assertTrue(ob.SpamField == None) def test(): - object = ConversionTest() - object.SpamField = System.String("bad") + ob = ConversionTest() + ob.SpamField = System.String("bad") self.assertRaises(TypeError, test) def test(): - object = ConversionTest() - object.SpamField = System.Int32(1) + ob = ConversionTest() + ob.SpamField = System.Int32(1) self.assertRaises(TypeError, test) def testObjectConversion(self): - """Test object conversion.""" + """Test ob conversion.""" from Python.Test import Spam - object = ConversionTest() - self.assertTrue(object.ObjectField == None) + ob = ConversionTest() + self.assertTrue(ob.ObjectField == None) - object.ObjectField = Spam("eggs") - self.assertTrue(object.ObjectField.__class__.__name__ == "Spam") - self.assertTrue(object.ObjectField.GetValue() == "eggs") + ob.ObjectField = Spam("eggs") + self.assertTrue(ob.ObjectField.__class__.__name__ == "Spam") + self.assertTrue(ob.ObjectField.GetValue() == "eggs") - object.ObjectField = None - self.assertTrue(object.ObjectField == None) + ob.ObjectField = None + self.assertTrue(ob.ObjectField == None) - object.ObjectField = System.String("spam") - self.assertTrue(object.ObjectField == "spam") + ob.ObjectField = System.String("spam") + self.assertTrue(ob.ObjectField == "spam") - object.ObjectField = System.Int32(1) - self.assertTrue(object.ObjectField == 1) + ob.ObjectField = System.Int32(1) + self.assertTrue(ob.ObjectField == 1) # need to test subclass here def test(): - object = ConversionTest() - object.ObjectField = self + ob = ConversionTest() + ob.ObjectField = self self.assertRaises(TypeError, test) @@ -732,56 +732,56 @@ def testEnumConversion(self): """Test enum conversion.""" from Python.Test import ShortEnum - object = ConversionTest() - self.assertTrue(object.EnumField == ShortEnum.Zero) + ob = ConversionTest() + self.assertTrue(ob.EnumField == ShortEnum.Zero) - object.EnumField = ShortEnum.One - self.assertTrue(object.EnumField == ShortEnum.One) + ob.EnumField = ShortEnum.One + self.assertTrue(ob.EnumField == ShortEnum.One) - object.EnumField = 0 - self.assertTrue(object.EnumField == ShortEnum.Zero) - self.assertTrue(object.EnumField == 0) + ob.EnumField = 0 + self.assertTrue(ob.EnumField == ShortEnum.Zero) + self.assertTrue(ob.EnumField == 0) - object.EnumField = 1 - self.assertTrue(object.EnumField == ShortEnum.One) - self.assertTrue(object.EnumField == 1) + ob.EnumField = 1 + self.assertTrue(ob.EnumField == ShortEnum.One) + self.assertTrue(ob.EnumField == 1) def test(): - object = ConversionTest() - object.EnumField = 10 + ob = ConversionTest() + ob.EnumField = 10 self.assertRaises(ValueError, test) def test(): - object = ConversionTest() - object.EnumField = 255 + ob = ConversionTest() + ob.EnumField = 255 self.assertRaises(ValueError, test) def test(): - object = ConversionTest() - object.EnumField = 1000000 + ob = ConversionTest() + ob.EnumField = 1000000 self.assertRaises(OverflowError, test) def test(): - object = ConversionTest() - object.EnumField = "spam" + ob = ConversionTest() + ob.EnumField = "spam" self.assertRaises(TypeError, test) def testNullConversion(self): """Test null conversion.""" - object = ConversionTest() + ob = ConversionTest() - object.StringField = None - self.assertTrue(object.StringField == None) + ob.StringField = None + self.assertTrue(ob.StringField == None) - object.ObjectField = None - self.assertTrue(object.ObjectField == None) + ob.ObjectField = None + self.assertTrue(ob.ObjectField == None) - object.SpamField = None - self.assertTrue(object.SpamField == None) + ob.SpamField = None + self.assertTrue(ob.SpamField == None) # Primitive types and enums should not be set to null. @@ -797,37 +797,37 @@ def test(): def testByteArrayConversion(self): """Test byte array conversion.""" - object = ConversionTest() + ob = ConversionTest() - self.assertTrue(object.ByteArrayField == None) + self.assertTrue(ob.ByteArrayField == None) - object.ByteArrayField = [0, 1, 2, 3, 4] - array = object.ByteArrayField + ob.ByteArrayField = [0, 1, 2, 3, 4] + array = ob.ByteArrayField self.assertTrue(len(array) == 5) self.assertTrue(array[0] == 0) self.assertTrue(array[4] == 4) value = b"testing" - object.ByteArrayField = value - array = object.ByteArrayField + ob.ByteArrayField = value + array = ob.ByteArrayField for i in range(len(value)): self.assertTrue(array[i] == indexbytes(value, i)) def testSByteArrayConversion(self): """Test sbyte array conversion.""" - object = ConversionTest() + ob = ConversionTest() - self.assertTrue(object.SByteArrayField == None) + self.assertTrue(ob.SByteArrayField == None) - object.SByteArrayField = [0, 1, 2, 3, 4] - array = object.SByteArrayField + ob.SByteArrayField = [0, 1, 2, 3, 4] + array = ob.SByteArrayField self.assertTrue(len(array) == 5) self.assertTrue(array[0] == 0) self.assertTrue(array[4] == 4) value = b"testing" - object.SByteArrayField = value - array = object.SByteArrayField + ob.SByteArrayField = value + array = ob.SByteArrayField for i in range(len(value)): self.assertTrue(array[i] == indexbytes(value, i)) diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index 589fc1796..493395d27 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -125,11 +125,11 @@ def test(): def testEnumConversion(self): """Test enumeration conversion.""" - object = Test.FieldTest() - self.assertTrue(object.EnumField == 0) + ob = Test.FieldTest() + self.assertTrue(ob.EnumField == 0) - object.EnumField = Test.ShortEnum.One - self.assertTrue(object.EnumField == 1) + ob.EnumField = Test.ShortEnum.One + self.assertTrue(ob.EnumField == 1) def test(): Test.FieldTest().EnumField = 20 diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 5417b4a8f..008b6b20a 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -12,17 +12,17 @@ class EventTests(unittest.TestCase): def testPublicInstanceEvent(self): """Test public instance events.""" - object = EventTest() + ob = EventTest() handler = GenericHandler() self.assertTrue(handler.value == None) - object.PublicEvent += handler.handler + ob.PublicEvent += handler.handler - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - object.PublicEvent -= handler.handler + ob.PublicEvent -= handler.handler def testPublicStaticEvent(self): """Test public static events.""" @@ -36,21 +36,21 @@ def testPublicStaticEvent(self): def testProtectedInstanceEvent(self): """Test protected instance events.""" - object = EventTest() + ob = EventTest() handler = GenericHandler() self.assertTrue(handler.value == None) - object.ProtectedEvent += handler.handler + ob.ProtectedEvent += handler.handler - object.OnProtectedEvent(TestEventArgs(10)) + ob.OnProtectedEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - object.ProtectedEvent -= handler.handler + ob.ProtectedEvent -= handler.handler def testProtectedStaticEvent(self): """Test protected static events.""" - object = EventTest + ob = EventTest handler = GenericHandler() self.assertTrue(handler.value == None) @@ -100,213 +100,213 @@ def test(): def testMulticastEvent(self): """Test multicast events.""" - object = EventTest() + ob = EventTest() handler1 = GenericHandler() handler2 = GenericHandler() handler3 = GenericHandler() - object.PublicEvent += handler1.handler - object.PublicEvent += handler2.handler - object.PublicEvent += handler3.handler + ob.PublicEvent += handler1.handler + ob.PublicEvent += handler2.handler + ob.PublicEvent += handler3.handler - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler1.value == 10) self.assertTrue(handler2.value == 10) self.assertTrue(handler3.value == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler1.value == 20) self.assertTrue(handler2.value == 20) self.assertTrue(handler3.value == 20) - object.PublicEvent -= handler1.handler - object.PublicEvent -= handler2.handler - object.PublicEvent -= handler3.handler + ob.PublicEvent -= handler1.handler + ob.PublicEvent -= handler2.handler + ob.PublicEvent -= handler3.handler def testInstanceMethodHandler(self): """Test instance method handlers.""" - object = EventTest() + ob = EventTest() handler = GenericHandler() - object.PublicEvent += handler.handler + ob.PublicEvent += handler.handler self.assertTrue(handler.value == None) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - object.PublicEvent -= handler.handler + ob.PublicEvent -= handler.handler self.assertTrue(handler.value == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) def testVarArgsInstanceMethodHandler(self): """Test vararg instance method handlers.""" - object = EventTest() + ob = EventTest() handler = VariableArgsHandler() - object.PublicEvent += handler.handler + ob.PublicEvent += handler.handler self.assertTrue(handler.value == None) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - object.PublicEvent -= handler.handler + ob.PublicEvent -= handler.handler self.assertTrue(handler.value == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) - def testCallableObjectHandler(self): - """Test callable object handlers.""" - object = EventTest() + def testCallableobHandler(self): + """Test callable ob handlers.""" + ob = EventTest() handler = CallableHandler() - object.PublicEvent += handler + ob.PublicEvent += handler self.assertTrue(handler.value == None) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - object.PublicEvent -= handler + ob.PublicEvent -= handler self.assertTrue(handler.value == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) def testVarArgsCallableHandler(self): """Test varargs callable handlers.""" - object = EventTest() + ob = EventTest() handler = VarCallableHandler() - object.PublicEvent += handler + ob.PublicEvent += handler self.assertTrue(handler.value == None) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - object.PublicEvent -= handler + ob.PublicEvent -= handler self.assertTrue(handler.value == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) def testStaticMethodHandler(self): """Test static method handlers.""" - object = EventTest() + ob = EventTest() handler = StaticMethodHandler() StaticMethodHandler.value = None - object.PublicEvent += handler.handler + ob.PublicEvent += handler.handler self.assertTrue(handler.value == None) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - object.PublicEvent -= handler.handler + ob.PublicEvent -= handler.handler self.assertTrue(handler.value == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) def testClassMethodHandler(self): """Test class method handlers.""" - object = EventTest() + ob = EventTest() handler = ClassMethodHandler() ClassMethodHandler.value = None - object.PublicEvent += handler.handler + ob.PublicEvent += handler.handler self.assertTrue(handler.value == None) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - object.PublicEvent -= handler.handler + ob.PublicEvent -= handler.handler self.assertTrue(handler.value == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) def testManagedInstanceMethodHandler(self): """Test managed instance method handlers.""" - object = EventTest() + ob = EventTest() - object.PublicEvent += object.GenericHandler - self.assertTrue(object.value == 0) + ob.PublicEvent += ob.GenericHandler + self.assertTrue(ob.value == 0) - object.OnPublicEvent(TestEventArgs(10)) - self.assertTrue(object.value == 10) + ob.OnPublicEvent(TestEventArgs(10)) + self.assertTrue(ob.value == 10) - object.PublicEvent -= object.GenericHandler - self.assertTrue(object.value == 10) + ob.PublicEvent -= ob.GenericHandler + self.assertTrue(ob.value == 10) - object.OnPublicEvent(TestEventArgs(20)) - self.assertTrue(object.value == 10) + ob.OnPublicEvent(TestEventArgs(20)) + self.assertTrue(ob.value == 10) def testManagedStaticMethodHandler(self): """Test managed static method handlers.""" - object = EventTest() + ob = EventTest() EventTest.s_value = 0 - object.PublicEvent += object.StaticHandler + ob.PublicEvent += ob.StaticHandler self.assertTrue(EventTest.s_value == 0) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(EventTest.s_value == 10) - object.PublicEvent -= object.StaticHandler + ob.PublicEvent -= ob.StaticHandler self.assertTrue(EventTest.s_value == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(EventTest.s_value == 10) def testUnboundMethodHandler(self): """Test failure mode for unbound method handlers.""" - object = EventTest() - object.PublicEvent += GenericHandler.handler + ob = EventTest() + ob.PublicEvent += GenericHandler.handler try: - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) except TypeError: - object.PublicEvent -= GenericHandler.handler + ob.PublicEvent -= GenericHandler.handler return raise TypeError("should have raised a TypeError") def testFunctionHandler(self): """Test function handlers.""" - object = EventTest() + ob = EventTest() dict = {'value': None} def handler(sender, args, dict=dict): dict['value'] = args.value - object.PublicEvent += handler + ob.PublicEvent += handler self.assertTrue(dict['value'] == None) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(dict['value'] == 10) - object.PublicEvent -= handler + ob.PublicEvent -= handler self.assertTrue(dict['value'] == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(dict['value'] == 10) def testAddNonCallableHandler(self): """Test handling of attempts to add non-callable handlers.""" def test(): - object = EventTest() - object.PublicEvent += 10 + ob = EventTest() + ob.PublicEvent += 10 self.assertRaises(TypeError, test) def test(): - object = EventTest() - object.PublicEvent += "spam" + ob = EventTest() + ob.PublicEvent += "spam" self.assertRaises(TypeError, test) @@ -314,124 +314,124 @@ def test(): class spam: pass - object = EventTest() - object.PublicEvent += spam() + ob = EventTest() + ob.PublicEvent += spam() self.assertRaises(TypeError, test) def testRemoveMultipleHandlers(self): """Test removing multiple instances of the same handler.""" - object = EventTest() + ob = EventTest() handler = MultipleHandler() h1 = handler.handler - object.PublicEvent += h1 + ob.PublicEvent += h1 h2 = handler.handler - object.PublicEvent += h2 + ob.PublicEvent += h2 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 20) - object.PublicEvent -= h1 + ob.PublicEvent -= h1 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) - object.PublicEvent -= h2 + ob.PublicEvent -= h2 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) # try again, removing in a different order. - object = EventTest() + ob = EventTest() handler = MultipleHandler() h1 = handler.handler - object.PublicEvent += h1 + ob.PublicEvent += h1 h2 = handler.handler - object.PublicEvent += h2 + ob.PublicEvent += h2 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 20) - object.PublicEvent -= h2 + ob.PublicEvent -= h2 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) - object.PublicEvent -= h1 + ob.PublicEvent -= h1 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) def testRemoveMultipleStaticHandlers(self): """Test removing multiple instances of a static handler.""" - object = EventTest() + ob = EventTest() handler = MultipleHandler() h1 = handler.handler - object.PublicStaticEvent += h1 + ob.PublicStaticEvent += h1 h2 = handler.handler - object.PublicStaticEvent += h2 + ob.PublicStaticEvent += h2 - object.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(TestEventArgs(10)) self.assertTrue(handler.value == 20) - object.PublicStaticEvent -= h1 + ob.PublicStaticEvent -= h1 - object.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) - object.PublicStaticEvent -= h2 + ob.PublicStaticEvent -= h2 - object.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) # try again, removing in a different order. - object = EventTest() + ob = EventTest() handler = MultipleHandler() h1 = handler.handler - object.PublicStaticEvent += h1 + ob.PublicStaticEvent += h1 h2 = handler.handler - object.PublicStaticEvent += h2 + ob.PublicStaticEvent += h2 - object.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(TestEventArgs(10)) self.assertTrue(handler.value == 20) - object.PublicStaticEvent -= h2 + ob.PublicStaticEvent -= h2 - object.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) - object.PublicStaticEvent -= h1 + ob.PublicStaticEvent -= h1 - object.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) def testRandomMultipleHandlers(self): """Test random subscribe / unsubscribe of the same handlers.""" import random - object = EventTest() + ob = EventTest() handler = MultipleHandler() handler2 = MultipleHandler() - object.PublicEvent += handler2.handler - object.PublicEvent += handler2.handler + ob.PublicEvent += handler2.handler + ob.PublicEvent += handler2.handler handlers = [] for i in range(30): method = handler.handler - object.PublicEvent += method + ob.PublicEvent += method handlers.append(method) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 300) self.assertTrue(handler2.value == 20) handler.value = 0 @@ -440,46 +440,46 @@ def testRandomMultipleHandlers(self): for i in range(30): item = random.choice(handlers) handlers.remove(item) - object.PublicEvent -= item + ob.PublicEvent -= item handler.value = 0 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == (len(handlers) * 10)) self.assertTrue(handler2.value == ((i + 1) * 20)) handler2.value = 0 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler2.value == 20) - object.PublicEvent -= handler2.handler + ob.PublicEvent -= handler2.handler handler2.value = 0 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler2.value == 10) - object.PublicEvent -= handler2.handler + ob.PublicEvent -= handler2.handler handler2.value = 0 - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler2.value == 0) def testRemoveInternalCallHandler(self): """Test remove on an event sink implemented w/internalcall.""" - object = EventTest() + ob = EventTest() def h(sender, args): pass - object.PublicEvent += h - object.PublicEvent -= h + ob.PublicEvent += h + ob.PublicEvent -= h def testRemoveUnknownHandler(self): """Test removing an event handler that was never added.""" def test(): - object = EventTest() + ob = EventTest() handler = GenericHandler() - object.PublicEvent -= handler.handler + ob.PublicEvent -= handler.handler self.assertRaises(ValueError, test) @@ -490,78 +490,78 @@ class BadHandler: def handler(self, one): return 'too many' - object = EventTest() + ob = EventTest() handler = BadHandler() def test(): - object.PublicEvent += handler.handler - object.OnPublicEvent(TestEventArgs(10)) + ob.PublicEvent += handler.handler + ob.OnPublicEvent(TestEventArgs(10)) self.assertRaises(TypeError, test) - object.PublicEvent -= handler.handler + ob.PublicEvent -= handler.handler class BadHandler: def handler(self, one, two, three, four, five): return 'not enough' - object = EventTest() + ob = EventTest() handler = BadHandler() def test(): - object.PublicEvent += handler.handler - object.OnPublicEvent(TestEventArgs(10)) + ob.PublicEvent += handler.handler + ob.OnPublicEvent(TestEventArgs(10)) self.assertRaises(TypeError, test) - object.PublicEvent -= handler.handler + ob.PublicEvent -= handler.handler def testIncorrectInvokation(self): """Test incorrect invocation of events.""" - object = EventTest() + ob = EventTest() handler = GenericHandler() - object.PublicEvent += handler.handler + ob.PublicEvent += handler.handler def test(): - object.OnPublicEvent() + ob.OnPublicEvent() self.assertRaises(TypeError, test) def test(): - object.OnPublicEvent(32) + ob.OnPublicEvent(32) self.assertRaises(TypeError, test) - object.PublicEvent -= handler.handler + ob.PublicEvent -= handler.handler def testExplicitCLSEventRegistration(self): """Test explicit CLS event registration.""" from Python.Test import TestEventHandler - object = EventTest() + ob = EventTest() handler = GenericHandler() delegate = TestEventHandler(handler.handler) - object.add_PublicEvent(delegate) + ob.add_PublicEvent(delegate) self.assertTrue(handler.value == None) - object.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - object.remove_PublicEvent(delegate) + ob.remove_PublicEvent(delegate) self.assertTrue(handler.value == 10) - object.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) def testImplicitCLSEventRegistration(self): """Test implicit CLS event registration.""" def test(): - object = EventTest() + ob = EventTest() handler = GenericHandler() - object.add_PublicEvent(handler.handler) + ob.add_PublicEvent(handler.handler) self.assertRaises(TypeError, test) @@ -591,8 +591,8 @@ def test(): self.assertRaises(TypeError, test) def test(): - object = EventTest() - object.PublicEvent = 0 + ob = EventTest() + ob.PublicEvent = 0 self.assertRaises(TypeError, test) diff --git a/src/tests/test_field.py b/src/tests/test_field.py index 8a2c0c67a..1a46e1d96 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -11,11 +11,11 @@ class FieldTests(unittest.TestCase): def testPublicInstanceField(self): """Test public instance fields.""" - object = FieldTest() - self.assertTrue(object.PublicField == 0) + ob = FieldTest() + self.assertTrue(ob.PublicField == 0) - object.PublicField = 1 - self.assertTrue(object.PublicField == 1) + ob.PublicField = 1 + self.assertTrue(ob.PublicField == 1) def test(): del FieldTest().PublicField @@ -24,15 +24,15 @@ def test(): def testPublicStaticField(self): """Test public static fields.""" - object = FieldTest() + ob = FieldTest() self.assertTrue(FieldTest.PublicStaticField == 0) FieldTest.PublicStaticField = 1 self.assertTrue(FieldTest.PublicStaticField == 1) - self.assertTrue(object.PublicStaticField == 1) - object.PublicStaticField = 0 - self.assertTrue(object.PublicStaticField == 0) + self.assertTrue(ob.PublicStaticField == 1) + ob.PublicStaticField = 0 + self.assertTrue(ob.PublicStaticField == 0) def test(): del FieldTest.PublicStaticField @@ -46,11 +46,11 @@ def test(): def testProtectedInstanceField(self): """Test protected instance fields.""" - object = FieldTest() - self.assertTrue(object.ProtectedField == 0) + ob = FieldTest() + self.assertTrue(ob.ProtectedField == 0) - object.ProtectedField = 1 - self.assertTrue(object.ProtectedField == 1) + ob.ProtectedField = 1 + self.assertTrue(ob.ProtectedField == 1) def test(): del FieldTest().ProtectedField @@ -59,15 +59,15 @@ def test(): def testProtectedStaticField(self): """Test protected static fields.""" - object = FieldTest() + ob = FieldTest() self.assertTrue(FieldTest.ProtectedStaticField == 0) FieldTest.ProtectedStaticField = 1 self.assertTrue(FieldTest.ProtectedStaticField == 1) - self.assertTrue(object.ProtectedStaticField == 1) - object.ProtectedStaticField = 0 - self.assertTrue(object.ProtectedStaticField == 0) + self.assertTrue(ob.ProtectedStaticField == 1) + ob.ProtectedStaticField = 0 + self.assertTrue(ob.ProtectedStaticField == 0) def test(): del FieldTest.ProtectedStaticField @@ -95,10 +95,10 @@ def test(): def testReadOnlyStaticField(self): """Test readonly static fields.""" - object = FieldTest() + ob = FieldTest() self.assertTrue(FieldTest.ReadOnlyStaticField == 0) - self.assertTrue(object.ReadOnlyStaticField == 0) + self.assertTrue(ob.ReadOnlyStaticField == 0) def test(): FieldTest.ReadOnlyStaticField = 1 @@ -122,10 +122,10 @@ def test(): def testConstantField(self): """Test const fields.""" - object = FieldTest() + ob = FieldTest() self.assertTrue(FieldTest.ConstField == 0) - self.assertTrue(object.ConstField == 0) + self.assertTrue(ob.ConstField == 0) def test(): FieldTest().ConstField = 1 @@ -190,15 +190,15 @@ def testFieldDescriptorGetSet(self): # a descriptor actually goes through the descriptor (rather than # silently replacing the descriptor in the instance or type dict. - object = FieldTest() + ob = FieldTest() self.assertTrue(FieldTest.PublicStaticField == 0) - self.assertTrue(object.PublicStaticField == 0) + self.assertTrue(ob.PublicStaticField == 0) descriptor = FieldTest.__dict__['PublicStaticField'] self.assertTrue(type(descriptor) != int) - object.PublicStaticField = 0 + ob.PublicStaticField = 0 descriptor = FieldTest.__dict__['PublicStaticField'] self.assertTrue(type(descriptor) != int) @@ -231,180 +231,180 @@ def test(): def testBooleanField(self): """Test boolean fields.""" # change this to true / false later for Python 2.3? - object = FieldTest() - self.assertTrue(object.BooleanField == False) + ob = FieldTest() + self.assertTrue(ob.BooleanField == False) - object.BooleanField = True - self.assertTrue(object.BooleanField == True) + ob.BooleanField = True + self.assertTrue(ob.BooleanField == True) - object.BooleanField = False - self.assertTrue(object.BooleanField == False) + ob.BooleanField = False + self.assertTrue(ob.BooleanField == False) - object.BooleanField = 1 - self.assertTrue(object.BooleanField == True) + ob.BooleanField = 1 + self.assertTrue(ob.BooleanField == True) - object.BooleanField = 0 - self.assertTrue(object.BooleanField == False) + ob.BooleanField = 0 + self.assertTrue(ob.BooleanField == False) def testSByteField(self): """Test sbyte fields.""" - object = FieldTest() - self.assertTrue(object.SByteField == 0) + ob = FieldTest() + self.assertTrue(ob.SByteField == 0) - object.SByteField = 1 - self.assertTrue(object.SByteField == 1) + ob.SByteField = 1 + self.assertTrue(ob.SByteField == 1) def testByteField(self): """Test byte fields.""" - object = FieldTest() - self.assertTrue(object.ByteField == 0) + ob = FieldTest() + self.assertTrue(ob.ByteField == 0) - object.ByteField = 1 - self.assertTrue(object.ByteField == 1) + ob.ByteField = 1 + self.assertTrue(ob.ByteField == 1) def testCharField(self): """Test char fields.""" - object = FieldTest() - self.assertTrue(object.CharField == u'A') - self.assertTrue(object.CharField == 'A') + ob = FieldTest() + self.assertTrue(ob.CharField == u'A') + self.assertTrue(ob.CharField == 'A') - object.CharField = 'B' - self.assertTrue(object.CharField == u'B') - self.assertTrue(object.CharField == 'B') + ob.CharField = 'B' + self.assertTrue(ob.CharField == u'B') + self.assertTrue(ob.CharField == 'B') - object.CharField = u'C' - self.assertTrue(object.CharField == u'C') - self.assertTrue(object.CharField == 'C') + ob.CharField = u'C' + self.assertTrue(ob.CharField == u'C') + self.assertTrue(ob.CharField == 'C') def testInt16Field(self): """Test int16 fields.""" - object = FieldTest() - self.assertTrue(object.Int16Field == 0) + ob = FieldTest() + self.assertTrue(ob.Int16Field == 0) - object.Int16Field = 1 - self.assertTrue(object.Int16Field == 1) + ob.Int16Field = 1 + self.assertTrue(ob.Int16Field == 1) def testInt32Field(self): """Test int32 fields.""" - object = FieldTest() - self.assertTrue(object.Int32Field == 0) + ob = FieldTest() + self.assertTrue(ob.Int32Field == 0) - object.Int32Field = 1 - self.assertTrue(object.Int32Field == 1) + ob.Int32Field = 1 + self.assertTrue(ob.Int32Field == 1) def testInt64Field(self): """Test int64 fields.""" - object = FieldTest() - self.assertTrue(object.Int64Field == 0) + ob = FieldTest() + self.assertTrue(ob.Int64Field == 0) - object.Int64Field = 1 - self.assertTrue(object.Int64Field == 1) + ob.Int64Field = 1 + self.assertTrue(ob.Int64Field == 1) def testUInt16Field(self): """Test uint16 fields.""" - object = FieldTest() - self.assertTrue(object.UInt16Field == 0) + ob = FieldTest() + self.assertTrue(ob.UInt16Field == 0) - object.UInt16Field = 1 - self.assertTrue(object.UInt16Field == 1) + ob.UInt16Field = 1 + self.assertTrue(ob.UInt16Field == 1) def testUInt32Field(self): """Test uint32 fields.""" - object = FieldTest() - self.assertTrue(object.UInt32Field == 0) + ob = FieldTest() + self.assertTrue(ob.UInt32Field == 0) - object.UInt32Field = 1 - self.assertTrue(object.UInt32Field == 1) + ob.UInt32Field = 1 + self.assertTrue(ob.UInt32Field == 1) def testUInt64Field(self): """Test uint64 fields.""" - object = FieldTest() - self.assertTrue(object.UInt64Field == 0) + ob = FieldTest() + self.assertTrue(ob.UInt64Field == 0) - object.UInt64Field = 1 - self.assertTrue(object.UInt64Field == 1) + ob.UInt64Field = 1 + self.assertTrue(ob.UInt64Field == 1) def testSingleField(self): """Test single fields.""" - object = FieldTest() - self.assertTrue(object.SingleField == 0.0) + ob = FieldTest() + self.assertTrue(ob.SingleField == 0.0) - object.SingleField = 1.1 - self.assertTrue(object.SingleField == 1.1) + ob.SingleField = 1.1 + self.assertTrue(ob.SingleField == 1.1) def testDoubleField(self): """Test double fields.""" - object = FieldTest() - self.assertTrue(object.DoubleField == 0.0) + ob = FieldTest() + self.assertTrue(ob.DoubleField == 0.0) - object.DoubleField = 1.1 - self.assertTrue(object.DoubleField == 1.1) + ob.DoubleField = 1.1 + self.assertTrue(ob.DoubleField == 1.1) def testDecimalField(self): """Test decimal fields.""" - object = FieldTest() - self.assertTrue(object.DecimalField == System.Decimal(0)) + ob = FieldTest() + self.assertTrue(ob.DecimalField == System.Decimal(0)) - object.DecimalField = System.Decimal(1) - self.assertTrue(object.DecimalField == System.Decimal(1)) + ob.DecimalField = System.Decimal(1) + self.assertTrue(ob.DecimalField == System.Decimal(1)) def testStringField(self): """Test string fields.""" - object = FieldTest() - self.assertTrue(object.StringField == "spam") + ob = FieldTest() + self.assertTrue(ob.StringField == "spam") - object.StringField = "eggs" - self.assertTrue(object.StringField == "eggs") + ob.StringField = "eggs" + self.assertTrue(ob.StringField == "eggs") def testInterfaceField(self): """Test interface fields.""" from Python.Test import Spam, ISpam - object = FieldTest() + ob = FieldTest() - self.assertTrue(ISpam(object.SpamField).GetValue() == "spam") - self.assertTrue(object.SpamField.GetValue() == "spam") + self.assertTrue(ISpam(ob.SpamField).GetValue() == "spam") + self.assertTrue(ob.SpamField.GetValue() == "spam") - object.SpamField = Spam("eggs") - self.assertTrue(ISpam(object.SpamField).GetValue() == "eggs") - self.assertTrue(object.SpamField.GetValue() == "eggs") + ob.SpamField = Spam("eggs") + self.assertTrue(ISpam(ob.SpamField).GetValue() == "eggs") + self.assertTrue(ob.SpamField.GetValue() == "eggs") def testObjectField(self): - """Test object fields.""" - object = FieldTest() - self.assertTrue(object.ObjectField == None) + """Test ob fields.""" + ob = FieldTest() + self.assertTrue(ob.ObjectField == None) - object.ObjectField = System.String("spam") - self.assertTrue(object.ObjectField == "spam") + ob.ObjectField = System.String("spam") + self.assertTrue(ob.ObjectField == "spam") - object.ObjectField = System.Int32(1) - self.assertTrue(object.ObjectField == 1) + ob.ObjectField = System.Int32(1) + self.assertTrue(ob.ObjectField == 1) - object.ObjectField = None - self.assertTrue(object.ObjectField == None) + ob.ObjectField = None + self.assertTrue(ob.ObjectField == None) def testEnumField(self): """Test enum fields.""" from Python.Test import ShortEnum - object = FieldTest() - self.assertTrue(object.EnumField == ShortEnum.Zero) + ob = FieldTest() + self.assertTrue(ob.EnumField == ShortEnum.Zero) - object.EnumField = ShortEnum.One - self.assertTrue(object.EnumField == ShortEnum.One) + ob.EnumField = ShortEnum.One + self.assertTrue(ob.EnumField == ShortEnum.One) def testNullableField(self): """Test nullable fields.""" - object = FieldTest() + ob = FieldTest() - object.StringField = None - self.assertTrue(object.StringField == None) + ob.StringField = None + self.assertTrue(ob.StringField == None) - object.ObjectField = None - self.assertTrue(object.ObjectField == None) + ob.ObjectField = None + self.assertTrue(ob.ObjectField == None) - object.SpamField = None - self.assertTrue(object.SpamField == None) + ob.SpamField = None + self.assertTrue(ob.SpamField == None) # Primitive types and enums should not be set to null. diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index 74c9b1876..4e631de4f 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -12,616 +12,616 @@ class IndexerTests(unittest.TestCase): def testPublicIndexer(self): """Test public indexers.""" - object = Test.PublicIndexerTest() + ob = Test.PublicIndexerTest() - object[0] = "zero" - self.assertTrue(object[0] == "zero") + ob[0] = "zero" + self.assertTrue(ob[0] == "zero") - object[1] = "one" - self.assertTrue(object[1] == "one") + ob[1] = "one" + self.assertTrue(ob[1] == "one") - self.assertTrue(object[10] == None) + self.assertTrue(ob[10] == None) def testProtectedIndexer(self): """Test protected indexers.""" - object = Test.ProtectedIndexerTest() + ob = Test.ProtectedIndexerTest() - object[0] = "zero" - self.assertTrue(object[0] == "zero") + ob[0] = "zero" + self.assertTrue(ob[0] == "zero") - object[1] = "one" - self.assertTrue(object[1] == "one") + ob[1] = "one" + self.assertTrue(ob[1] == "one") - self.assertTrue(object[10] == None) + self.assertTrue(ob[10] == None) def testInternalIndexer(self): """Test internal indexers.""" - object = Test.InternalIndexerTest() + ob = Test.InternalIndexerTest() def test(): - object[0] = "zero" + ob[0] = "zero" self.assertRaises(TypeError, test) def test(): - Test.InternalIndexerTest.__getitem__(object, 0) + Test.InternalIndexerTest.__getitem__(ob, 0) self.assertRaises(TypeError, test) def test(): - object.__getitem__(0) + ob.__getitem__(0) self.assertRaises(TypeError, test) def testPrivateIndexer(self): """Test private indexers.""" - object = Test.PrivateIndexerTest() + ob = Test.PrivateIndexerTest() def test(): - object[0] = "zero" + ob[0] = "zero" self.assertRaises(TypeError, test) def test(): - Test.PrivateIndexerTest.__getitem__(object, 0) + Test.PrivateIndexerTest.__getitem__(ob, 0) self.assertRaises(TypeError, test) def test(): - object.__getitem__(0) + ob.__getitem__(0) self.assertRaises(TypeError, test) def testBooleanIndexer(self): """Test boolean indexers.""" - object = Test.BooleanIndexerTest() + ob = Test.BooleanIndexerTest() - self.assertTrue(object[True] == None) - self.assertTrue(object[1] == None) + self.assertTrue(ob[True] == None) + self.assertTrue(ob[1] == None) - object[0] = "false" - self.assertTrue(object[0] == "false") + ob[0] = "false" + self.assertTrue(ob[0] == "false") - object[1] = "true" - self.assertTrue(object[1] == "true") + ob[1] = "true" + self.assertTrue(ob[1] == "true") - object[False] = "false" - self.assertTrue(object[False] == "false") + ob[False] = "false" + self.assertTrue(ob[False] == "false") - object[True] = "true" - self.assertTrue(object[True] == "true") + ob[True] = "true" + self.assertTrue(ob[True] == "true") def testByteIndexer(self): """Test byte indexers.""" - object = Test.ByteIndexerTest() + ob = Test.ByteIndexerTest() max = 255 min = 0 - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = str(max) - self.assertTrue(object[max] == str(max)) + ob[max] = str(max) + self.assertTrue(ob[max] == str(max)) - object[min] = str(min) - self.assertTrue(object[min] == str(min)) + ob[min] = str(min) + self.assertTrue(ob[min] == str(min)) def test(): - object = Test.ByteIndexerTest() - object["wrong"] + ob = Test.ByteIndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.ByteIndexerTest() - object["wrong"] = "wrong" + ob = Test.ByteIndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testSByteIndexer(self): """Test sbyte indexers.""" - object = Test.SByteIndexerTest() + ob = Test.SByteIndexerTest() max = 127 min = -128 - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = str(max) - self.assertTrue(object[max] == str(max)) + ob[max] = str(max) + self.assertTrue(ob[max] == str(max)) - object[min] = str(min) - self.assertTrue(object[min] == str(min)) + ob[min] = str(min) + self.assertTrue(ob[min] == str(min)) def test(): - object = Test.SByteIndexerTest() - object["wrong"] + ob = Test.SByteIndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.SByteIndexerTest() - object["wrong"] = "wrong" + ob = Test.SByteIndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testCharIndexer(self): """Test char indexers.""" - object = Test.CharIndexerTest() + ob = Test.CharIndexerTest() max = unichr(65535) min = unichr(0) - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = "max" - self.assertTrue(object[max] == "max") + ob[max] = "max" + self.assertTrue(ob[max] == "max") - object[min] = "min" - self.assertTrue(object[min] == "min") + ob[min] = "min" + self.assertTrue(ob[min] == "min") def test(): - object = Test.CharIndexerTest() - object["wrong"] + ob = Test.CharIndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.CharIndexerTest() - object["wrong"] = "wrong" + ob = Test.CharIndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testInt16Indexer(self): """Test Int16 indexers.""" - object = Test.Int16IndexerTest() + ob = Test.Int16IndexerTest() max = 32767 min = -32768 - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = str(max) - self.assertTrue(object[max] == str(max)) + ob[max] = str(max) + self.assertTrue(ob[max] == str(max)) - object[min] = str(min) - self.assertTrue(object[min] == str(min)) + ob[min] = str(min) + self.assertTrue(ob[min] == str(min)) def test(): - object = Test.Int16IndexerTest() - object["wrong"] + ob = Test.Int16IndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.Int16IndexerTest() - object["wrong"] = "wrong" + ob = Test.Int16IndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testInt32Indexer(self): """Test Int32 indexers.""" - object = Test.Int32IndexerTest() + ob = Test.Int32IndexerTest() max = 2147483647 min = -2147483648 - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = str(max) - self.assertTrue(object[max] == str(max)) + ob[max] = str(max) + self.assertTrue(ob[max] == str(max)) - object[min] = str(min) - self.assertTrue(object[min] == str(min)) + ob[min] = str(min) + self.assertTrue(ob[min] == str(min)) def test(): - object = Test.Int32IndexerTest() - object["wrong"] + ob = Test.Int32IndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.Int32IndexerTest() - object["wrong"] = "wrong" + ob = Test.Int32IndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testInt64Indexer(self): """Test Int64 indexers.""" - object = Test.Int64IndexerTest() + ob = Test.Int64IndexerTest() max = long(9223372036854775807) min = long(-9223372036854775808) - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = str(max) - self.assertTrue(object[max] == str(max)) + ob[max] = str(max) + self.assertTrue(ob[max] == str(max)) - object[min] = str(min) - self.assertTrue(object[min] == str(min)) + ob[min] = str(min) + self.assertTrue(ob[min] == str(min)) def test(): - object = Test.Int64IndexerTest() - object["wrong"] + ob = Test.Int64IndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.Int64IndexerTest() - object["wrong"] = "wrong" + ob = Test.Int64IndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testUInt16Indexer(self): """Test UInt16 indexers.""" - object = Test.UInt16IndexerTest() + ob = Test.UInt16IndexerTest() max = 65535 min = 0 - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = str(max) - self.assertTrue(object[max] == str(max)) + ob[max] = str(max) + self.assertTrue(ob[max] == str(max)) - object[min] = str(min) - self.assertTrue(object[min] == str(min)) + ob[min] = str(min) + self.assertTrue(ob[min] == str(min)) def test(): - object = Test.UInt16IndexerTest() - object["wrong"] + ob = Test.UInt16IndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.UInt16IndexerTest() - object["wrong"] = "wrong" + ob = Test.UInt16IndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testUInt32Indexer(self): """Test UInt32 indexers.""" - object = Test.UInt32IndexerTest() + ob = Test.UInt32IndexerTest() max = long(4294967295) min = 0 - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = str(max) - self.assertTrue(object[max] == str(max)) + ob[max] = str(max) + self.assertTrue(ob[max] == str(max)) - object[min] = str(min) - self.assertTrue(object[min] == str(min)) + ob[min] = str(min) + self.assertTrue(ob[min] == str(min)) def test(): - object = Test.UInt32IndexerTest() - object["wrong"] + ob = Test.UInt32IndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.UInt32IndexerTest() - object["wrong"] = "wrong" + ob = Test.UInt32IndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testUInt64Indexer(self): """Test UInt64 indexers.""" - object = Test.UInt64IndexerTest() + ob = Test.UInt64IndexerTest() max = long(18446744073709551615) min = 0 - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = str(max) - self.assertTrue(object[max] == str(max)) + ob[max] = str(max) + self.assertTrue(ob[max] == str(max)) - object[min] = str(min) - self.assertTrue(object[min] == str(min)) + ob[min] = str(min) + self.assertTrue(ob[min] == str(min)) def test(): - object = Test.UInt64IndexerTest() - object["wrong"] + ob = Test.UInt64IndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.UInt64IndexerTest() - object["wrong"] = "wrong" + ob = Test.UInt64IndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testSingleIndexer(self): """Test Single indexers.""" - object = Test.SingleIndexerTest() + ob = Test.SingleIndexerTest() max = 3.402823e38 min = -3.402823e38 - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = "max" - self.assertTrue(object[max] == "max") + ob[max] = "max" + self.assertTrue(ob[max] == "max") - object[min] = "min" - self.assertTrue(object[min] == "min") + ob[min] = "min" + self.assertTrue(ob[min] == "min") def test(): - object = Test.SingleIndexerTest() - object["wrong"] + ob = Test.SingleIndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.SingleIndexerTest() - object["wrong"] = "wrong" + ob = Test.SingleIndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testDoubleIndexer(self): """Test Double indexers.""" - object = Test.DoubleIndexerTest() + ob = Test.DoubleIndexerTest() max = 1.7976931348623157e308 min = -1.7976931348623157e308 - self.assertTrue(object[max] == None) + self.assertTrue(ob[max] == None) - object[max] = "max" - self.assertTrue(object[max] == "max") + ob[max] = "max" + self.assertTrue(ob[max] == "max") - object[min] = "min" - self.assertTrue(object[min] == "min") + ob[min] = "min" + self.assertTrue(ob[min] == "min") def test(): - object = Test.DoubleIndexerTest() - object["wrong"] + ob = Test.DoubleIndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.DoubleIndexerTest() - object["wrong"] = "wrong" + ob = Test.DoubleIndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testDecimalIndexer(self): """Test Decimal indexers.""" - object = Test.DecimalIndexerTest() + ob = Test.DecimalIndexerTest() from System import Decimal max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") - self.assertTrue(object[max_d] == None) + self.assertTrue(ob[max_d] == None) - object[max_d] = "max" - self.assertTrue(object[max_d] == "max") + ob[max_d] = "max" + self.assertTrue(ob[max_d] == "max") - object[min_d] = "min" - self.assertTrue(object[min_d] == "min") + ob[min_d] = "min" + self.assertTrue(ob[min_d] == "min") def test(): - object = Test.DecimalIndexerTest() - object["wrong"] + ob = Test.DecimalIndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.DecimalIndexerTest() - object["wrong"] = "wrong" + ob = Test.DecimalIndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testStringIndexer(self): """Test String indexers.""" - object = Test.StringIndexerTest() + ob = Test.StringIndexerTest() - self.assertTrue(object["spam"] == None) - self.assertTrue(object[u"spam"] == None) + self.assertTrue(ob["spam"] == None) + self.assertTrue(ob[u"spam"] == None) - object["spam"] = "spam" - self.assertTrue(object["spam"] == "spam") - self.assertTrue(object["spam"] == u"spam") - self.assertTrue(object[u"spam"] == "spam") - self.assertTrue(object[u"spam"] == u"spam") + ob["spam"] = "spam" + self.assertTrue(ob["spam"] == "spam") + self.assertTrue(ob["spam"] == u"spam") + self.assertTrue(ob[u"spam"] == "spam") + self.assertTrue(ob[u"spam"] == u"spam") - object[u"eggs"] = u"eggs" - self.assertTrue(object["eggs"] == "eggs") - self.assertTrue(object["eggs"] == u"eggs") - self.assertTrue(object[u"eggs"] == "eggs") - self.assertTrue(object[u"eggs"] == u"eggs") + ob[u"eggs"] = u"eggs" + self.assertTrue(ob["eggs"] == "eggs") + self.assertTrue(ob["eggs"] == u"eggs") + self.assertTrue(ob[u"eggs"] == "eggs") + self.assertTrue(ob[u"eggs"] == u"eggs") def test(): - object = Test.StringIndexerTest() - object[1] + ob = Test.StringIndexerTest() + ob[1] self.assertRaises(TypeError, test) def test(): - object = Test.StringIndexerTest() - object[1] = "wrong" + ob = Test.StringIndexerTest() + ob[1] = "wrong" self.assertRaises(TypeError, test) def testEnumIndexer(self): """Test enum indexers.""" - object = Test.EnumIndexerTest() + ob = Test.EnumIndexerTest() key = Test.ShortEnum.One - self.assertTrue(object[key] == None) + self.assertTrue(ob[key] == None) - object[key] = "spam" - self.assertTrue(object[key] == "spam") + ob[key] = "spam" + self.assertTrue(ob[key] == "spam") - object[key] = "eggs" - self.assertTrue(object[key] == "eggs") + ob[key] = "eggs" + self.assertTrue(ob[key] == "eggs") - object[1] = "spam" - self.assertTrue(object[1] == "spam") + ob[1] = "spam" + self.assertTrue(ob[1] == "spam") def test(): - object = Test.EnumIndexerTest() - object["wrong"] + ob = Test.EnumIndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.EnumIndexerTest() - object["wrong"] = "wrong" + ob = Test.EnumIndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testObjectIndexer(self): - """Test object indexers.""" - object = Test.ObjectIndexerTest() + """Test ob indexers.""" + ob = Test.ObjectIndexerTest() from Python.Test import Spam spam = Spam("spam") - self.assertTrue(object[spam] == None) - self.assertTrue(object["spam"] == None) - self.assertTrue(object[1] == None) - self.assertTrue(object[None] == None) + self.assertTrue(ob[spam] == None) + self.assertTrue(ob["spam"] == None) + self.assertTrue(ob[1] == None) + self.assertTrue(ob[None] == None) - object[spam] = "spam" - self.assertTrue(object[spam] == "spam") + ob[spam] = "spam" + self.assertTrue(ob[spam] == "spam") - object["spam"] = "eggs" - self.assertTrue(object["spam"] == "eggs") + ob["spam"] = "eggs" + self.assertTrue(ob["spam"] == "eggs") - object[1] = "one" - self.assertTrue(object[1] == "one") + ob[1] = "one" + self.assertTrue(ob[1] == "one") - object[long(1)] = "long" - self.assertTrue(object[long(1)] == "long") + ob[long(1)] = "long" + self.assertTrue(ob[long(1)] == "long") def test(): class eggs: pass key = eggs() - object = Test.ObjectIndexerTest() - object[key] = "wrong" + ob = Test.ObjectIndexerTest() + ob[key] = "wrong" self.assertRaises(TypeError, test) def testInterfaceIndexer(self): """Test interface indexers.""" - object = Test.InterfaceIndexerTest() + ob = Test.InterfaceIndexerTest() from Python.Test import Spam spam = Spam("spam") - self.assertTrue(object[spam] == None) + self.assertTrue(ob[spam] == None) - object[spam] = "spam" - self.assertTrue(object[spam] == "spam") + ob[spam] = "spam" + self.assertTrue(ob[spam] == "spam") - object[spam] = "eggs" - self.assertTrue(object[spam] == "eggs") + ob[spam] = "eggs" + self.assertTrue(ob[spam] == "eggs") def test(): - object = Test.InterfaceIndexerTest() - object["wrong"] + ob = Test.InterfaceIndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.InterfaceIndexerTest() - object["wrong"] = "wrong" + ob = Test.InterfaceIndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testTypedIndexer(self): """Test typed indexers.""" - object = Test.TypedIndexerTest() + ob = Test.TypedIndexerTest() from Python.Test import Spam spam = Spam("spam") - self.assertTrue(object[spam] == None) + self.assertTrue(ob[spam] == None) - object[spam] = "spam" - self.assertTrue(object[spam] == "spam") + ob[spam] = "spam" + self.assertTrue(ob[spam] == "spam") - object[spam] = "eggs" - self.assertTrue(object[spam] == "eggs") + ob[spam] = "eggs" + self.assertTrue(ob[spam] == "eggs") def test(): - object = Test.TypedIndexerTest() - object["wrong"] + ob = Test.TypedIndexerTest() + ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.TypedIndexerTest() - object["wrong"] = "wrong" + ob = Test.TypedIndexerTest() + ob["wrong"] = "wrong" self.assertRaises(TypeError, test) def testMultiArgIndexer(self): """Test indexers that take multiple index arguments.""" - object = Test.MultiArgIndexerTest() + ob = Test.MultiArgIndexerTest() - object[0, 1] = "zero one" - self.assertTrue(object[0, 1] == "zero one") + ob[0, 1] = "zero one" + self.assertTrue(ob[0, 1] == "zero one") - object[1, 9] = "one nine" - self.assertTrue(object[1, 9] == "one nine") + ob[1, 9] = "one nine" + self.assertTrue(ob[1, 9] == "one nine") - self.assertTrue(object[10, 50] == None) + self.assertTrue(ob[10, 50] == None) def test(): - object = Test.MultiArgIndexerTest() - v = object[0, "one"] + ob = Test.MultiArgIndexerTest() + v = ob[0, "one"] self.assertRaises(TypeError, test) def test(): - object = Test.MultiArgIndexerTest() - object[0, "one"] = "wrong" + ob = Test.MultiArgIndexerTest() + ob[0, "one"] = "wrong" self.assertRaises(TypeError, test) def testMultiTypeIndexer(self): """Test indexers that take multiple indices of different types.""" - object = Test.MultiTypeIndexerTest() + ob = Test.MultiTypeIndexerTest() spam = Test.Spam("spam") - object[0, "one", spam] = "zero one spam" - self.assertTrue(object[0, "one", spam] == "zero one spam") + ob[0, "one", spam] = "zero one spam" + self.assertTrue(ob[0, "one", spam] == "zero one spam") - object[1, "nine", spam] = "one nine spam" - self.assertTrue(object[1, "nine", spam] == "one nine spam") + ob[1, "nine", spam] = "one nine spam" + self.assertTrue(ob[1, "nine", spam] == "one nine spam") def test(): - object = Test.MultiTypeIndexerTest() - v = object[0, 1, spam] + ob = Test.MultiTypeIndexerTest() + v = ob[0, 1, spam] self.assertRaises(TypeError, test) def test(): - object = Test.MultiTypeIndexerTest() - object[0, 1, spam] = "wrong" + ob = Test.MultiTypeIndexerTest() + ob[0, 1, spam] = "wrong" self.assertRaises(TypeError, test) def testMultiDefaultKeyIndexer(self): """Test indexers that take multiple indices with a default key arguments.""" # default argument is 2 in the MultiDefaultKeyIndexerTest object - object = Test.MultiDefaultKeyIndexerTest() - object[0, 2] = "zero one spam" - self.assertTrue(object[0] == "zero one spam") + ob = Test.MultiDefaultKeyIndexerTest() + ob[0, 2] = "zero one spam" + self.assertTrue(ob[0] == "zero one spam") - object[1] = "one nine spam" - self.assertTrue(object[1, 2] == "one nine spam") + ob[1] = "one nine spam" + self.assertTrue(ob[1, 2] == "one nine spam") def testIndexerWrongKeyType(self): """Test calling an indexer using a key of the wrong type.""" def test(): - object = Test.PublicIndexerTest() - v = object["wrong"] + ob = Test.PublicIndexerTest() + v = ob["wrong"] self.assertRaises(TypeError, test) def test(): - object = Test.PublicIndexerTest() - object["wrong"] = "spam" + ob = Test.PublicIndexerTest() + ob["wrong"] = "spam" self.assertRaises(TypeError, test) @@ -629,27 +629,27 @@ def testIndexerWrongValueType(self): """Test calling an indexer using a value of the wrong type.""" def test(): - object = Test.PublicIndexerTest() - object[1] = 9993.9 + ob = Test.PublicIndexerTest() + ob[1] = 9993.9 self.assertRaises(TypeError, test) def testUnboundIndexer(self): """Test calling an unbound indexer.""" - object = Test.PublicIndexerTest() + ob = Test.PublicIndexerTest() - Test.PublicIndexerTest.__setitem__(object, 0, "zero") - self.assertTrue(object[0] == "zero") + Test.PublicIndexerTest.__setitem__(ob, 0, "zero") + self.assertTrue(ob[0] == "zero") - Test.PublicIndexerTest.__setitem__(object, 1, "one") - self.assertTrue(object[1] == "one") + Test.PublicIndexerTest.__setitem__(ob, 1, "one") + self.assertTrue(ob[1] == "one") - self.assertTrue(object[10] == None) + self.assertTrue(ob[10] == None) def testIndexerAbuse(self): """Test indexer abuse.""" _class = Test.PublicIndexerTest - object = Test.PublicIndexerTest() + ob = Test.PublicIndexerTest() def test(): del _class.__getitem__ @@ -657,7 +657,7 @@ def test(): self.assertRaises(AttributeError, test) def test(): - del object.__getitem__ + del ob.__getitem__ self.assertRaises(AttributeError, test) @@ -667,7 +667,7 @@ def test(): self.assertRaises(AttributeError, test) def test(): - del object.__setitem__ + del ob.__setitem__ self.assertRaises(AttributeError, test) diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 88652cd71..0430bb019 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -59,26 +59,26 @@ def test(): def testPublicInstanceMethod(self): """Test public instance method visibility.""" - object = MethodTest() - self.assertTrue(object.PublicMethod() == "public") + ob = MethodTest() + self.assertTrue(ob.PublicMethod() == "public") def testPublicStaticMethod(self): """Test public static method visibility.""" - object = MethodTest() + ob = MethodTest() self.assertTrue(MethodTest.PublicStaticMethod() == "public static") - self.assertTrue(object.PublicStaticMethod() == "public static") + self.assertTrue(ob.PublicStaticMethod() == "public static") def testProtectedInstanceMethod(self): """Test protected instance method visibility.""" - object = MethodTest() - self.assertTrue(object.ProtectedMethod() == "protected") + ob = MethodTest() + self.assertTrue(ob.ProtectedMethod() == "protected") def testProtectedStaticMethod(self): """Test protected static method visibility.""" - object = MethodTest() + ob = MethodTest() result = "protected static" self.assertTrue(MethodTest.ProtectedStaticMethod() == result) - self.assertTrue(object.ProtectedStaticMethod() == result) + self.assertTrue(ob.ProtectedStaticMethod() == result) def testInternalMethod(self): """Test internal method visibility.""" @@ -130,17 +130,17 @@ def testUnboundManagedMethodCall(self): """Test calling unbound managed methods.""" from Python.Test import MethodTestSub - object = MethodTest() - self.assertTrue(MethodTest.PublicMethod(object) == "public") + ob = MethodTest() + self.assertTrue(MethodTest.PublicMethod(ob) == "public") def test(): MethodTest.PublicMethod() self.assertRaises(TypeError, test) - object = MethodTestSub() - self.assertTrue(MethodTestSub.PublicMethod(object) == "public") - self.assertTrue(MethodTestSub.PublicMethod(object, "echo") == "echo") + ob = MethodTestSub() + self.assertTrue(MethodTestSub.PublicMethod(ob) == "public") + self.assertTrue(MethodTestSub.PublicMethod(ob, "echo") == "echo") def test(): MethodTestSub.PublicMethod("echo") @@ -151,19 +151,19 @@ def testOverloadedMethodInheritance(self): """Test that overloads are inherited properly.""" from Python.Test import MethodTestSub - object = MethodTest() - self.assertTrue(object.PublicMethod() == "public") + ob = MethodTest() + self.assertTrue(ob.PublicMethod() == "public") def test(): - object = MethodTest() - object.PublicMethod("echo") + ob = MethodTest() + ob.PublicMethod("echo") self.assertRaises(TypeError, test) - object = MethodTestSub() - self.assertTrue(object.PublicMethod() == "public") + ob = MethodTestSub() + self.assertTrue(ob.PublicMethod() == "public") - self.assertTrue(object.PublicMethod("echo") == "echo") + self.assertTrue(ob.PublicMethod("echo") == "echo") def testMethodDescriptorAbuse(self): """Test method descriptor abuse.""" @@ -193,27 +193,27 @@ def testMethodCallEnumConversion(self): """Test enum conversion in method call.""" from System import TypeCode - object = MethodTest() - r = object.TestEnumConversion(TypeCode.Int32) + ob = MethodTest() + r = ob.TestEnumConversion(TypeCode.Int32) self.assertTrue(r == TypeCode.Int32) def testMethodCallFlagsConversion(self): """Test flags conversion in method call.""" from System.IO import FileAccess - object = MethodTest() + ob = MethodTest() flags = FileAccess.Read | FileAccess.Write - r = object.TestFlagsConversion(flags) + r = ob.TestFlagsConversion(flags) self.assertTrue(r == flags) def testMethodCallStructConversion(self): """Test struct conversion in method call.""" from System import Guid - object = MethodTest() + ob = MethodTest() guid = Guid.NewGuid() temp = guid.ToString() - r = object.TestStructConversion(guid) + r = ob.TestStructConversion(guid) self.assertTrue(r.ToString() == temp) def testSubclassInstanceConversion(self): @@ -222,17 +222,17 @@ def testSubclassInstanceConversion(self): class TestSubException(System.Exception): pass - object = MethodTest() + ob = MethodTest() instance = TestSubException() - result = object.TestSubclassConversion(instance) + result = ob.TestSubclassConversion(instance) self.assertTrue(isinstance(result, System.Exception)) def testNullArrayConversion(self): """Test null array conversion in method call.""" from System import Type - object = MethodTest() - r = object.TestNullArrayConversion(None) + ob = MethodTest() + r = ob.TestNullArrayConversion(None) self.assertTrue(r == None) def testStringParamsArgs(self): diff --git a/src/tests/test_property.py b/src/tests/test_property.py index e5d7112ef..b0676f6b1 100644 --- a/src/tests/test_property.py +++ b/src/tests/test_property.py @@ -10,11 +10,11 @@ class PropertyTests(unittest.TestCase): def testPublicInstanceProperty(self): """Test public instance properties.""" - object = PropertyTest() + ob = PropertyTest() - self.assertTrue(object.PublicProperty == 0) - object.PublicProperty = 1 - self.assertTrue(object.PublicProperty == 1) + self.assertTrue(ob.PublicProperty == 0) + ob.PublicProperty = 1 + self.assertTrue(ob.PublicProperty == 1) def test(): del PropertyTest().PublicProperty @@ -23,15 +23,15 @@ def test(): def testPublicStaticProperty(self): """Test public static properties.""" - object = PropertyTest() + ob = PropertyTest() self.assertTrue(PropertyTest.PublicStaticProperty == 0) PropertyTest.PublicStaticProperty = 1 self.assertTrue(PropertyTest.PublicStaticProperty == 1) - self.assertTrue(object.PublicStaticProperty == 1) - object.PublicStaticProperty = 0 - self.assertTrue(object.PublicStaticProperty == 0) + self.assertTrue(ob.PublicStaticProperty == 1) + ob.PublicStaticProperty = 0 + self.assertTrue(ob.PublicStaticProperty == 0) def test(): del PropertyTest.PublicStaticProperty @@ -45,11 +45,11 @@ def test(): def testProtectedInstanceProperty(self): """Test protected instance properties.""" - object = PropertyTest() + ob = PropertyTest() - self.assertTrue(object.ProtectedProperty == 0) - object.ProtectedProperty = 1 - self.assertTrue(object.ProtectedProperty == 1) + self.assertTrue(ob.ProtectedProperty == 0) + ob.ProtectedProperty = 1 + self.assertTrue(ob.ProtectedProperty == 1) def test(): del PropertyTest().ProtectedProperty @@ -58,15 +58,15 @@ def test(): def testProtectedStaticProperty(self): """Test protected static properties.""" - object = PropertyTest() + ob = PropertyTest() self.assertTrue(PropertyTest.ProtectedStaticProperty == 0) PropertyTest.ProtectedStaticProperty = 1 self.assertTrue(PropertyTest.ProtectedStaticProperty == 1) - self.assertTrue(object.ProtectedStaticProperty == 1) - object.ProtectedStaticProperty = 0 - self.assertTrue(object.ProtectedStaticProperty == 0) + self.assertTrue(ob.ProtectedStaticProperty == 1) + ob.ProtectedStaticProperty = 0 + self.assertTrue(ob.ProtectedStaticProperty == 0) def test(): del PropertyTest.ProtectedStaticProperty @@ -82,17 +82,17 @@ def testInternalProperty(self): """Test internal properties.""" def test(): - f = PropertyTest().InternalProperty + return PropertyTest().InternalProperty self.assertRaises(AttributeError, test) def test(): - f = PropertyTest().InternalStaticProperty + return PropertyTest().InternalStaticProperty self.assertRaises(AttributeError, test) def test(): - f = PropertyTest.InternalStaticProperty + return PropertyTest.InternalStaticProperty self.assertRaises(AttributeError, test) @@ -100,17 +100,17 @@ def testPrivateProperty(self): """Test private properties.""" def test(): - f = PropertyTest().PrivateProperty + return PropertyTest().PrivateProperty self.assertRaises(AttributeError, test) def test(): - f = PropertyTest().PrivateStaticProperty + return PropertyTest().PrivateStaticProperty self.assertRaises(AttributeError, test) def test(): - f = PropertyTest.PrivateStaticProperty + return PropertyTest.PrivateStaticProperty self.assertRaises(AttributeError, test) @@ -121,15 +121,15 @@ def testPropertyDescriptorGetSet(self): # a descriptor actually goes through the descriptor (rather than # silently replacing the descriptor in the instance or type dict. - object = PropertyTest() + ob = PropertyTest() self.assertTrue(PropertyTest.PublicStaticProperty == 0) - self.assertTrue(object.PublicStaticProperty == 0) + self.assertTrue(ob.PublicStaticProperty == 0) descriptor = PropertyTest.__dict__['PublicStaticProperty'] self.assertTrue(type(descriptor) != int) - object.PublicStaticProperty = 0 + ob.PublicStaticProperty = 0 descriptor = PropertyTest.__dict__['PublicStaticProperty'] self.assertTrue(type(descriptor) != int) @@ -141,8 +141,8 @@ def testPropertyDescriptorWrongType(self): """Test setting a property using a value of the wrong type.""" def test(): - object = PropertyTest() - object.PublicProperty = "spam" + ob = PropertyTest() + ob.PublicProperty = "spam" self.assertTrue(TypeError, test) @@ -164,8 +164,8 @@ def testInterfaceProperty(self): """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.""" - from System.Collections import Hashtable, ICollection + mapping = Hashtable() coll = ICollection(mapping) self.assertTrue(coll.Count == 0) diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index 20938ba88..444d0a116 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -71,65 +71,65 @@ class SubClassTests(unittest.TestCase): def testBaseClass(self): """Test base class managed type""" - object = SubClassTest() - self.assertEqual(object.foo(), "foo") - self.assertEqual(TestFunctions.test_foo(object), "foo") - self.assertEqual(object.bar("bar", 2), "bar") - self.assertEqual(TestFunctions.test_bar(object, "bar", 2), "bar") - self.assertEqual(object.not_overriden(), "not_overriden") - self.assertEqual(list(object.return_list()), ["a", "b", "c"]) - self.assertEqual(list(SubClassTest.test_list(object)), ["a", "b", "c"]) + ob = SubClassTest() + self.assertEqual(ob.foo(), "foo") + self.assertEqual(TestFunctions.test_foo(ob), "foo") + self.assertEqual(ob.bar("bar", 2), "bar") + self.assertEqual(TestFunctions.test_bar(ob, "bar", 2), "bar") + self.assertEqual(ob.not_overriden(), "not_overriden") + self.assertEqual(list(ob.return_list()), ["a", "b", "c"]) + self.assertEqual(list(SubClassTest.test_list(ob)), ["a", "b", "c"]) def testInterface(self): """Test python classes can derive from C# interfaces""" - object = InterfaceTestClass() - self.assertEqual(object.foo(), "InterfaceTestClass") - self.assertEqual(TestFunctions.test_foo(object), "InterfaceTestClass") - self.assertEqual(object.bar("bar", 2), "bar/bar") - self.assertEqual(TestFunctions.test_bar(object, "bar", 2), "bar/bar") + ob = InterfaceTestClass() + self.assertEqual(ob.foo(), "InterfaceTestClass") + self.assertEqual(TestFunctions.test_foo(ob), "InterfaceTestClass") + self.assertEqual(ob.bar("bar", 2), "bar/bar") + self.assertEqual(TestFunctions.test_bar(ob, "bar", 2), "bar/bar") - x = TestFunctions.pass_through(object) - self.assertEqual(id(x), id(object)) + x = TestFunctions.pass_through(ob) + self.assertEqual(id(x), id(ob)) def testDerivedClass(self): """Test python class derived from managed type""" - object = DerivedClass() - self.assertEqual(object.foo(), "DerivedClass") - self.assertEqual(object.base_foo(), "foo") - self.assertEqual(object.super_foo(), "foo") - self.assertEqual(TestFunctions.test_foo(object), "DerivedClass") - self.assertEqual(object.bar("bar", 2), "bar_bar") - self.assertEqual(TestFunctions.test_bar(object, "bar", 2), "bar_bar") - self.assertEqual(object.not_overriden(), "not_overriden") - self.assertEqual(list(object.return_list()), ["A", "B", "C"]) - self.assertEqual(list(SubClassTest.test_list(object)), ["A", "B", "C"]) - - x = TestFunctions.pass_through(object) - self.assertEqual(id(x), id(object)) + ob = DerivedClass() + self.assertEqual(ob.foo(), "DerivedClass") + self.assertEqual(ob.base_foo(), "foo") + self.assertEqual(ob.super_foo(), "foo") + self.assertEqual(TestFunctions.test_foo(ob), "DerivedClass") + self.assertEqual(ob.bar("bar", 2), "bar_bar") + self.assertEqual(TestFunctions.test_bar(ob, "bar", 2), "bar_bar") + self.assertEqual(ob.not_overriden(), "not_overriden") + self.assertEqual(list(ob.return_list()), ["A", "B", "C"]) + self.assertEqual(list(SubClassTest.test_list(ob)), ["A", "B", "C"]) + + x = TestFunctions.pass_through(ob) + self.assertEqual(id(x), id(ob)) def testCreateInstance(self): """Test derived instances can be created from managed code""" - object = TestFunctions.create_instance(DerivedClass) - self.assertEqual(object.foo(), "DerivedClass") - self.assertEqual(TestFunctions.test_foo(object), "DerivedClass") - self.assertEqual(object.bar("bar", 2), "bar_bar") - self.assertEqual(TestFunctions.test_bar(object, "bar", 2), "bar_bar") - self.assertEqual(object.not_overriden(), "not_overriden") + ob = TestFunctions.create_instance(DerivedClass) + self.assertEqual(ob.foo(), "DerivedClass") + self.assertEqual(TestFunctions.test_foo(ob), "DerivedClass") + self.assertEqual(ob.bar("bar", 2), "bar_bar") + self.assertEqual(TestFunctions.test_bar(ob, "bar", 2), "bar_bar") + self.assertEqual(ob.not_overriden(), "not_overriden") - x = TestFunctions.pass_through(object) - self.assertEqual(id(x), id(object)) + x = TestFunctions.pass_through(ob) + self.assertEqual(id(x), id(ob)) - object2 = TestFunctions.create_instance(InterfaceTestClass) - self.assertEqual(object2.foo(), "InterfaceTestClass") - self.assertEqual(TestFunctions.test_foo(object2), "InterfaceTestClass") - self.assertEqual(object2.bar("bar", 2), "bar/bar") - self.assertEqual(TestFunctions.test_bar(object2, "bar", 2), "bar/bar") + ob2 = TestFunctions.create_instance(InterfaceTestClass) + self.assertEqual(ob2.foo(), "InterfaceTestClass") + self.assertEqual(TestFunctions.test_foo(ob2), "InterfaceTestClass") + self.assertEqual(ob2.bar("bar", 2), "bar/bar") + self.assertEqual(TestFunctions.test_bar(ob2, "bar", 2), "bar/bar") - y = TestFunctions.pass_through(object2) - self.assertEqual(id(y), id(object2)) + y = TestFunctions.pass_through(ob2) + self.assertEqual(id(y), id(ob2)) def testEvents(self): - class EventHandler: + class EventHandler(object): def handler(self, x, args): self.value = args.value From 11445f557f5adfdc702c8655862c4ac7156a720a Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 21 Jan 2017 21:10:12 -0700 Subject: [PATCH 039/245] Refactor utility functions --- src/tests/leaktest.py | 97 ++---------------- src/tests/test_class.py | 20 ++-- src/tests/test_compat.py | 54 ++++------ src/tests/test_delegate.py | 66 +++--------- src/tests/test_event.py | 83 ++------------- src/tests/test_generic.py | 202 +++++++++++++++++++------------------ src/tests/test_indexer.py | 2 +- src/tests/test_module.py | 60 +++++------ src/tests/utils.py | 132 ++++++++++++++++++++++++ 9 files changed, 315 insertions(+), 401 deletions(-) create mode 100644 src/tests/utils.py diff --git a/src/tests/leaktest.py b/src/tests/leaktest.py index 43a0e83a7..666e6e276 100644 --- a/src/tests/leaktest.py +++ b/src/tests/leaktest.py @@ -6,10 +6,14 @@ import clr import gc +import sys import System from _compat import range +from utils import (CallableHandler, ClassMethodHandler, GenericHandler, + HelloClass, StaticMethodHandler, VarCallableHandler, + VariableArgsHandler, hello_func) class LeakTest(object): @@ -53,7 +57,6 @@ def run(self): self.testDelegates() def report(self): - import sys, gc gc.collect() dicttype = type({}) for item in gc.get_objects(): @@ -78,7 +81,6 @@ def testModules(self): def testClasses(self): from System.Collections import Hashtable from Python.Test import StringDelegate - from System import Int32 self.notify("Running class leak check...") @@ -91,7 +93,7 @@ def testClasses(self): del x # Value type - x = Int32(99) + x = System.Int32(99) del x # Delegate type @@ -101,7 +103,7 @@ def testClasses(self): self.end_test() def testEnumerations(self): - from Python import Test + import Python.Test as Test self.notify("Running enum leak check...") @@ -215,7 +217,6 @@ def handler(sender, args, dict=dict): def testDelegates(self): from Python.Test import DelegateTest, StringDelegate - import System self.notify("Running delegate leak check...") @@ -326,92 +327,6 @@ def testDelegates(self): self.end_test() -class GenericHandler(object): - """A generic handler to test event callbacks.""" - - def __init__(self): - self.value = None - - def handler(self, sender, args): - self.value = args.value - - -class VariableArgsHandler(object): - """A variable args handler to test event callbacks.""" - - def __init__(self): - self.value = None - - def handler(self, *args): - ob, eventargs = args - self.value = eventargs.value - - -class CallableHandler(object): - """A callable handler to test event callbacks.""" - - def __init__(self): - self.value = None - - def __call__(self, sender, args): - self.value = args.value - - -class VarCallableHandler(object): - """A variable args callable handler to test event callbacks.""" - - def __init__(self): - self.value = None - - def __call__(self, *args): - ob, eventargs = args - self.value = eventargs.value - - -class StaticMethodHandler(object): - """A static method handler to test event callbacks.""" - - value = None - - def handler(sender, args): - StaticMethodHandler.value = args.value - - handler = staticmethod(handler) - - -class ClassMethodHandler(object): - """A class method handler to test event callbacks.""" - - value = None - - def handler(cls, sender, args): - cls.value = args.value - - handler = classmethod(handler) - - -class HelloClass(object): - def hello(self): - return "hello" - - def __call__(self): - return "hello" - - def s_hello(): - return "hello" - - s_hello = staticmethod(s_hello) - - def c_hello(cls): - return "hello" - - c_hello = classmethod(c_hello) - - -def hello_func(): - return "hello" - - if __name__ == '__main__': test = LeakTest() test.run() diff --git a/src/tests/test_class.py b/src/tests/test_class.py index 169683883..b681c3a11 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -8,6 +8,16 @@ from _compat import DictProxyType, range +class ClassicClass: + def kind(self): + return 'classic' + + +class NewStyleClass(object): + def kind(self): + return 'new-style' + + class ClassTests(unittest.TestCase): """Test CLR class support.""" @@ -273,15 +283,5 @@ def PyCallback(self, self2): self.assertTrue(testobj.SameReference) -class ClassicClass: - def kind(self): - return 'classic' - - -class NewStyleClass(object): - def kind(self): - return 'new-style' - - def test_suite(): return unittest.makeSuite(ClassTests) diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index f89aceece..fbdd5260e 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -4,32 +4,18 @@ import unittest from _compat import ClassType, PY2, PY3, range +from utils import isCLRClass, isCLRModule, isCLRRootModule class CompatibilityTests(unittest.TestCase): - """ - Backward-compatibility tests for deprecated features. - """ - - def isCLRModule(self, object): - return type(object).__name__ == 'ModuleObject' - - def isCLRRootModule(self, object): - if PY3: - # in Python 3 the clr module is a normal python module - return object.__name__ == "clr" - elif PY2: - return type(object).__name__ == 'CLRModule' - - def isCLRClass(self, object): - return type(object).__name__ == 'CLR Metatype' # for now + """Backward-compatibility tests for deprecated features.""" # Tests for old-style CLR-prefixed module naming. def testSimpleImport(self): """Test simple import.""" import CLR - self.assertTrue(self.isCLRRootModule(CLR)) + self.assertTrue(isCLRRootModule(CLR)) self.assertTrue(CLR.__name__ == 'clr') import sys @@ -49,7 +35,7 @@ def testSimpleImport(self): def testSimpleImportWithAlias(self): """Test simple import with aliasing.""" import CLR as myCLR - self.assertTrue(self.isCLRRootModule(myCLR)) + self.assertTrue(isCLRRootModule(myCLR)) self.assertTrue(myCLR.__name__ == 'clr') import sys as mySys @@ -69,11 +55,11 @@ def testSimpleImportWithAlias(self): def testDottedNameImport(self): """Test dotted-name import.""" import CLR.System - self.assertTrue(self.isCLRModule(CLR.System)) + self.assertTrue(isCLRModule(CLR.System)) self.assertTrue(CLR.System.__name__ == 'System') import System - self.assertTrue(self.isCLRModule(System)) + self.assertTrue(isCLRModule(System)) self.assertTrue(System.__name__ == 'System') self.assertTrue(System is CLR.System) @@ -85,11 +71,11 @@ def testDottedNameImport(self): def testDottedNameImportWithAlias(self): """Test dotted-name import with aliasing.""" import CLR.System as myCLRSystem - self.assertTrue(self.isCLRModule(myCLRSystem)) + self.assertTrue(isCLRModule(myCLRSystem)) self.assertTrue(myCLRSystem.__name__ == 'System') import System as mySystem - self.assertTrue(self.isCLRModule(mySystem)) + self.assertTrue(isCLRModule(mySystem)) self.assertTrue(mySystem.__name__ == 'System') self.assertTrue(mySystem is myCLRSystem) @@ -101,7 +87,7 @@ def testDottedNameImportWithAlias(self): def testSimpleImportFrom(self): """Test simple 'import from'.""" from CLR import System - self.assertTrue(self.isCLRModule(System)) + self.assertTrue(isCLRModule(System)) self.assertTrue(System.__name__ == 'System') from xml import dom @@ -111,7 +97,7 @@ def testSimpleImportFrom(self): def testSimpleImportFromWithAlias(self): """Test simple 'import from' with aliasing.""" from CLR import System as mySystem - self.assertTrue(self.isCLRModule(mySystem)) + self.assertTrue(isCLRModule(mySystem)) self.assertTrue(mySystem.__name__ == 'System') from xml import dom as myDom @@ -121,11 +107,11 @@ def testSimpleImportFromWithAlias(self): def testDottedNameImportFrom(self): """Test dotted-name 'import from'.""" from CLR.System import Xml - self.assertTrue(self.isCLRModule(Xml)) + self.assertTrue(isCLRModule(Xml)) self.assertTrue(Xml.__name__ == 'System.Xml') from CLR.System.Xml import XmlDocument - self.assertTrue(self.isCLRClass(XmlDocument)) + self.assertTrue(isCLRClass(XmlDocument)) self.assertTrue(XmlDocument.__name__ == 'XmlDocument') from xml.dom import pulldom @@ -139,11 +125,11 @@ def testDottedNameImportFrom(self): def testDottedNameImportFromWithAlias(self): """Test dotted-name 'import from' with aliasing.""" from CLR.System import Xml as myXml - self.assertTrue(self.isCLRModule(myXml)) + self.assertTrue(isCLRModule(myXml)) self.assertTrue(myXml.__name__ == 'System.Xml') from CLR.System.Xml import XmlDocument as myXmlDocument - self.assertTrue(self.isCLRClass(myXmlDocument)) + self.assertTrue(isCLRClass(myXmlDocument)) self.assertTrue(myXmlDocument.__name__ == 'XmlDocument') from xml.dom import pulldom as myPulldom @@ -159,12 +145,12 @@ def testFromModuleImportStar(self): count = len(locals().keys()) m = __import__('CLR.System.Management', globals(), locals(), ['*']) self.assertTrue(m.__name__ == 'System.Management') - self.assertTrue(self.isCLRModule(m)) + self.assertTrue(isCLRModule(m)) self.assertTrue(len(locals().keys()) > count + 1) m2 = __import__('System.Management', globals(), locals(), ['*']) self.assertTrue(m2.__name__ == 'System.Management') - self.assertTrue(self.isCLRModule(m2)) + self.assertTrue(isCLRModule(m2)) self.assertTrue(len(locals().keys()) > count + 1) self.assertTrue(m is m2) @@ -193,7 +179,7 @@ def testImplicitLoadAlreadyValidNamespace(self): # Python runtime to "do the right thing", allowing types from both # assemblies to be found in the CLR.System module implicitly. import CLR.System - self.assertTrue(self.isCLRClass(CLR.System.UriBuilder)) + self.assertTrue(isCLRClass(CLR.System.UriBuilder)) def testImportNonExistantModule(self): """Test import failure for a non-existant module.""" @@ -211,7 +197,7 @@ def testLookupNoNamespaceType(self): """Test lookup of types without a qualified namespace.""" import CLR.Python.Test import CLR - self.assertTrue(self.isCLRClass(CLR.NoNamespaceType)) + self.assertTrue(isCLRClass(CLR.NoNamespaceType)) def testModuleLookupRecursion(self): """Test for recursive lookup handling.""" @@ -232,10 +218,10 @@ def testModuleGetAttr(self): import CLR.System as System int_type = System.Int32 - self.assertTrue(self.isCLRClass(int_type)) + self.assertTrue(isCLRClass(int_type)) module = System.Xml - self.assertTrue(self.isCLRModule(module)) + self.assertTrue(isCLRModule(module)) def test(): spam = System.Spam diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index df371ca9a..33940caca 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -8,6 +8,7 @@ from Python.Test import DelegateTest, StringDelegate from _compat import DictProxyType +from utils import HelloClass, hello_func, MultipleHandler class DelegateTests(unittest.TestCase): @@ -60,10 +61,7 @@ def test(): def testDelegateFromFunction(self): """Test delegate implemented with a Python function.""" - def sayhello(): - return "hello" - - d = StringDelegate(sayhello) + d = StringDelegate(hello_func) ob = DelegateTest() self.assertTrue(ob.CallStringDelegate(d) == "hello") @@ -76,12 +74,8 @@ def sayhello(): def testDelegateFromMethod(self): """Test delegate implemented with a Python instance method.""" - class Hello: - def sayhello(self): - return "hello" - - inst = Hello() - d = StringDelegate(inst.sayhello) + inst = HelloClass() + d = StringDelegate(inst.hello) ob = DelegateTest() self.assertTrue(ob.CallStringDelegate(d) == "hello") @@ -94,12 +88,8 @@ def sayhello(self): def testDelegateFromUnboundMethod(self): """Test failure mode for unbound methods.""" - class Hello: - def sayhello(self): - return "hello" - def test(): - d = StringDelegate(Hello.sayhello) + d = StringDelegate(HelloClass.hello) d() self.assertRaises(TypeError, test) @@ -107,13 +97,7 @@ def test(): def testDelegateFromStaticMethod(self): """Test delegate implemented with a Python static method.""" - class Hello: - def sayhello(): - return "hello" - - sayhello = staticmethod(sayhello) - - d = StringDelegate(Hello.sayhello) + d = StringDelegate(HelloClass.s_hello) ob = DelegateTest() self.assertTrue(ob.CallStringDelegate(d) == "hello") @@ -123,8 +107,8 @@ def sayhello(): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - inst = Hello() - d = StringDelegate(inst.sayhello) + inst = HelloClass() + d = StringDelegate(inst.s_hello) ob = DelegateTest() self.assertTrue(ob.CallStringDelegate(d) == "hello") @@ -137,13 +121,7 @@ def sayhello(): def testDelegateFromClassMethod(self): """Test delegate implemented with a Python class method.""" - class Hello: - def sayhello(self): - return "hello" - - sayhello = classmethod(sayhello) - - d = StringDelegate(Hello.sayhello) + d = StringDelegate(HelloClass.c_hello) ob = DelegateTest() self.assertTrue(ob.CallStringDelegate(d) == "hello") @@ -153,8 +131,8 @@ def sayhello(self): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - inst = Hello() - d = StringDelegate(inst.sayhello) + inst = HelloClass() + d = StringDelegate(inst.c_hello) ob = DelegateTest() self.assertTrue(ob.CallStringDelegate(d) == "hello") @@ -167,11 +145,7 @@ def sayhello(self): def testDelegateFromCallable(self): """Test delegate implemented with a Python callable object.""" - class Hello: - def __call__(self): - return "hello" - - inst = Hello() + inst = HelloClass() d = StringDelegate(inst) ob = DelegateTest() @@ -208,11 +182,7 @@ def testDelegateFromManagedStaticMethod(self): def testDelegateFromDelegate(self): """Test delegate implemented with another delegate.""" - - def sayhello(): - return "hello" - - d1 = StringDelegate(sayhello) + d1 = StringDelegate(hello_func) d2 = StringDelegate(d1) ob = DelegateTest() @@ -244,15 +214,7 @@ def test(): def testMulticastDelegate(self): """Test multicast delegates.""" - class Multi: - def __init__(self): - self.value = 0 - - def count(self): - self.value += 1 - return 'ok' - - inst = Multi() + inst = MultipleHandler() d1 = StringDelegate(inst.count) d2 = StringDelegate(inst.count) diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 008b6b20a..858069f6c 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -5,6 +5,9 @@ from Python.Test import EventTest, TestEventArgs from _compat import range +from utils import (CallableHandler, ClassMethodHandler, GenericHandler, + MultipleHandler, StaticMethodHandler, VarCallableHandler, + VariableArgsHandler) class EventTests(unittest.TestCase): @@ -311,7 +314,7 @@ def test(): self.assertRaises(TypeError, test) def test(): - class spam: + class spam(object): pass ob = EventTest() @@ -486,7 +489,7 @@ def test(): def testHandlerCallbackFailure(self): """Test failure mode for inappropriate handlers.""" - class BadHandler: + class BadHandler(object): def handler(self, one): return 'too many' @@ -501,7 +504,7 @@ def test(): ob.PublicEvent -= handler.handler - class BadHandler: + class BadHandler(object): def handler(self, one, two, three, four, five): return 'not enough' @@ -602,79 +605,5 @@ def test(): self.assertRaises(TypeError, test) -class GenericHandler: - """A generic handler to test event callbacks.""" - - def __init__(self): - self.value = None - - def handler(self, sender, args): - self.value = args.value - - -class VariableArgsHandler: - """A variable args handler to test event callbacks.""" - - def __init__(self): - self.value = None - - def handler(self, *args): - ob, eventargs = args - self.value = eventargs.value - - -class CallableHandler: - """A callable handler to test event callbacks.""" - - def __init__(self): - self.value = None - - def __call__(self, sender, args): - self.value = args.value - - -class VarCallableHandler: - """A variable args callable handler to test event callbacks.""" - - def __init__(self): - self.value = None - - def __call__(self, *args): - ob, eventargs = args - self.value = eventargs.value - - -class StaticMethodHandler(object): - """A static method handler to test event callbacks.""" - - value = None - - def handler(sender, args): - StaticMethodHandler.value = args.value - - handler = staticmethod(handler) - - -class ClassMethodHandler(object): - """A class method handler to test event callbacks.""" - - value = None - - def handler(cls, sender, args): - cls.value = args.value - - handler = classmethod(handler) - - -class MultipleHandler: - """A generic handler to test multiple callbacks.""" - - def __init__(self): - self.value = 0 - - def handler(self, sender, args): - self.value += args.value - - def test_suite(): return unittest.makeSuite(EventTests) diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index 67af8acb4..536a2bb7f 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -11,6 +11,107 @@ class GenericTests(unittest.TestCase): """Test CLR generics support.""" + def _testGenericWrapperByType(self, ptype, value): + """Test Helper""" + from Python.Test import GenericWrapper + import System + + inst = GenericWrapper[ptype](value) + self.assertTrue(inst.value == value) + + atype = System.Array[ptype] + items = atype([value, value, value]) + inst = GenericWrapper[atype](items) + self.assertTrue(len(inst.value) == 3) + self.assertTrue(inst.value[0] == value) + self.assertTrue(inst.value[1] == value) + + def _testGenericMethodByType(self, ptype, value, test_type=0): + """Test Helper""" + from Python.Test import GenericMethodTest, GenericStaticMethodTest + import System + + itype = GenericMethodTest[System.Type] + stype = GenericStaticMethodTest[System.Type] + + # Explicit selection (static method) + result = stype.Overloaded[ptype](value) + if test_type: + self.assertTrue(result.__class__ == value.__class__) + else: + self.assertTrue(result == value) + + # Type inference (static method) + result = stype.Overloaded(value) + self.assertTrue(result == value) + if test_type: + self.assertTrue(result.__class__ == value.__class__) + else: + self.assertTrue(result == value) + + # Explicit selection (instance method) + result = itype().Overloaded[ptype](value) + self.assertTrue(result == value) + if test_type: + self.assertTrue(result.__class__ == value.__class__) + else: + self.assertTrue(result == value) + + # Type inference (instance method) + result = itype().Overloaded(value) + self.assertTrue(result == value) + if test_type: + self.assertTrue(result.__class__ == value.__class__) + else: + self.assertTrue(result == value) + + atype = System.Array[ptype] + items = atype([value, value, value]) + + # Explicit selection (static method) + result = stype.Overloaded[atype](items) + if test_type: + self.assertTrue(len(result) == 3) + self.assertTrue(result[0].__class__ == value.__class__) + self.assertTrue(result[1].__class__ == value.__class__) + else: + self.assertTrue(len(result) == 3) + self.assertTrue(result[0] == value) + self.assertTrue(result[1] == value) + + # Type inference (static method) + result = stype.Overloaded(items) + if test_type: + self.assertTrue(len(result) == 3) + self.assertTrue(result[0].__class__ == value.__class__) + self.assertTrue(result[1].__class__ == value.__class__) + else: + self.assertTrue(len(result) == 3) + self.assertTrue(result[0] == value) + self.assertTrue(result[1] == value) + + # Explicit selection (instance method) + result = itype().Overloaded[atype](items) + if test_type: + self.assertTrue(len(result) == 3) + self.assertTrue(result[0].__class__ == value.__class__) + self.assertTrue(result[1].__class__ == value.__class__) + else: + self.assertTrue(len(result) == 3) + self.assertTrue(result[0] == value) + self.assertTrue(result[1] == value) + + # Type inference (instance method) + result = itype().Overloaded(items) + if test_type: + self.assertTrue(len(result) == 3) + self.assertTrue(result[0].__class__ == value.__class__) + self.assertTrue(result[1].__class__ == value.__class__) + else: + self.assertTrue(len(result) == 3) + self.assertTrue(result[0] == value) + self.assertTrue(result[1] == value) + def testPythonTypeAliasing(self): """Test python type alias support with generics.""" from System.Collections.Generic import Dictionary @@ -80,9 +181,11 @@ def testGenericValueType(self): self.assertTrue(inst.Value == 10) def testGenericInterface(self): + # TODO NotImplemented pass def testGenericDelegate(self): + # TODO NotImplemented pass def testOpenGenericType(self): @@ -138,20 +241,6 @@ def test(): self.assertTrue(_class().value == 2) self.assertTrue(_class.value == 2) - def _testGenericWrapperByType(self, ptype, value, test_type=0): - from Python.Test import GenericWrapper - import System - - inst = GenericWrapper[ptype](value) - self.assertTrue(inst.value == value) - - atype = System.Array[ptype] - items = atype([value, value, value]) - inst = GenericWrapper[atype](items) - self.assertTrue(len(inst.value) == 3) - self.assertTrue(inst.value[0] == value) - self.assertTrue(inst.value[1] == value) - def testGenericTypeBinding(self): """Test argument conversion / binding for generic methods.""" from Python.Test import InterfaceTest, ISayHello1, ShortEnum @@ -184,91 +273,6 @@ def testGenericTypeBinding(self): self._testGenericWrapperByType(InterfaceTest, InterfaceTest()) self._testGenericWrapperByType(ISayHello1, InterfaceTest()) - def _testGenericMethodByType(self, ptype, value, test_type=0): - from Python.Test import GenericMethodTest, GenericStaticMethodTest - import System - - itype = GenericMethodTest[System.Type] - stype = GenericStaticMethodTest[System.Type] - - # Explicit selection (static method) - result = stype.Overloaded[ptype](value) - if test_type: - self.assertTrue(result.__class__ == value.__class__) - else: - self.assertTrue(result == value) - - # Type inference (static method) - result = stype.Overloaded(value) - self.assertTrue(result == value) - if test_type: - self.assertTrue(result.__class__ == value.__class__) - else: - self.assertTrue(result == value) - - # Explicit selection (instance method) - result = itype().Overloaded[ptype](value) - self.assertTrue(result == value) - if test_type: - self.assertTrue(result.__class__ == value.__class__) - else: - self.assertTrue(result == value) - - # Type inference (instance method) - result = itype().Overloaded(value) - self.assertTrue(result == value) - if test_type: - self.assertTrue(result.__class__ == value.__class__) - else: - self.assertTrue(result == value) - - atype = System.Array[ptype] - items = atype([value, value, value]) - - # Explicit selection (static method) - result = stype.Overloaded[atype](items) - if test_type: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0].__class__ == value.__class__) - self.assertTrue(result[1].__class__ == value.__class__) - else: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0] == value) - self.assertTrue(result[1] == value) - - # Type inference (static method) - result = stype.Overloaded(items) - if test_type: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0].__class__ == value.__class__) - self.assertTrue(result[1].__class__ == value.__class__) - else: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0] == value) - self.assertTrue(result[1] == value) - - # Explicit selection (instance method) - result = itype().Overloaded[atype](items) - if test_type: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0].__class__ == value.__class__) - self.assertTrue(result[1].__class__ == value.__class__) - else: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0] == value) - self.assertTrue(result[1] == value) - - # Type inference (instance method) - result = itype().Overloaded(items) - if test_type: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0].__class__ == value.__class__) - self.assertTrue(result[1].__class__ == value.__class__) - else: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0] == value) - self.assertTrue(result[1] == value) - def testGenericMethodBinding(self): from Python.Test import GenericMethodTest, GenericStaticMethodTest from System import InvalidOperationException diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index 4e631de4f..eaa02abd0 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -490,7 +490,7 @@ def testObjectIndexer(self): self.assertTrue(ob[long(1)] == "long") def test(): - class eggs: + class eggs(object): pass key = eggs() diff --git a/src/tests/test_module.py b/src/tests/test_module.py index a2624fc4c..4748c0497 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -7,38 +7,24 @@ from fnmatch import fnmatch from _compat import ClassType, PY2, PY3, range +from utils import isCLRClass, isCLRModule, isCLRRootModule # testImplicitAssemblyLoad() passes on deprecation warning; perfect! # # clr.AddReference('System.Windows.Forms') - class ModuleTests(unittest.TestCase): """Test CLR modules and the CLR import hook.""" - def isCLRModule(self, object): - return type(object).__name__ == 'ModuleObject' - - def isCLRRootModule(self, object): - if PY3: - # in Python 3 the clr module is a normal python module - return object.__name__ == "clr" - elif PY2: - return type(object).__name__ == 'CLRModule' - - def isCLRClass(self, object): - return type(object).__name__ == 'CLR Metatype' # for now - def testAAAImportHookWorks(self): """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 def test000importClr(self): import clr - self.assertTrue(self.isCLRRootModule(clr)) + self.assertTrue(isCLRRootModule(clr)) def testVersionClr(self): import clr @@ -74,13 +60,13 @@ def testModuleInterface(self): self.assertTrue(fnmatch(system_file, "*System*.dll") or fnmatch(system_file, "*mscorlib.dll"), "unexpected System.__file__: " + system_file) self.assertTrue(System.__doc__.startswith("Namespace containing types from the following assemblies:")) - self.assertTrue(self.isCLRClass(System.String)) - self.assertTrue(self.isCLRClass(System.Int32)) + self.assertTrue(isCLRClass(System.String)) + self.assertTrue(isCLRClass(System.Int32)) def testSimpleImport(self): """Test simple import.""" import System - self.assertTrue(self.isCLRModule(System)) + self.assertTrue(isCLRModule(System)) self.assertTrue(System.__name__ == 'System') import sys @@ -99,7 +85,7 @@ def testSimpleImport(self): def testSimpleImportWithAlias(self): """Test simple import with aliasing.""" import System as mySystem - self.assertTrue(self.isCLRModule(mySystem)) + self.assertTrue(isCLRModule(mySystem)) self.assertTrue(mySystem.__name__ == 'System') import sys as mySys @@ -118,7 +104,7 @@ def testSimpleImportWithAlias(self): def testDottedNameImport(self): """Test dotted-name import.""" import System.Reflection - self.assertTrue(self.isCLRModule(System.Reflection)) + self.assertTrue(isCLRModule(System.Reflection)) self.assertTrue(System.Reflection.__name__ == 'System.Reflection') import xml.dom @@ -128,16 +114,16 @@ def testDottedNameImport(self): def testMultipleDottedNameImport(self): """Test an import bug with multiple dotted imports.""" import System.Data - self.assertTrue(self.isCLRModule(System.Data)) + self.assertTrue(isCLRModule(System.Data)) self.assertTrue(System.Data.__name__ == 'System.Data') import System.Data - self.assertTrue(self.isCLRModule(System.Data)) + self.assertTrue(isCLRModule(System.Data)) self.assertTrue(System.Data.__name__ == 'System.Data') def testDottedNameImportWithAlias(self): """Test dotted-name import with aliasing.""" import System.Reflection as SysRef - self.assertTrue(self.isCLRModule(SysRef)) + self.assertTrue(isCLRModule(SysRef)) self.assertTrue(SysRef.__name__ == 'System.Reflection') import xml.dom as myDom @@ -147,7 +133,7 @@ def testDottedNameImportWithAlias(self): def testSimpleImportFrom(self): """Test simple 'import from'.""" from System import Reflection - self.assertTrue(self.isCLRModule(Reflection)) + self.assertTrue(isCLRModule(Reflection)) self.assertTrue(Reflection.__name__ == 'System.Reflection') from xml import dom @@ -157,7 +143,7 @@ def testSimpleImportFrom(self): def testSimpleImportFromWithAlias(self): """Test simple 'import from' with aliasing.""" from System import Collections as Coll - self.assertTrue(self.isCLRModule(Coll)) + self.assertTrue(isCLRModule(Coll)) self.assertTrue(Coll.__name__ == 'System.Collections') from xml import dom as myDom @@ -167,13 +153,13 @@ def testSimpleImportFromWithAlias(self): def testDottedNameImportFrom(self): """Test dotted-name 'import from'.""" from System.Collections import Specialized - self.assertTrue(self.isCLRModule(Specialized)) + self.assertTrue(isCLRModule(Specialized)) self.assertTrue( Specialized.__name__ == 'System.Collections.Specialized' ) from System.Collections.Specialized import StringCollection - self.assertTrue(self.isCLRClass(StringCollection)) + self.assertTrue(isCLRClass(StringCollection)) self.assertTrue(StringCollection.__name__ == 'StringCollection') from xml.dom import pulldom @@ -187,11 +173,11 @@ def testDottedNameImportFrom(self): def testDottedNameImportFromWithAlias(self): """Test dotted-name 'import from' with aliasing.""" from System.Collections import Specialized as Spec - self.assertTrue(self.isCLRModule(Spec)) + self.assertTrue(isCLRModule(Spec)) self.assertTrue(Spec.__name__ == 'System.Collections.Specialized') from System.Collections.Specialized import StringCollection as SC - self.assertTrue(self.isCLRClass(SC)) + self.assertTrue(isCLRClass(SC)) self.assertTrue(SC.__name__ == 'StringCollection') from xml.dom import pulldom as myPulldom @@ -207,7 +193,7 @@ def testFromModuleImportStar(self): count = len(locals().keys()) m = __import__('System.Xml', globals(), locals(), ['*']) self.assertTrue(m.__name__ == 'System.Xml') - self.assertTrue(self.isCLRModule(m)) + self.assertTrue(isCLRModule(m)) self.assertTrue(len(locals().keys()) > count + 1) def testImplicitAssemblyLoad(self): @@ -225,10 +211,10 @@ def testImplicitAssemblyLoad(self): with warnings.catch_warnings(record=True) as w: clr.AddReference("System.Windows.Forms") import System.Windows.Forms as Forms - self.assertTrue(self.isCLRModule(Forms)) + self.assertTrue(isCLRModule(Forms)) self.assertTrue(Forms.__name__ == 'System.Windows.Forms') from System.Windows.Forms import Form - self.assertTrue(self.isCLRClass(Form)) + self.assertTrue(isCLRClass(Form)) self.assertTrue(Form.__name__ == 'Form') self.assertEqual(len(w), 0) @@ -255,7 +241,7 @@ def testImplicitLoadAlreadyValidNamespace(self): # Python runtime to "do the right thing", allowing types from both # assemblies to be found in the System module implicitly. import System - self.assertTrue(self.isCLRClass(System.UriBuilder)) + self.assertTrue(isCLRClass(System.UriBuilder)) def testImportNonExistantModule(self): """Test import failure for a non-existant module.""" @@ -269,7 +255,7 @@ def testLookupNoNamespaceType(self): """Test lookup of types without a qualified namespace.""" import Python.Test import clr - self.assertTrue(self.isCLRClass(clr.NoNamespaceType)) + self.assertTrue(isCLRClass(clr.NoNamespaceType)) def testModuleLookupRecursion(self): """Test for recursive lookup handling.""" @@ -290,10 +276,10 @@ def testModuleGetAttr(self): import System int_type = System.Int32 - self.assertTrue(self.isCLRClass(int_type)) + self.assertTrue(isCLRClass(int_type)) module = System.Xml - self.assertTrue(self.isCLRModule(module)) + self.assertTrue(isCLRModule(module)) def test(): spam = System.Spam diff --git a/src/tests/utils.py b/src/tests/utils.py new file mode 100644 index 000000000..dd4d8767d --- /dev/null +++ b/src/tests/utils.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- + +"""Tests Utilities + +Refactor utility functions and classes +""" + +from _compat import PY2, PY3 + + +def isCLRModule(ob): + return type(ob).__name__ == 'ModuleObject' + + +def isCLRRootModule(ob): + if PY3: + # in Python 3 the clr module is a normal python module + return ob.__name__ == "clr" + elif PY2: + return type(ob).__name__ == 'CLRModule' + + +def isCLRClass(ob): + return type(ob).__name__ == 'CLR Metatype' # for now + + +class ClassicClass: + def kind(self): + return "classic" + + +class NewStyleClass(object): + def kind(self): + return "new-style" + + +class GenericHandler(object): + """A generic handler to test event callbacks.""" + + def __init__(self): + self.value = None + + def handler(self, sender, args): + self.value = args.value + + +class VariableArgsHandler(object): + """A variable args handler to test event callbacks.""" + + def __init__(self): + self.value = None + + def handler(self, *args): + ob, eventargs = args + self.value = eventargs.value + + +class CallableHandler(object): + """A callable handler to test event callbacks.""" + + def __init__(self): + self.value = None + + def __call__(self, sender, args): + self.value = args.value + + +class VarCallableHandler(object): + """A variable args callable handler to test event callbacks.""" + + def __init__(self): + self.value = None + + def __call__(self, *args): + ob, eventargs = args + self.value = eventargs.value + + +class StaticMethodHandler(object): + """A static method handler to test event callbacks.""" + + value = None + + def handler(sender, args): + StaticMethodHandler.value = args.value + + handler = staticmethod(handler) + + +class ClassMethodHandler(object): + """A class method handler to test event callbacks.""" + + value = None + + def handler(cls, sender, args): + cls.value = args.value + + handler = classmethod(handler) + + +class MultipleHandler(object): + """A generic handler to test multiple callbacks.""" + + def __init__(self): + self.value = 0 + + def handler(self, sender, args): + self.value += args.value + + def count(self): + self.value += 1 + return 'ok' + + +class HelloClass(object): + def hello(self): + return "hello" + + def __call__(self): + return "hello" + + @staticmethod + def s_hello(): + return "hello" + + @classmethod + def c_hello(cls): + return "hello" + + +def hello_func(): + return "hello" From 6bb0255fe0033ec90b5d6fe0bbacde220ed5043b Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 21 Jan 2017 23:18:16 -0700 Subject: [PATCH 040/245] Rename tests --- src/tests/leaktest.py | 10 +-- src/tests/test_array.py | 80 ++++++++++---------- src/tests/test_class.py | 36 ++++----- src/tests/test_compat.py | 32 ++++---- src/tests/test_constructors.py | 8 +- src/tests/test_conversion.py | 40 +++++----- src/tests/test_delegate.py | 34 ++++----- src/tests/test_docstring.py | 6 +- src/tests/test_engine.py | 6 +- src/tests/test_enum.py | 30 ++++---- src/tests/test_event.py | 56 +++++++------- src/tests/test_exceptions.py | 46 +++++------ src/tests/test_field.py | 60 +++++++-------- src/tests/test_generic.py | 34 ++++----- src/tests/test_indexer.py | 58 +++++++------- src/tests/test_interface.py | 8 +- src/tests/test_method.py | 80 ++++++++++---------- src/tests/test_module.py | 54 ++++++------- src/tests/test_property.py | 20 ++--- src/tests/test_subclass.py | 10 +-- src/tests/test_suite/test_callback.py | 4 +- src/tests/test_suite/test_import.py | 2 +- src/tests/test_suite/test_recursive_types.py | 2 +- src/tests/test_thread.py | 6 +- 24 files changed, 361 insertions(+), 361 deletions(-) diff --git a/src/tests/leaktest.py b/src/tests/leaktest.py index 666e6e276..a54774566 100644 --- a/src/tests/leaktest.py +++ b/src/tests/leaktest.py @@ -63,7 +63,7 @@ def report(self): if type(item) != dicttype: print(item, sys.getrefcount(item)) - def testModules(self): + def test_modules(self): self.notify("Running module leak check...") for i in range(self.count): @@ -78,7 +78,7 @@ def testModules(self): self.end_test() - def testClasses(self): + def test_classes(self): from System.Collections import Hashtable from Python.Test import StringDelegate @@ -102,7 +102,7 @@ def testClasses(self): self.end_test() - def testEnumerations(self): + def test_enumerations(self): import Python.Test as Test self.notify("Running enum leak check...") @@ -137,7 +137,7 @@ def testEnumerations(self): self.end_test() - def testEvents(self): + def test_events(self): from Python.Test import EventTest, TestEventArgs self.notify("Running event leak check...") @@ -215,7 +215,7 @@ def handler(sender, args, dict=dict): self.end_test() - def testDelegates(self): + def test_delegates(self): from Python.Test import DelegateTest, StringDelegate self.notify("Running delegate leak check...") diff --git a/src/tests/test_array.py b/src/tests/test_array.py index 134b95557..b12c785e7 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -11,7 +11,7 @@ class ArrayTests(unittest.TestCase): """Test support for managed arrays.""" - def testPublicArray(self): + def test_public_array(self): """Test public arrays.""" ob = Test.PublicArrayTest() items = ob.items @@ -33,7 +33,7 @@ def testPublicArray(self): items[-1] = 4 self.assertTrue(items[-1] == 4) - def testProtectedArray(self): + def test_protected_array(self): """Test protected arrays.""" ob = Test.ProtectedArrayTest() items = ob.items @@ -55,7 +55,7 @@ def testProtectedArray(self): items[-1] = 4 self.assertTrue(items[-1] == 4) - def testInternalArray(self): + def test_internal_array(self): """Test internal arrays.""" def test(): @@ -64,7 +64,7 @@ def test(): self.assertRaises(AttributeError, test) - def testPrivateArray(self): + def test_private_array(self): """Test private arrays.""" def test(): @@ -73,7 +73,7 @@ def test(): self.assertRaises(AttributeError, test) - def testArrayBoundsChecking(self): + def test_array_bounds_checking(self): """Test array bounds checking.""" ob = Test.Int32ArrayTest() @@ -115,7 +115,7 @@ def test(): self.assertRaises(IndexError, test) - def testArrayContains(self): + def test_array_contains(self): """Test array support for __contains__.""" ob = Test.Int32ArrayTest() @@ -132,7 +132,7 @@ def testArrayContains(self): self.assertFalse(None in items) # which threw ^ here which is a little odd. # But when run from runtests.py. Not when this module ran by itself. - def testBooleanArray(self): + def test_boolean_array(self): """Test boolean arrays.""" ob = Test.BooleanArrayTest() items = ob.items @@ -163,7 +163,7 @@ def test(): self.assertRaises(TypeError, test) - def testByteArray(self): + def test_byte_array(self): """Test byte arrays.""" ob = Test.ByteArrayTest() items = ob.items @@ -212,7 +212,7 @@ def test(): self.assertRaises(TypeError, test) - def testSByteArray(self): + def test_sbyte_array(self): """Test sbyte arrays.""" ob = Test.SByteArrayTest() items = ob.items @@ -261,7 +261,7 @@ def test(): self.assertRaises(TypeError, test) - def testCharArray(self): + def test_char_array(self): """Test char arrays.""" ob = Test.CharArrayTest() items = ob.items @@ -298,7 +298,7 @@ def test(): self.assertRaises(TypeError, test) - def testInt16Array(self): + def test_int16_array(self): """Test Int16 arrays.""" ob = Test.Int16ArrayTest() items = ob.items @@ -347,7 +347,7 @@ def test(): self.assertRaises(TypeError, test) - def testInt32Array(self): + def test_int32_array(self): """Test Int32 arrays.""" ob = Test.Int32ArrayTest() items = ob.items @@ -396,7 +396,7 @@ def test(): self.assertRaises(TypeError, test) - def testInt64Array(self): + def test_int64_array(self): """Test Int64 arrays.""" ob = Test.Int64ArrayTest() items = ob.items @@ -445,7 +445,7 @@ def test(): self.assertRaises(TypeError, test) - def testUInt16Array(self): + def test_uint16_array(self): """Test UInt16 arrays.""" ob = Test.UInt16ArrayTest() items = ob.items @@ -494,7 +494,7 @@ def test(): self.assertRaises(TypeError, test) - def testUInt32Array(self): + def test_uint32_array(self): """Test UInt32 arrays.""" ob = Test.UInt32ArrayTest() items = ob.items @@ -543,7 +543,7 @@ def test(): self.assertRaises(TypeError, test) - def testUInt64Array(self): + def test_uint64_array(self): """Test UInt64 arrays.""" ob = Test.UInt64ArrayTest() items = ob.items @@ -592,7 +592,7 @@ def test(): self.assertRaises(TypeError, test) - def testSingleArray(self): + def test_single_array(self): """Test Single arrays.""" ob = Test.SingleArrayTest() items = ob.items @@ -629,7 +629,7 @@ def test(): self.assertRaises(TypeError, test) - def testDoubleArray(self): + def test_double_array(self): """Test Double arrays.""" ob = Test.DoubleArrayTest() items = ob.items @@ -666,7 +666,7 @@ def test(): self.assertRaises(TypeError, test) - def testDecimalArray(self): + def test_decimal_array(self): """Test Decimal arrays.""" ob = Test.DecimalArrayTest() items = ob.items @@ -704,7 +704,7 @@ def test(): self.assertRaises(TypeError, test) - def testStringArray(self): + def test_string_array(self): """Test String arrays.""" ob = Test.StringArrayTest() items = ob.items @@ -738,7 +738,7 @@ def test(): self.assertRaises(TypeError, test) - def testEnumArray(self): + def test_enum_array(self): """Test enum arrays.""" from Python.Test import ShortEnum ob = Test.EnumArrayTest() @@ -779,7 +779,7 @@ def test(): self.assertRaises(TypeError, test) - def testObjectArray(self): + def test_object_array(self): """Test ob arrays.""" from Python.Test import Spam ob = Test.ObjectArrayTest() @@ -820,7 +820,7 @@ def test(): self.assertRaises(TypeError, test) - def testNullArray(self): + def test_null_array(self): """Test null arrays.""" ob = Test.NullArrayTest() items = ob.items @@ -851,7 +851,7 @@ def test(): self.assertRaises(TypeError, test) - def testInterfaceArray(self): + def test_interface_array(self): """Test interface arrays.""" from Python.Test import Spam ob = Test.InterfaceArrayTest() @@ -895,7 +895,7 @@ def test(): self.assertRaises(TypeError, test) - def testTypedArray(self): + def test_typed_array(self): """Test typed arrays.""" from Python.Test import Spam ob = Test.TypedArrayTest() @@ -939,7 +939,7 @@ def test(): self.assertRaises(TypeError, test) - def testMultiDimensionalArray(self): + def test_multi_dimensional_array(self): """Test multi-dimensional arrays.""" ob = Test.MultiDimensionalArrayTest() items = ob.items @@ -1011,7 +1011,7 @@ def test(): self.assertRaises(TypeError, test) - def testArrayIteration(self): + def test_array_iteration(self): """Test array iteration.""" items = Test.Int32ArrayTest().items @@ -1028,7 +1028,7 @@ def testArrayIteration(self): for i in empty: raise TypeError('iteration over empty array') - def testTupleArrayConversion(self): + def test_tuple_array_conversion(self): """Test conversion of tuples to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1042,7 +1042,7 @@ def testTupleArrayConversion(self): self.assertTrue(result[0].__class__ == Spam) self.assertTrue(len(result) == 10) - def testTupleNestedArrayConversion(self): + def test_tuple_nested_array_conversion(self): """Test conversion of tuples to array-of-array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1061,7 +1061,7 @@ def testTupleNestedArrayConversion(self): self.assertTrue(len(result[0]) == 10) self.assertTrue(result[0][0].__class__ == Spam) - def testListArrayConversion(self): + def test_list_array_conversion(self): """Test conversion of lists to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1074,7 +1074,7 @@ def testListArrayConversion(self): self.assertTrue(result[0].__class__ == Spam) self.assertTrue(len(result) == 10) - def testListNestedArrayConversion(self): + def test_list_nested_array_conversion(self): """Test conversion of lists to array-of-array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1092,7 +1092,7 @@ def testListNestedArrayConversion(self): self.assertTrue(len(result[0]) == 10) self.assertTrue(result[0][0].__class__ == Spam) - def testSequenceArrayConversion(self): + def test_sequence_array_conversion(self): """Test conversion of sequence-like obs to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1105,7 +1105,7 @@ def testSequenceArrayConversion(self): self.assertTrue(result[0].__class__ == Spam) self.assertTrue(len(result) == 10) - def testSequenceNestedArrayConversion(self): + def test_sequence_nested_array_conversion(self): """Test conversion of sequences to array-of-array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1123,7 +1123,7 @@ def testSequenceNestedArrayConversion(self): self.assertTrue(len(result[0]) == 10) self.assertTrue(result[0][0].__class__ == Spam) - def testTupleArrayConversionTypeChecking(self): + def test_tuple_array_conversion_type_checking(self): """Test error handling for tuple conversion to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1159,7 +1159,7 @@ def test(items=items): self.assertRaises(TypeError, test) - def testListArrayConversionTypeChecking(self): + def test_list_array_conversion_type_checking(self): """Test error handling for list conversion to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1190,7 +1190,7 @@ def test(items=items): self.assertRaises(TypeError, test) - def testSequenceArrayConversionTypeChecking(self): + def test_sequence_array_conversion_type_checking(self): """Test error handling for sequence conversion to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1221,7 +1221,7 @@ def test(items=items): self.assertRaises(TypeError, test) - def testMDArrayConversion(self): + def test_md_array_conversion(self): """Test passing of multi-dimensional array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam @@ -1245,7 +1245,7 @@ def testMDArrayConversion(self): self.assertTrue(result[0, 0].__class__ == Spam) self.assertTrue(result[0, 0].__class__ == Spam) - def testBoxedValueTypeMutationResult(self): + def test_boxed_value_type_mutation_result(self): """Test behavior of boxed value types.""" # This test actually exists mostly as documentation of an important @@ -1282,7 +1282,7 @@ def testBoxedValueTypeMutationResult(self): self.assertTrue(items[i].X == i + 1) self.assertTrue(items[i].Y == i + 1) - def testSpecialArrayCreation(self): + def test_special_array_creation(self): """Test using the Array[] syntax for creating arrays.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from System import Array @@ -1416,7 +1416,7 @@ def testSpecialArrayCreation(self): self.assertTrue(value[1].__class__ == inst.__class__) self.assertTrue(value.Length == 2) - def testArrayAbuse(self): + def test_array_abuse(self): """Test array abuse.""" _class = Test.PublicArrayTest ob = Test.PublicArrayTest() diff --git a/src/tests/test_class.py b/src/tests/test_class.py index b681c3a11..02d5f1efc 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -21,17 +21,17 @@ def kind(self): class ClassTests(unittest.TestCase): """Test CLR class support.""" - def testBasicReferenceType(self): + def test_basic_reference_type(self): """Test usage of CLR defined reference types.""" String = System.String self.assertEquals(String.Empty, "") - def testBasicValueType(self): + def test_basic_value_type(self): """Test usage of CLR defined value types.""" Int32 = System.Int32 self.assertEquals(Int32.MaxValue, 2147483647) - def testClassStandardAttrs(self): + def test_class_standard_attrs(self): """Test standard class attributes.""" from Python.Test import ClassTest @@ -40,24 +40,24 @@ def testClassStandardAttrs(self): self.assertTrue(type(ClassTest.__dict__) == DictProxyType) self.assertTrue(len(ClassTest.__doc__) > 0) - def testClassDocstrings(self): + def test_class_docstrings(self): """Test standard class docstring generation""" from Python.Test import ClassTest value = 'Void .ctor()' self.assertTrue(ClassTest.__doc__ == value) - def testClassDefaultStr(self): + def test_class_default_str(self): """Test the default __str__ implementation for managed objects.""" s = System.String("this is a test") self.assertTrue(str(s) == "this is a test") - def testClassDefaultRepr(self): + def test_class_default_repr(self): """Test the default __repr__ implementation for managed objects.""" s = System.String("this is a test") self.assertTrue(repr(s).startswith(" Python type conversions.""" - def testBoolConversion(self): + def test_bool_conversion(self): """Test bool conversion.""" ob = ConversionTest() self.assertTrue(ob.BooleanField == False) @@ -63,7 +63,7 @@ def testBoolConversion(self): self.assertTrue(ob.BooleanField is True) self.assertTrue(ob.BooleanField == 1) - def testSByteConversion(self): + def test_sbyte_conversion(self): """Test sbyte conversion.""" self.assertTrue(System.SByte.MaxValue == 127) self.assertTrue(System.SByte.MinValue == -128) @@ -113,7 +113,7 @@ def test(): self.assertRaises(OverflowError, test) - def testByteConversion(self): + def test_byte_conversion(self): """Test byte conversion.""" self.assertTrue(System.Byte.MaxValue == 255) self.assertTrue(System.Byte.MinValue == 0) @@ -163,7 +163,7 @@ def test(): self.assertRaises(OverflowError, test) - def testCharConversion(self): + def test_char_conversion(self): """Test char conversion.""" self.assertTrue(System.Char.MaxValue == unichr(65535)) self.assertTrue(System.Char.MinValue == unichr(0)) @@ -195,7 +195,7 @@ def test(): self.assertRaises(TypeError, test) - def testInt16Conversion(self): + def test_int16_conversion(self): """Test int16 conversion.""" self.assertTrue(System.Int16.MaxValue == 32767) self.assertTrue(System.Int16.MinValue == -32768) @@ -245,7 +245,7 @@ def test(): self.assertRaises(OverflowError, test) - def testInt32Conversion(self): + def test_int32_conversion(self): """Test int32 conversion.""" self.assertTrue(System.Int32.MaxValue == 2147483647) self.assertTrue(System.Int32.MinValue == -2147483648) @@ -295,7 +295,7 @@ def test(): self.assertRaises(OverflowError, test) - def testInt64Conversion(self): + def test_int64_conversion(self): """Test int64 conversion.""" self.assertTrue(System.Int64.MaxValue == long(9223372036854775807)) self.assertTrue(System.Int64.MinValue == long(-9223372036854775808)) @@ -345,7 +345,7 @@ def test(): self.assertRaises(OverflowError, test) - def testUInt16Conversion(self): + def test_uint16_conversion(self): """Test uint16 conversion.""" self.assertTrue(System.UInt16.MaxValue == 65535) self.assertTrue(System.UInt16.MinValue == 0) @@ -395,7 +395,7 @@ def test(): self.assertRaises(OverflowError, test) - def testUInt32Conversion(self): + def test_uint32_conversion(self): """Test uint32 conversion.""" self.assertTrue(System.UInt32.MaxValue == long(4294967295)) self.assertTrue(System.UInt32.MinValue == 0) @@ -445,7 +445,7 @@ def test(): self.assertRaises(OverflowError, test) - def testUInt64Conversion(self): + def test_uint64_conversion(self): """Test uint64 conversion.""" self.assertTrue(System.UInt64.MaxValue == long(18446744073709551615)) self.assertTrue(System.UInt64.MinValue == 0) @@ -495,7 +495,7 @@ def test(): self.assertRaises(OverflowError, test) - def testSingleConversion(self): + def test_single_conversion(self): """Test single conversion.""" self.assertTrue(System.Single.MaxValue == 3.402823e38) self.assertTrue(System.Single.MinValue == -3.402823e38) @@ -545,7 +545,7 @@ def test(): self.assertRaises(OverflowError, test) - def testDoubleConversion(self): + def test_double_conversion(self): """Test double conversion.""" self.assertTrue(System.Double.MaxValue == 1.7976931348623157e308) self.assertTrue(System.Double.MinValue == -1.7976931348623157e308) @@ -595,7 +595,7 @@ def test(): self.assertRaises(OverflowError, test) - def testDecimalConversion(self): + def test_decimal_conversion(self): """Test decimal conversion.""" from System import Decimal @@ -637,7 +637,7 @@ def test(): self.assertRaises(TypeError, test) - def testStringConversion(self): + def test_string_conversion(self): """Test string / unicode conversion.""" ob = ConversionTest() @@ -670,7 +670,7 @@ def test(): self.assertRaises(TypeError, test) - def testInterfaceConversion(self): + def test_interface_conversion(self): """Test interface conversion.""" from Python.Test import Spam, ISpam @@ -700,7 +700,7 @@ def test(): self.assertRaises(TypeError, test) - def testObjectConversion(self): + def test_object_conversion(self): """Test ob conversion.""" from Python.Test import Spam @@ -728,7 +728,7 @@ def test(): self.assertRaises(TypeError, test) - def testEnumConversion(self): + def test_enum_conversion(self): """Test enum conversion.""" from Python.Test import ShortEnum @@ -770,7 +770,7 @@ def test(): self.assertRaises(TypeError, test) - def testNullConversion(self): + def test_null_conversion(self): """Test null conversion.""" ob = ConversionTest() @@ -795,7 +795,7 @@ def test(): self.assertRaises(TypeError, test) - def testByteArrayConversion(self): + def test_byte_array_conversion(self): """Test byte array conversion.""" ob = ConversionTest() @@ -813,7 +813,7 @@ def testByteArrayConversion(self): for i in range(len(value)): self.assertTrue(array[i] == indexbytes(value, i)) - def testSByteArrayConversion(self): + def test_sbyte_array_conversion(self): """Test sbyte array conversion.""" ob = ConversionTest() diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index 33940caca..37203e77d 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -14,7 +14,7 @@ class DelegateTests(unittest.TestCase): """Test CLR delegate support.""" - def testDelegateStandardAttrs(self): + def test_delegate_standard_attrs(self): """Test standard delegate attributes.""" from Python.Test import PublicDelegate @@ -23,7 +23,7 @@ def testDelegateStandardAttrs(self): self.assertTrue(type(PublicDelegate.__dict__) == DictProxyType) self.assertTrue(PublicDelegate.__doc__ == None) - def testGlobalDelegateVisibility(self): + def test_global_delegate_visibility(self): """Test visibility of module-level delegates.""" from Python.Test import PublicDelegate @@ -40,7 +40,7 @@ def test(): self.assertRaises(AttributeError, test) - def testNestedDelegateVisibility(self): + def test_nested_delegate_visibility(self): """Test visibility of nested delegates.""" ob = DelegateTest.PublicDelegate self.assertTrue(ob.__name__ == 'PublicDelegate') @@ -58,7 +58,7 @@ def test(): self.assertRaises(AttributeError, test) - def testDelegateFromFunction(self): + def test_delegate_from_function(self): """Test delegate implemented with a Python function.""" d = StringDelegate(hello_func) @@ -71,7 +71,7 @@ def testDelegateFromFunction(self): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - def testDelegateFromMethod(self): + def test_delegate_from_method(self): """Test delegate implemented with a Python instance method.""" inst = HelloClass() @@ -85,7 +85,7 @@ def testDelegateFromMethod(self): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - def testDelegateFromUnboundMethod(self): + def test_delegate_from_unbound_method(self): """Test failure mode for unbound methods.""" def test(): @@ -94,7 +94,7 @@ def test(): self.assertRaises(TypeError, test) - def testDelegateFromStaticMethod(self): + def test_delegate_from_static_method(self): """Test delegate implemented with a Python static method.""" d = StringDelegate(HelloClass.s_hello) @@ -118,7 +118,7 @@ def testDelegateFromStaticMethod(self): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - def testDelegateFromClassMethod(self): + def test_delegate_from_class_method(self): """Test delegate implemented with a Python class method.""" d = StringDelegate(HelloClass.c_hello) @@ -142,7 +142,7 @@ def testDelegateFromClassMethod(self): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - def testDelegateFromCallable(self): + def test_delegate_from_callable(self): """Test delegate implemented with a Python callable object.""" inst = HelloClass() @@ -156,7 +156,7 @@ def testDelegateFromCallable(self): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - def testDelegateFromManagedInstanceMethod(self): + def test_delegate_from_managed_instance_method(self): """Test delegate implemented with a managed instance method.""" ob = DelegateTest() d = StringDelegate(ob.SayHello) @@ -168,7 +168,7 @@ def testDelegateFromManagedInstanceMethod(self): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - def testDelegateFromManagedStaticMethod(self): + def test_delegate_from_managed_static_method(self): """Test delegate implemented with a managed static method.""" d = StringDelegate(DelegateTest.StaticSayHello) ob = DelegateTest() @@ -180,7 +180,7 @@ def testDelegateFromManagedStaticMethod(self): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - def testDelegateFromDelegate(self): + def test_delegate_from_delegate(self): """Test delegate implemented with another delegate.""" d1 = StringDelegate(hello_func) d2 = StringDelegate(d1) @@ -193,7 +193,7 @@ def testDelegateFromDelegate(self): self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.assertTrue(ob.stringDelegate() == "hello") - def testDelegateWithInvalidArgs(self): + def test_delegate_with_invalid_args(self): """Test delegate instantiation with invalid (non-callable) args.""" def test(): @@ -211,7 +211,7 @@ def test(): self.assertRaises(TypeError, test) - def testMulticastDelegate(self): + def test_multicast_delegate(self): """Test multicast delegates.""" inst = MultipleHandler() @@ -227,7 +227,7 @@ def testMulticastDelegate(self): self.assertTrue(md() == "ok") self.assertTrue(inst.value == 4) - def testSubclassDelegateFails(self): + def test_subclass_delegate_fails(self): """Test that subclassing of a delegate type fails.""" from Python.Test import PublicDelegate @@ -237,7 +237,7 @@ class Boom(PublicDelegate): self.assertRaises(TypeError, test) - def testDelegateEquality(self): + def test_delegate_equality(self): """Test delegate equality.""" def sayhello(): @@ -248,7 +248,7 @@ def sayhello(): ob.stringDelegate = d self.assertTrue(ob.stringDelegate == d) - def testBoolDelegate(self): + def test_bool_delegate(self): """Test boolean delegate.""" from Python.Test import BoolDelegate diff --git a/src/tests/test_docstring.py b/src/tests/test_docstring.py index afbd1062f..f2bc3302b 100644 --- a/src/tests/test_docstring.py +++ b/src/tests/test_docstring.py @@ -6,21 +6,21 @@ class DocStringTests(unittest.TestCase): """Test doc strings support.""" - def testDocWithCtor(self): + def test_doc_with_ctor(self): from Python.Test import DocWithCtorTest self.assertEqual(DocWithCtorTest.__doc__, 'DocWithCtorTest Class') self.assertEqual(DocWithCtorTest.TestMethod.__doc__, 'DocWithCtorTest TestMethod') self.assertEqual(DocWithCtorTest.StaticTestMethod.__doc__, 'DocWithCtorTest StaticTestMethod') - def testDocWithCtorNoDoc(self): + def test_doc_with_ctor_no_doc(self): from Python.Test import DocWithCtorNoDocTest self.assertEqual(DocWithCtorNoDocTest.__doc__, 'Void .ctor(Boolean)') self.assertEqual(DocWithCtorNoDocTest.TestMethod.__doc__, 'Void TestMethod(Double, Int32)') self.assertEqual(DocWithCtorNoDocTest.StaticTestMethod.__doc__, 'Void StaticTestMethod(Double, Int32)') - def testDocWithoutCtor(self): + def test_doc_without_ctor(self): from Python.Test import DocWithoutCtorTest self.assertEqual(DocWithoutCtorTest.__doc__, 'DocWithoutCtorTest Class') diff --git a/src/tests/test_engine.py b/src/tests/test_engine.py index 274dfb704..cfc019b5f 100644 --- a/src/tests/test_engine.py +++ b/src/tests/test_engine.py @@ -11,19 +11,19 @@ class EngineTests(unittest.TestCase): """Test PythonEngine embedding APIs.""" - def testMultipleCallsToInitialize(self): + def test_multiple_calls_to_initialize(self): """Test that multiple initialize calls are harmless.""" PythonEngine.Initialize() PythonEngine.Initialize() PythonEngine.Initialize() - def testImportModule(self): + def test_import_module(self): """Test module import.""" m = PythonEngine.ImportModule("sys") n = m.GetAttr("__name__") self.assertTrue(n.AsManagedObject(System.String) == "sys") - def testRunString(self): + def test_run_string(self): """Test the RunString method.""" PythonEngine.AcquireLock() diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index 493395d27..6f6097029 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -10,7 +10,7 @@ class EnumTests(unittest.TestCase): """Test CLR enum support.""" - def testEnumStandardAttrs(self): + def test_enum_standard_attrs(self): """Test standard enum attributes.""" from System import DayOfWeek @@ -19,7 +19,7 @@ def testEnumStandardAttrs(self): self.assertTrue(type(DayOfWeek.__dict__) == DictProxyType) self.assertTrue(DayOfWeek.__doc__ == None) - def testEnumGetMember(self): + def test_enum_get_member(self): """Test access to enum members.""" from System import DayOfWeek @@ -31,55 +31,55 @@ def testEnumGetMember(self): self.assertTrue(DayOfWeek.Friday == 5) self.assertTrue(DayOfWeek.Saturday == 6) - def testByteEnum(self): + def test_byte_enum(self): """Test byte enum.""" self.assertTrue(Test.ByteEnum.Zero == 0) self.assertTrue(Test.ByteEnum.One == 1) self.assertTrue(Test.ByteEnum.Two == 2) - def testSByteEnum(self): + def test_sbyte_enum(self): """Test sbyte enum.""" self.assertTrue(Test.SByteEnum.Zero == 0) self.assertTrue(Test.SByteEnum.One == 1) self.assertTrue(Test.SByteEnum.Two == 2) - def testShortEnum(self): + def test_short_enum(self): """Test short enum.""" self.assertTrue(Test.ShortEnum.Zero == 0) self.assertTrue(Test.ShortEnum.One == 1) self.assertTrue(Test.ShortEnum.Two == 2) - def testUShortEnum(self): + def test_ushort_enum(self): """Test ushort enum.""" self.assertTrue(Test.UShortEnum.Zero == 0) self.assertTrue(Test.UShortEnum.One == 1) self.assertTrue(Test.UShortEnum.Two == 2) - def testIntEnum(self): + def test_int_enum(self): """Test int enum.""" self.assertTrue(Test.IntEnum.Zero == 0) self.assertTrue(Test.IntEnum.One == 1) self.assertTrue(Test.IntEnum.Two == 2) - def testUIntEnum(self): + def test_uint_enum(self): """Test uint enum.""" self.assertTrue(Test.UIntEnum.Zero == long(0)) self.assertTrue(Test.UIntEnum.One == long(1)) self.assertTrue(Test.UIntEnum.Two == long(2)) - def testLongEnum(self): + def test_long_enum(self): """Test long enum.""" self.assertTrue(Test.LongEnum.Zero == long(0)) self.assertTrue(Test.LongEnum.One == long(1)) self.assertTrue(Test.LongEnum.Two == long(2)) - def testULongEnum(self): + def test_ulong_enum(self): """Test ulong enum.""" self.assertTrue(Test.ULongEnum.Zero == long(0)) self.assertTrue(Test.ULongEnum.One == long(1)) self.assertTrue(Test.ULongEnum.Two == long(2)) - def testInstantiateEnumFails(self): + def test_instantiate_enum_fails(self): """Test that instantiation of an enum class fails.""" from System import DayOfWeek @@ -88,7 +88,7 @@ def test(): self.assertRaises(TypeError, test) - def testSubclassEnumFails(self): + def test_subclass_enum_fails(self): """Test that subclassing of an enumeration fails.""" from System import DayOfWeek @@ -98,7 +98,7 @@ class Boom(DayOfWeek): self.assertRaises(TypeError, test) - def testEnumSetMemberFails(self): + def test_enum_set_member_fails(self): """Test that setattr operations on enumerations fail.""" from System import DayOfWeek @@ -112,7 +112,7 @@ def test(): self.assertRaises(TypeError, test) - def testEnumWithFlagsAttrConversion(self): + def test_enum_with_flags_attr_conversion(self): """Test enumeration conversion with FlagsAttribute set.""" # This works because the FlagsField enum has FlagsAttribute. Test.FieldTest().FlagsField = 99 @@ -123,7 +123,7 @@ def test(): self.assertRaises(ValueError, test) - def testEnumConversion(self): + def test_enum_conversion(self): """Test enumeration conversion.""" ob = Test.FieldTest() self.assertTrue(ob.EnumField == 0) diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 858069f6c..84a495430 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -13,7 +13,7 @@ class EventTests(unittest.TestCase): """Test CLR event support.""" - def testPublicInstanceEvent(self): + def test_public_instance_event(self): """Test public instance events.""" ob = EventTest() @@ -27,7 +27,7 @@ def testPublicInstanceEvent(self): ob.PublicEvent -= handler.handler - def testPublicStaticEvent(self): + def test_public_static_event(self): """Test public static events.""" handler = GenericHandler() self.assertTrue(handler.value == None) @@ -37,7 +37,7 @@ def testPublicStaticEvent(self): EventTest.OnPublicStaticEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) - def testProtectedInstanceEvent(self): + def test_protected_instance_event(self): """Test protected instance events.""" ob = EventTest() @@ -51,7 +51,7 @@ def testProtectedInstanceEvent(self): ob.ProtectedEvent -= handler.handler - def testProtectedStaticEvent(self): + def test_protected_static_event(self): """Test protected static events.""" ob = EventTest @@ -65,7 +65,7 @@ def testProtectedStaticEvent(self): EventTest.ProtectedStaticEvent -= handler.handler - def testInternalEvents(self): + def test_internal_events(self): """Test internal events.""" def test(): @@ -83,7 +83,7 @@ def test(): self.assertRaises(AttributeError, test) - def testPrivateEvents(self): + def test_private_events(self): """Test private events.""" def test(): @@ -101,7 +101,7 @@ def test(): self.assertRaises(AttributeError, test) - def testMulticastEvent(self): + def test_multicast_event(self): """Test multicast events.""" ob = EventTest() @@ -129,7 +129,7 @@ def testMulticastEvent(self): ob.PublicEvent -= handler2.handler ob.PublicEvent -= handler3.handler - def testInstanceMethodHandler(self): + def test_instance_method_handler(self): """Test instance method handlers.""" ob = EventTest() handler = GenericHandler() @@ -146,7 +146,7 @@ def testInstanceMethodHandler(self): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) - def testVarArgsInstanceMethodHandler(self): + def test_var_args_instance_method_handler(self): """Test vararg instance method handlers.""" ob = EventTest() handler = VariableArgsHandler() @@ -163,7 +163,7 @@ def testVarArgsInstanceMethodHandler(self): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) - def testCallableobHandler(self): + def test_callableob_handler(self): """Test callable ob handlers.""" ob = EventTest() handler = CallableHandler() @@ -180,7 +180,7 @@ def testCallableobHandler(self): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) - def testVarArgsCallableHandler(self): + def test_var_args_callable_handler(self): """Test varargs callable handlers.""" ob = EventTest() handler = VarCallableHandler() @@ -197,7 +197,7 @@ def testVarArgsCallableHandler(self): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) - def testStaticMethodHandler(self): + def test_static_method_handler(self): """Test static method handlers.""" ob = EventTest() handler = StaticMethodHandler() @@ -215,7 +215,7 @@ def testStaticMethodHandler(self): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) - def testClassMethodHandler(self): + def test_class_method_handler(self): """Test class method handlers.""" ob = EventTest() handler = ClassMethodHandler() @@ -233,7 +233,7 @@ def testClassMethodHandler(self): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) - def testManagedInstanceMethodHandler(self): + def test_managed_instance_method_handler(self): """Test managed instance method handlers.""" ob = EventTest() @@ -249,7 +249,7 @@ def testManagedInstanceMethodHandler(self): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(ob.value == 10) - def testManagedStaticMethodHandler(self): + def test_managed_static_method_handler(self): """Test managed static method handlers.""" ob = EventTest() EventTest.s_value = 0 @@ -266,7 +266,7 @@ def testManagedStaticMethodHandler(self): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(EventTest.s_value == 10) - def testUnboundMethodHandler(self): + def test_unbound_method_handler(self): """Test failure mode for unbound method handlers.""" ob = EventTest() ob.PublicEvent += GenericHandler.handler @@ -278,7 +278,7 @@ def testUnboundMethodHandler(self): raise TypeError("should have raised a TypeError") - def testFunctionHandler(self): + def test_function_handler(self): """Test function handlers.""" ob = EventTest() dict = {'value': None} @@ -298,7 +298,7 @@ def handler(sender, args, dict=dict): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(dict['value'] == 10) - def testAddNonCallableHandler(self): + def test_add_non_callable_handler(self): """Test handling of attempts to add non-callable handlers.""" def test(): @@ -322,7 +322,7 @@ class spam(object): self.assertRaises(TypeError, test) - def testRemoveMultipleHandlers(self): + def test_remove_multiple_handlers(self): """Test removing multiple instances of the same handler.""" ob = EventTest() handler = MultipleHandler() @@ -370,7 +370,7 @@ def testRemoveMultipleHandlers(self): ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) - def testRemoveMultipleStaticHandlers(self): + def test_remove_multiple_static_handlers(self): """Test removing multiple instances of a static handler.""" ob = EventTest() handler = MultipleHandler() @@ -418,7 +418,7 @@ def testRemoveMultipleStaticHandlers(self): ob.OnPublicStaticEvent(TestEventArgs(10)) self.assertTrue(handler.value == 30) - def testRandomMultipleHandlers(self): + def test_random_multiple_handlers(self): """Test random subscribe / unsubscribe of the same handlers.""" import random ob = EventTest() @@ -465,7 +465,7 @@ def testRandomMultipleHandlers(self): ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler2.value == 0) - def testRemoveInternalCallHandler(self): + def test_remove_internal_call_handler(self): """Test remove on an event sink implemented w/internalcall.""" ob = EventTest() @@ -475,7 +475,7 @@ def h(sender, args): ob.PublicEvent += h ob.PublicEvent -= h - def testRemoveUnknownHandler(self): + def test_remove_unknown_handler(self): """Test removing an event handler that was never added.""" def test(): @@ -486,7 +486,7 @@ def test(): self.assertRaises(ValueError, test) - def testHandlerCallbackFailure(self): + def test_handler_callback_failure(self): """Test failure mode for inappropriate handlers.""" class BadHandler(object): @@ -519,7 +519,7 @@ def test(): ob.PublicEvent -= handler.handler - def testIncorrectInvokation(self): + def test_incorrect_invokation(self): """Test incorrect invocation of events.""" ob = EventTest() @@ -538,7 +538,7 @@ def test(): ob.PublicEvent -= handler.handler - def testExplicitCLSEventRegistration(self): + def test_explicit_cls_event_registration(self): """Test explicit CLS event registration.""" from Python.Test import TestEventHandler @@ -558,7 +558,7 @@ def testExplicitCLSEventRegistration(self): ob.OnPublicEvent(TestEventArgs(20)) self.assertTrue(handler.value == 10) - def testImplicitCLSEventRegistration(self): + def test_implicit_cls_event_registration(self): """Test implicit CLS event registration.""" def test(): @@ -568,7 +568,7 @@ def test(): self.assertRaises(TypeError, test) - def testEventDescriptorAbuse(self): + def test_event_descriptor_abuse(self): """Test event descriptor abuse.""" def test(): diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index 647106a70..ffd9445eb 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -11,13 +11,13 @@ class ExceptionTests(unittest.TestCase): """Test exception support.""" - def testUnifiedExceptionSemantics(self): + def test_unified_exception_semantics(self): """Test unified exception semantics.""" e = System.Exception('Something bad happened') self.assertTrue(isinstance(e, Exception)) self.assertTrue(isinstance(e, System.Exception)) - def testStandardExceptionAttributes(self): + def test_standard_exception_attributes(self): """Test accessing standard exception attributes.""" from System import OverflowException from Python.Test import ExceptionTest @@ -33,7 +33,7 @@ def testStandardExceptionAttributes(self): v = e.ToString() self.assertTrue(len(v) > 0) - def testExtendedExceptionAttributes(self): + def test_extended_exception_attributes(self): """Test accessing extended exception attributes.""" from Python.Test import ExceptionTest, ExtendedException from System import OverflowException @@ -57,7 +57,7 @@ def testExtendedExceptionAttributes(self): self.assertTrue(e.GetExtraInfo() == 'changed') - def testRaiseClassException(self): + def test_raise_class_exception(self): """Test class exception propagation.""" from System import NullReferenceException @@ -73,7 +73,7 @@ def test(): self.assertTrue(type is NullReferenceException) self.assertTrue(isinstance(value, NullReferenceException)) - def testRaiseClassExceptionWithValue(self): + def test_raise_class_exception_with_value(self): """Test class exception propagation with associated value.""" from System import NullReferenceException @@ -90,7 +90,7 @@ def test(): self.assertTrue(isinstance(value, NullReferenceException)) self.assertTrue(value.Message == 'Aiiieee!') - def testRaiseInstanceException(self): + def test_raise_instance_exception(self): """Test instance exception propagation.""" from System import NullReferenceException @@ -107,7 +107,7 @@ def test(): self.assertTrue(isinstance(value, NullReferenceException)) self.assertTrue(len(value.Message) > 0) - def testRaiseInstanceExceptionWithArgs(self): + def test_raise_instance_exception_with_args(self): """Test instance exception propagation with args.""" from System import NullReferenceException @@ -124,7 +124,7 @@ def test(): self.assertTrue(isinstance(value, NullReferenceException)) self.assertTrue(value.Message == 'Aiiieee!') - def testManagedExceptionPropagation(self): + def test_managed_exception_propagation(self): """Test propagation of exceptions raised in managed code.""" from System import Decimal, OverflowException @@ -133,7 +133,7 @@ def test(): self.assertRaises(OverflowException, test) - def testManagedExceptionConversion(self): + def test_managed_exception_conversion(self): """Test conversion of managed exceptions.""" from System import Exception, OverflowException from Python.Test import ExceptionTest @@ -158,7 +158,7 @@ def testManagedExceptionConversion(self): v = ExceptionTest.SetWidenedException(OverflowException('error')) self.assertTrue(v) - def testCatchExceptionFromManagedMethod(self): + def test_catch_exception_from_managed_method(self): """Test catching an exception from a managed method.""" from Python.Test import ExceptionTest from System import OverflowException @@ -172,7 +172,7 @@ def testCatchExceptionFromManagedMethod(self): raise SystemError('failed to catch exception from managed method') - def testCatchExceptionFromManagedProperty(self): + def test_catch_exception_from_managed_property(self): """Test catching an exception from a managed property.""" from Python.Test import ExceptionTest from System import OverflowException @@ -193,7 +193,7 @@ def testCatchExceptionFromManagedProperty(self): raise SystemError('failed to catch exception from managed property') - def testCatchExceptionManagedClass(self): + def test_catch_exception_managed_class(self): """Test catching the managed class of an exception.""" from System import OverflowException @@ -204,7 +204,7 @@ def testCatchExceptionManagedClass(self): raise SystemError('failed to catch managed class exception') - def testCatchExceptionPythonClass(self): + def test_catch_exception_python_class(self): """Test catching the python class of an exception.""" from System import OverflowException if PY3: @@ -219,7 +219,7 @@ def testCatchExceptionPythonClass(self): raise SystemError('failed to catch python class exception') - def testCatchExceptionBaseClass(self): + def test_catch_exception_base_class(self): """Test catching the base of an exception.""" from System import OverflowException, ArithmeticException @@ -230,7 +230,7 @@ def testCatchExceptionBaseClass(self): raise SystemError('failed to catch base exception') - def testCatchExceptionNestedBaseClass(self): + def test_catch_exception_nested_base_class(self): """Test catching the nested base of an exception.""" from System import OverflowException, SystemException @@ -241,7 +241,7 @@ def testCatchExceptionNestedBaseClass(self): raise SystemError('failed to catch nested base exception') - def testCatchExceptionWithAssignment(self): + def test_catch_exception_with_assignment(self): """Test catching an exception with assignment.""" from System import OverflowException @@ -251,7 +251,7 @@ def testCatchExceptionWithAssignment(self): e = sys.exc_info()[1] self.assertTrue(isinstance(e, OverflowException)) - def testCatchExceptionUnqualified(self): + def test_catch_exception_unqualified(self): """Test catching an unqualified exception.""" from System import OverflowException @@ -262,14 +262,14 @@ def testCatchExceptionUnqualified(self): raise SystemError('failed to catch unqualified exception') - def testApparentModuleOfException(self): + def test_apparent_module_of_exception(self): """Test the apparent module of an exception.""" from System import Exception, OverflowException self.assertTrue(Exception.__module__ == 'System') self.assertTrue(OverflowException.__module__ == 'System') - def testStrOfException(self): + def test_str_of_exception(self): """Test the str() representation of an exception.""" from System import NullReferenceException from System import Convert, FormatException @@ -286,7 +286,7 @@ def testStrOfException(self): msg = text_type(e).encode("utf8") # fix for international installation self.assertTrue(msg.find(text_type('System.Convert.ToDateTime').encode("utf8")) > -1, msg) - def testPythonCompatOfManagedExceptions(self): + def test_python_compat_of_managed_exceptions(self): """Test if managed exceptions are compatible with Python's implementation """ from System import OverflowException @@ -303,7 +303,7 @@ def testPythonCompatOfManagedExceptions(self): elif PY2: self.assertEqual(repr(e), "OverflowException(u'A simple message',)") - def testExceptionIsInstanceOfSystemObject(self): + def test_exception_is_instance_of_system_object(self): """Test behavior of isinstance(, System.Object).""" # This is an anti-test, in that this is a caveat of the current # implementation. Because exceptions are not allowed to be new-style @@ -330,14 +330,14 @@ def testExceptionIsInstanceOfSystemObject(self): else: self.assertFalse(isinstance(o, Object)) - def testPicklingExceptions(self): + def test_pickling_exceptions(self): exc = System.Exception("test") dumped = pickle.dumps(exc) loaded = pickle.loads(dumped) self.assertEqual(exc.args, loaded.args) - def testChainedExceptions(self): + def test_chained_exceptions(self): # TODO: Why is this test PY3 only? if PY3: from Python.Test import ExceptionTest diff --git a/src/tests/test_field.py b/src/tests/test_field.py index 1a46e1d96..f3ec8b382 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -9,7 +9,7 @@ class FieldTests(unittest.TestCase): """Test CLR field support.""" - def testPublicInstanceField(self): + def test_public_instance_field(self): """Test public instance fields.""" ob = FieldTest() self.assertTrue(ob.PublicField == 0) @@ -22,7 +22,7 @@ def test(): self.assertRaises(TypeError, test) - def testPublicStaticField(self): + def test_public_static_field(self): """Test public static fields.""" ob = FieldTest() self.assertTrue(FieldTest.PublicStaticField == 0) @@ -44,7 +44,7 @@ def test(): self.assertRaises(TypeError, test) - def testProtectedInstanceField(self): + def test_protected_instance_field(self): """Test protected instance fields.""" ob = FieldTest() self.assertTrue(ob.ProtectedField == 0) @@ -57,7 +57,7 @@ def test(): self.assertRaises(TypeError, test) - def testProtectedStaticField(self): + def test_protected_static_field(self): """Test protected static fields.""" ob = FieldTest() self.assertTrue(FieldTest.ProtectedStaticField == 0) @@ -79,7 +79,7 @@ def test(): self.assertRaises(TypeError, test) - def testReadOnlyInstanceField(self): + def test_read_only_instance_field(self): """Test readonly instance fields.""" self.assertTrue(FieldTest().ReadOnlyField == 0) @@ -93,7 +93,7 @@ def test(): self.assertRaises(TypeError, test) - def testReadOnlyStaticField(self): + def test_read_only_static_field(self): """Test readonly static fields.""" ob = FieldTest() @@ -120,7 +120,7 @@ def test(): self.assertRaises(TypeError, test) - def testConstantField(self): + def test_constant_field(self): """Test const fields.""" ob = FieldTest() @@ -147,7 +147,7 @@ def test(): self.assertRaises(TypeError, test) - def testInternalField(self): + def test_internal_field(self): """Test internal fields.""" def test(): @@ -165,7 +165,7 @@ def test(): self.assertRaises(AttributeError, test) - def testPrivateField(self): + def test_private_field(self): """Test private fields.""" def test(): @@ -183,7 +183,7 @@ def test(): self.assertRaises(AttributeError, test) - def testFieldDescriptorGetSet(self): + def test_field_descriptor_get_set(self): """Test field descriptor get / set.""" # This test ensures that setting an attribute implemented with @@ -206,7 +206,7 @@ def testFieldDescriptorGetSet(self): descriptor = FieldTest.__dict__['PublicStaticField'] self.assertTrue(type(descriptor) != int) - def testFieldDescriptorWrongType(self): + def test_field_descriptor_wrong_type(self): """Test setting a field using a value of the wrong type.""" def test(): @@ -214,7 +214,7 @@ def test(): self.assertRaises(TypeError, test) - def testFieldDescriptorAbuse(self): + def test_field_descriptor_abuse(self): """Test field descriptor abuse.""" desc = FieldTest.__dict__['PublicField'] @@ -228,7 +228,7 @@ def test(): self.assertRaises(TypeError, test) - def testBooleanField(self): + def test_boolean_field(self): """Test boolean fields.""" # change this to true / false later for Python 2.3? ob = FieldTest() @@ -246,7 +246,7 @@ def testBooleanField(self): ob.BooleanField = 0 self.assertTrue(ob.BooleanField == False) - def testSByteField(self): + def test_sbyte_field(self): """Test sbyte fields.""" ob = FieldTest() self.assertTrue(ob.SByteField == 0) @@ -254,7 +254,7 @@ def testSByteField(self): ob.SByteField = 1 self.assertTrue(ob.SByteField == 1) - def testByteField(self): + def test_byte_field(self): """Test byte fields.""" ob = FieldTest() self.assertTrue(ob.ByteField == 0) @@ -262,7 +262,7 @@ def testByteField(self): ob.ByteField = 1 self.assertTrue(ob.ByteField == 1) - def testCharField(self): + def test_char_field(self): """Test char fields.""" ob = FieldTest() self.assertTrue(ob.CharField == u'A') @@ -276,7 +276,7 @@ def testCharField(self): self.assertTrue(ob.CharField == u'C') self.assertTrue(ob.CharField == 'C') - def testInt16Field(self): + def test_int16_field(self): """Test int16 fields.""" ob = FieldTest() self.assertTrue(ob.Int16Field == 0) @@ -284,7 +284,7 @@ def testInt16Field(self): ob.Int16Field = 1 self.assertTrue(ob.Int16Field == 1) - def testInt32Field(self): + def test_int32_field(self): """Test int32 fields.""" ob = FieldTest() self.assertTrue(ob.Int32Field == 0) @@ -292,7 +292,7 @@ def testInt32Field(self): ob.Int32Field = 1 self.assertTrue(ob.Int32Field == 1) - def testInt64Field(self): + def test_int64_field(self): """Test int64 fields.""" ob = FieldTest() self.assertTrue(ob.Int64Field == 0) @@ -300,7 +300,7 @@ def testInt64Field(self): ob.Int64Field = 1 self.assertTrue(ob.Int64Field == 1) - def testUInt16Field(self): + def test_uint16_field(self): """Test uint16 fields.""" ob = FieldTest() self.assertTrue(ob.UInt16Field == 0) @@ -308,7 +308,7 @@ def testUInt16Field(self): ob.UInt16Field = 1 self.assertTrue(ob.UInt16Field == 1) - def testUInt32Field(self): + def test_uint32_field(self): """Test uint32 fields.""" ob = FieldTest() self.assertTrue(ob.UInt32Field == 0) @@ -316,7 +316,7 @@ def testUInt32Field(self): ob.UInt32Field = 1 self.assertTrue(ob.UInt32Field == 1) - def testUInt64Field(self): + def test_uint64_field(self): """Test uint64 fields.""" ob = FieldTest() self.assertTrue(ob.UInt64Field == 0) @@ -324,7 +324,7 @@ def testUInt64Field(self): ob.UInt64Field = 1 self.assertTrue(ob.UInt64Field == 1) - def testSingleField(self): + def test_single_field(self): """Test single fields.""" ob = FieldTest() self.assertTrue(ob.SingleField == 0.0) @@ -332,7 +332,7 @@ def testSingleField(self): ob.SingleField = 1.1 self.assertTrue(ob.SingleField == 1.1) - def testDoubleField(self): + def test_double_field(self): """Test double fields.""" ob = FieldTest() self.assertTrue(ob.DoubleField == 0.0) @@ -340,7 +340,7 @@ def testDoubleField(self): ob.DoubleField = 1.1 self.assertTrue(ob.DoubleField == 1.1) - def testDecimalField(self): + def test_decimal_field(self): """Test decimal fields.""" ob = FieldTest() self.assertTrue(ob.DecimalField == System.Decimal(0)) @@ -348,7 +348,7 @@ def testDecimalField(self): ob.DecimalField = System.Decimal(1) self.assertTrue(ob.DecimalField == System.Decimal(1)) - def testStringField(self): + def test_string_field(self): """Test string fields.""" ob = FieldTest() self.assertTrue(ob.StringField == "spam") @@ -356,7 +356,7 @@ def testStringField(self): ob.StringField = "eggs" self.assertTrue(ob.StringField == "eggs") - def testInterfaceField(self): + def test_interface_field(self): """Test interface fields.""" from Python.Test import Spam, ISpam @@ -369,7 +369,7 @@ def testInterfaceField(self): self.assertTrue(ISpam(ob.SpamField).GetValue() == "eggs") self.assertTrue(ob.SpamField.GetValue() == "eggs") - def testObjectField(self): + def test_object_field(self): """Test ob fields.""" ob = FieldTest() self.assertTrue(ob.ObjectField == None) @@ -383,7 +383,7 @@ def testObjectField(self): ob.ObjectField = None self.assertTrue(ob.ObjectField == None) - def testEnumField(self): + def test_enum_field(self): """Test enum fields.""" from Python.Test import ShortEnum @@ -393,7 +393,7 @@ def testEnumField(self): ob.EnumField = ShortEnum.One self.assertTrue(ob.EnumField == ShortEnum.One) - def testNullableField(self): + def test_nullable_field(self): """Test nullable fields.""" ob = FieldTest() diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index 536a2bb7f..d4c93c060 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -112,7 +112,7 @@ def _testGenericMethodByType(self, ptype, value, test_type=0): self.assertTrue(result[0] == value) self.assertTrue(result[1] == value) - def testPythonTypeAliasing(self): + def test_python_type_aliasing(self): """Test python type alias support with generics.""" from System.Collections.Generic import Dictionary @@ -166,7 +166,7 @@ def testPythonTypeAliasing(self): dict.Add(True, False) self.assertTrue(dict[True] == False) - def testGenericReferenceType(self): + def test_generic_reference_type(self): """Test usage of generic reference type definitions.""" from Python.Test import GenericTypeDefinition @@ -174,21 +174,21 @@ def testGenericReferenceType(self): self.assertTrue(inst.value1 == "one") self.assertTrue(inst.value2 == 2) - def testGenericValueType(self): + def test_generic_value_type(self): """Test usage of generic value type definitions.""" inst = System.Nullable[System.Int32](10) self.assertTrue(inst.HasValue) self.assertTrue(inst.Value == 10) - def testGenericInterface(self): + def test_generic_interface(self): # TODO NotImplemented pass - def testGenericDelegate(self): + def test_generic_delegate(self): # TODO NotImplemented pass - def testOpenGenericType(self): + def test_open_generic_type(self): """Test behavior of reflected open constructed generic types.""" from Python.Test import DerivedFromOpenGeneric @@ -204,7 +204,7 @@ def test(): self.assertRaises(TypeError, test) - def testDerivedFromOpenGenericType(self): + def test_derived_from_open_generic_type(self): """Test a generic type derived from an open generic type.""" from Python.Test import DerivedFromOpenGeneric @@ -215,7 +215,7 @@ def testDerivedFromOpenGenericType(self): self.assertTrue(inst.value2 == 'two') self.assertTrue(inst.value3 == 'three') - def testGenericTypeNameResolution(self): + def test_generic_type_name_resolution(self): """Test the ability to disambiguate generic type names.""" from Python.Test import GenericNameTest1, GenericNameTest2 @@ -241,7 +241,7 @@ def test(): self.assertTrue(_class().value == 2) self.assertTrue(_class.value == 2) - def testGenericTypeBinding(self): + def test_generic_type_binding(self): """Test argument conversion / binding for generic methods.""" from Python.Test import InterfaceTest, ISayHello1, ShortEnum import System @@ -273,7 +273,7 @@ def testGenericTypeBinding(self): self._testGenericWrapperByType(InterfaceTest, InterfaceTest()) self._testGenericWrapperByType(ISayHello1, InterfaceTest()) - def testGenericMethodBinding(self): + def test_generic_method_binding(self): from Python.Test import GenericMethodTest, GenericStaticMethodTest from System import InvalidOperationException @@ -298,7 +298,7 @@ def test(): self.assertRaises(TypeError, test) - def testGenericMethodTypeHandling(self): + def test_generic_method_type_handling(self): """Test argument conversion / binding for generic methods.""" from Python.Test import InterfaceTest, ISayHello1, ShortEnum import System @@ -333,7 +333,7 @@ def testGenericMethodTypeHandling(self): self._testGenericMethodByType(InterfaceTest, InterfaceTest(), 1) self._testGenericMethodByType(ISayHello1, InterfaceTest(), 1) - def testCorrectOverloadSelection(self): + def test_correct_overload_selection(self): """Test correct overloading selection for common types.""" from System.Drawing import Font @@ -371,7 +371,7 @@ def testCorrectOverloadSelection(self): CSArray = Array.CreateInstance(Byte, 1000) handler = GCHandle.Alloc(CSArray, GCHandleType.Pinned) - def testGenericMethodOverloadSelection(self): + def test_generic_method_overload_selection(self): """Test explicit overload selection with generic methods.""" from Python.Test import GenericMethodTest, GenericStaticMethodTest @@ -452,7 +452,7 @@ def test(): self.assertRaises(TypeError, test) - def testMethodOverloadSelectionWithGenericTypes(self): + def test_method_overload_selection_with_generic_types(self): """Check method overload selection using generic types.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from Python.Test import MethodTest, GenericWrapper @@ -587,7 +587,7 @@ def testMethodOverloadSelectionWithGenericTypes(self): self.assertTrue(value[0].value == 0) self.assertTrue(value[1].value == 1) - def testOverloadSelectionWithArraysOfGenericTypes(self): + def test_overload_selection_with_arrays_of_generic_types(self): """Check overload selection using arrays of generic types.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from Python.Test import MethodTest, GenericWrapper @@ -770,12 +770,12 @@ def testOverloadSelectionWithArraysOfGenericTypes(self): self.assertTrue(value[0].value.__class__ == inst.__class__) self.assertTrue(value.Length == 2) - def testGenericOverloadSelectionMagicNameOnly(self): + def test_generic_overload_selection_magic_name_only(self): """Test using only __overloads__ to select on type & sig""" # TODO NotImplemented pass - def testNestedGenericClass(self): + def test_nested_generic_class(self): """Check nested generic classes.""" # TODO NotImplemented pass diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index eaa02abd0..daec3d7f7 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -10,7 +10,7 @@ class IndexerTests(unittest.TestCase): """Test support for indexer properties.""" - def testPublicIndexer(self): + def test_public_indexer(self): """Test public indexers.""" ob = Test.PublicIndexerTest() @@ -22,7 +22,7 @@ def testPublicIndexer(self): self.assertTrue(ob[10] == None) - def testProtectedIndexer(self): + def test_protected_indexer(self): """Test protected indexers.""" ob = Test.ProtectedIndexerTest() @@ -34,7 +34,7 @@ def testProtectedIndexer(self): self.assertTrue(ob[10] == None) - def testInternalIndexer(self): + def test_internal_indexer(self): """Test internal indexers.""" ob = Test.InternalIndexerTest() @@ -53,7 +53,7 @@ def test(): self.assertRaises(TypeError, test) - def testPrivateIndexer(self): + def test_private_indexer(self): """Test private indexers.""" ob = Test.PrivateIndexerTest() @@ -72,7 +72,7 @@ def test(): self.assertRaises(TypeError, test) - def testBooleanIndexer(self): + def test_boolean_indexer(self): """Test boolean indexers.""" ob = Test.BooleanIndexerTest() @@ -91,7 +91,7 @@ def testBooleanIndexer(self): ob[True] = "true" self.assertTrue(ob[True] == "true") - def testByteIndexer(self): + def test_byte_indexer(self): """Test byte indexers.""" ob = Test.ByteIndexerTest() max = 255 @@ -117,7 +117,7 @@ def test(): self.assertRaises(TypeError, test) - def testSByteIndexer(self): + def test_sbyte_indexer(self): """Test sbyte indexers.""" ob = Test.SByteIndexerTest() max = 127 @@ -143,7 +143,7 @@ def test(): self.assertRaises(TypeError, test) - def testCharIndexer(self): + def test_char_indexer(self): """Test char indexers.""" ob = Test.CharIndexerTest() max = unichr(65535) @@ -169,7 +169,7 @@ def test(): self.assertRaises(TypeError, test) - def testInt16Indexer(self): + def test_int16_indexer(self): """Test Int16 indexers.""" ob = Test.Int16IndexerTest() max = 32767 @@ -195,7 +195,7 @@ def test(): self.assertRaises(TypeError, test) - def testInt32Indexer(self): + def test_int32_indexer(self): """Test Int32 indexers.""" ob = Test.Int32IndexerTest() max = 2147483647 @@ -221,7 +221,7 @@ def test(): self.assertRaises(TypeError, test) - def testInt64Indexer(self): + def test_int64_indexer(self): """Test Int64 indexers.""" ob = Test.Int64IndexerTest() max = long(9223372036854775807) @@ -247,7 +247,7 @@ def test(): self.assertRaises(TypeError, test) - def testUInt16Indexer(self): + def test_uint16_indexer(self): """Test UInt16 indexers.""" ob = Test.UInt16IndexerTest() max = 65535 @@ -273,7 +273,7 @@ def test(): self.assertRaises(TypeError, test) - def testUInt32Indexer(self): + def test_uint32_indexer(self): """Test UInt32 indexers.""" ob = Test.UInt32IndexerTest() max = long(4294967295) @@ -299,7 +299,7 @@ def test(): self.assertRaises(TypeError, test) - def testUInt64Indexer(self): + def test_uint64_indexer(self): """Test UInt64 indexers.""" ob = Test.UInt64IndexerTest() max = long(18446744073709551615) @@ -325,7 +325,7 @@ def test(): self.assertRaises(TypeError, test) - def testSingleIndexer(self): + def test_single_indexer(self): """Test Single indexers.""" ob = Test.SingleIndexerTest() max = 3.402823e38 @@ -351,7 +351,7 @@ def test(): self.assertRaises(TypeError, test) - def testDoubleIndexer(self): + def test_double_indexer(self): """Test Double indexers.""" ob = Test.DoubleIndexerTest() max = 1.7976931348623157e308 @@ -377,7 +377,7 @@ def test(): self.assertRaises(TypeError, test) - def testDecimalIndexer(self): + def test_decimal_indexer(self): """Test Decimal indexers.""" ob = Test.DecimalIndexerTest() @@ -405,7 +405,7 @@ def test(): self.assertRaises(TypeError, test) - def testStringIndexer(self): + def test_string_indexer(self): """Test String indexers.""" ob = Test.StringIndexerTest() @@ -436,7 +436,7 @@ def test(): self.assertRaises(TypeError, test) - def testEnumIndexer(self): + def test_enum_indexer(self): """Test enum indexers.""" ob = Test.EnumIndexerTest() @@ -465,7 +465,7 @@ def test(): self.assertRaises(TypeError, test) - def testObjectIndexer(self): + def test_object_indexer(self): """Test ob indexers.""" ob = Test.ObjectIndexerTest() @@ -499,7 +499,7 @@ class eggs(object): self.assertRaises(TypeError, test) - def testInterfaceIndexer(self): + def test_interface_indexer(self): """Test interface indexers.""" ob = Test.InterfaceIndexerTest() @@ -526,7 +526,7 @@ def test(): self.assertRaises(TypeError, test) - def testTypedIndexer(self): + def test_typed_indexer(self): """Test typed indexers.""" ob = Test.TypedIndexerTest() @@ -553,7 +553,7 @@ def test(): self.assertRaises(TypeError, test) - def testMultiArgIndexer(self): + def test_multi_arg_indexer(self): """Test indexers that take multiple index arguments.""" ob = Test.MultiArgIndexerTest() @@ -577,7 +577,7 @@ def test(): self.assertRaises(TypeError, test) - def testMultiTypeIndexer(self): + def test_multi_type_indexer(self): """Test indexers that take multiple indices of different types.""" ob = Test.MultiTypeIndexerTest() spam = Test.Spam("spam") @@ -600,7 +600,7 @@ def test(): self.assertRaises(TypeError, test) - def testMultiDefaultKeyIndexer(self): + def test_multi_default_key_indexer(self): """Test indexers that take multiple indices with a default key arguments.""" # default argument is 2 in the MultiDefaultKeyIndexerTest object ob = Test.MultiDefaultKeyIndexerTest() @@ -610,7 +610,7 @@ def testMultiDefaultKeyIndexer(self): ob[1] = "one nine spam" self.assertTrue(ob[1, 2] == "one nine spam") - def testIndexerWrongKeyType(self): + def test_indexer_wrong_key_type(self): """Test calling an indexer using a key of the wrong type.""" def test(): @@ -625,7 +625,7 @@ def test(): self.assertRaises(TypeError, test) - def testIndexerWrongValueType(self): + def test_indexer_wrong_value_type(self): """Test calling an indexer using a value of the wrong type.""" def test(): @@ -634,7 +634,7 @@ def test(): self.assertRaises(TypeError, test) - def testUnboundIndexer(self): + def test_unbound_indexer(self): """Test calling an unbound indexer.""" ob = Test.PublicIndexerTest() @@ -646,7 +646,7 @@ def testUnboundIndexer(self): self.assertTrue(ob[10] == None) - def testIndexerAbuse(self): + def test_indexer_abuse(self): """Test indexer abuse.""" _class = Test.PublicIndexerTest ob = Test.PublicIndexerTest() diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index 6bc05fd5f..d47c6279a 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -10,7 +10,7 @@ class InterfaceTests(unittest.TestCase): """Test CLR interface support.""" - def testInterfaceStandardAttrs(self): + def test_interface_standard_attrs(self): """Test standard class attributes.""" from Python.Test import IPublicInterface @@ -18,7 +18,7 @@ def testInterfaceStandardAttrs(self): self.assertTrue(IPublicInterface.__module__ == 'Python.Test') self.assertTrue(type(IPublicInterface.__dict__) == DictProxyType) - def testGlobalInterfaceVisibility(self): + def test_global_interface_visibility(self): """Test visibility of module-level interfaces.""" from Python.Test import IPublicInterface @@ -34,7 +34,7 @@ def test(): self.assertRaises(AttributeError, test) - def testNestedInterfaceVisibility(self): + def test_nested_interface_visibility(self): """Test visibility of nested interfaces.""" from Python.Test import InterfaceTest @@ -54,7 +54,7 @@ def test(): self.assertRaises(AttributeError, test) - def testExplicitCastToInterface(self): + def test_explicit_cast_to_interface(self): """Test explicit cast to an interface.""" from Python.Test import InterfaceTest diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 0430bb019..677a69b52 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -11,7 +11,7 @@ class MethodTests(unittest.TestCase): """Test CLR method support.""" - def testInstanceMethodDescriptor(self): + def test_instance_method_descriptor(self): """Test instance method descriptor behavior.""" def test(): @@ -34,7 +34,7 @@ def test(): self.assertRaises(AttributeError, test) - def testStaticMethodDescriptor(self): + def test_static_method_descriptor(self): """Test static method descriptor behavior.""" def test(): @@ -57,30 +57,30 @@ def test(): self.assertRaises(AttributeError, test) - def testPublicInstanceMethod(self): + def test_public_instance_method(self): """Test public instance method visibility.""" ob = MethodTest() self.assertTrue(ob.PublicMethod() == "public") - def testPublicStaticMethod(self): + def test_public_static_method(self): """Test public static method visibility.""" ob = MethodTest() self.assertTrue(MethodTest.PublicStaticMethod() == "public static") self.assertTrue(ob.PublicStaticMethod() == "public static") - def testProtectedInstanceMethod(self): + def test_protected_instance_method(self): """Test protected instance method visibility.""" ob = MethodTest() self.assertTrue(ob.ProtectedMethod() == "protected") - def testProtectedStaticMethod(self): + def test_protected_static_method(self): """Test protected static method visibility.""" ob = MethodTest() result = "protected static" self.assertTrue(MethodTest.ProtectedStaticMethod() == result) self.assertTrue(ob.ProtectedStaticMethod() == result) - def testInternalMethod(self): + def test_internal_method(self): """Test internal method visibility.""" def test(): @@ -103,7 +103,7 @@ def test(): self.assertRaises(AttributeError, test) - def testPrivateMethod(self): + def test_private_method(self): """Test private method visibility.""" def test(): @@ -126,7 +126,7 @@ def test(): self.assertRaises(AttributeError, test) - def testUnboundManagedMethodCall(self): + def test_unbound_managed_method_call(self): """Test calling unbound managed methods.""" from Python.Test import MethodTestSub @@ -147,7 +147,7 @@ def test(): self.assertRaises(TypeError, test) - def testOverloadedMethodInheritance(self): + def test_overloaded_method_inheritance(self): """Test that overloads are inherited properly.""" from Python.Test import MethodTestSub @@ -165,7 +165,7 @@ def test(): self.assertTrue(ob.PublicMethod("echo") == "echo") - def testMethodDescriptorAbuse(self): + def test_method_descriptor_abuse(self): """Test method descriptor abuse.""" desc = MethodTest.__dict__['PublicMethod'] @@ -179,7 +179,7 @@ def test(): self.assertRaises(AttributeError, test) - def testMethodDocstrings(self): + def test_method_docstrings(self): """Test standard method docstring generation""" method = MethodTest.GetType value = 'System.Type GetType()' @@ -189,7 +189,7 @@ def testMethodDocstrings(self): # Tests of specific argument and result conversion scenarios # ====================================================================== - def testMethodCallEnumConversion(self): + def test_method_call_enum_conversion(self): """Test enum conversion in method call.""" from System import TypeCode @@ -197,7 +197,7 @@ def testMethodCallEnumConversion(self): r = ob.TestEnumConversion(TypeCode.Int32) self.assertTrue(r == TypeCode.Int32) - def testMethodCallFlagsConversion(self): + def test_method_call_flags_conversion(self): """Test flags conversion in method call.""" from System.IO import FileAccess @@ -206,7 +206,7 @@ def testMethodCallFlagsConversion(self): r = ob.TestFlagsConversion(flags) self.assertTrue(r == flags) - def testMethodCallStructConversion(self): + def test_method_call_struct_conversion(self): """Test struct conversion in method call.""" from System import Guid @@ -216,7 +216,7 @@ def testMethodCallStructConversion(self): r = ob.TestStructConversion(guid) self.assertTrue(r.ToString() == temp) - def testSubclassInstanceConversion(self): + def test_subclass_instance_conversion(self): """Test subclass instance conversion in method call.""" class TestSubException(System.Exception): @@ -227,7 +227,7 @@ class TestSubException(System.Exception): result = ob.TestSubclassConversion(instance) self.assertTrue(isinstance(result, System.Exception)) - def testNullArrayConversion(self): + def test_null_array_conversion(self): """Test null array conversion in method call.""" from System import Type @@ -235,7 +235,7 @@ def testNullArrayConversion(self): r = ob.TestNullArrayConversion(None) self.assertTrue(r == None) - def testStringParamsArgs(self): + def test_string_params_args(self): """Test use of string params.""" result = MethodTest.TestStringParamsArg('one', 'two', 'three') self.assertEqual(result.Length, 3) @@ -250,7 +250,7 @@ def testStringParamsArgs(self): self.assertTrue(result[1] == 'two') self.assertTrue(result[2] == 'three') - def testObjectParamsArgs(self): + def test_object_params_args(self): """Test use of object params.""" result = MethodTest.TestObjectParamsArg('one', 'two', 'three') self.assertEqual(len(result), 3, result) @@ -264,7 +264,7 @@ def testObjectParamsArgs(self): self.assertTrue(result[1] == 'two') self.assertTrue(result[2] == 'three') - def testValueParamsArgs(self): + def test_value_params_args(self): """Test use of value type params.""" result = MethodTest.TestValueParamsArg(1, 2, 3) self.assertEqual(len(result), 3) @@ -278,12 +278,12 @@ def testValueParamsArgs(self): self.assertTrue(result[1] == 2) self.assertTrue(result[2] == 3) - def testNonParamsArrayInLastPlace(self): + def test_non_params_array_in_last_place(self): """Test overload resolution with of non-"params" array as last parameter.""" result = MethodTest.TestNonParamsArrayInLastPlace(1, 2, 3) self.assertTrue(result) - def testStringOutParams(self): + def test_string_out_params(self): """Test use of string out-parameters.""" result = MethodTest.TestStringOutParams("hi", "there") self.assertTrue(type(result) == type(())) @@ -297,7 +297,7 @@ def testStringOutParams(self): self.assertTrue(result[0] == True) self.assertTrue(result[1] == "output string") - def testStringRefParams(self): + def test_string_ref_params(self): """Test use of string byref parameters.""" result = MethodTest.TestStringRefParams("hi", "there") self.assertTrue(type(result) == type(())) @@ -311,7 +311,7 @@ def testStringRefParams(self): self.assertTrue(result[0] == True) self.assertTrue(result[1] == "output string") - def testValueOutParams(self): + def test_value_out_params(self): """Test use of value type out-parameters.""" result = MethodTest.TestValueOutParams("hi", 1) self.assertTrue(type(result) == type(())) @@ -325,7 +325,7 @@ def test(): # None cannot be converted to a value type like int, long, etc. self.assertRaises(TypeError, test) - def testValueRefParams(self): + def test_value_ref_params(self): """Test use of value type byref parameters.""" result = MethodTest.TestValueRefParams("hi", 1) self.assertTrue(type(result) == type(())) @@ -339,7 +339,7 @@ def test(): # None cannot be converted to a value type like int, long, etc. self.assertRaises(TypeError, test) - def testObjectOutParams(self): + def test_object_out_params(self): """Test use of object out-parameters.""" result = MethodTest.TestObjectOutParams("hi", MethodTest()) self.assertTrue(type(result) == type(())) @@ -353,7 +353,7 @@ def testObjectOutParams(self): self.assertTrue(result[0] == True) self.assertTrue(isinstance(result[1], System.Exception)) - def testObjectRefParams(self): + def test_object_ref_params(self): """Test use of object byref parameters.""" result = MethodTest.TestObjectRefParams("hi", MethodTest()) self.assertTrue(type(result) == type(())) @@ -367,7 +367,7 @@ def testObjectRefParams(self): self.assertTrue(result[0] == True) self.assertTrue(isinstance(result[1], System.Exception)) - def testStructOutParams(self): + def test_struct_out_params(self): """Test use of struct out-parameters.""" result = MethodTest.TestStructOutParams("hi", System.Guid.NewGuid()) self.assertTrue(type(result) == type(())) @@ -381,7 +381,7 @@ def test(): # None cannot be converted to a value type like a struct self.assertRaises(TypeError, test) - def testStructRefParams(self): + def test_struct_ref_params(self): """Test use of struct byref parameters.""" result = MethodTest.TestStructRefParams("hi", System.Guid.NewGuid()) self.assertTrue(type(result) == type(())) @@ -395,7 +395,7 @@ def test(): # None cannot be converted to a value type like a struct self.assertRaises(TypeError, test) - def testVoidSingleOutParam(self): + def test_void_single_out_param(self): """Test void method with single out-parameter.""" result = MethodTest.TestVoidSingleOutParam(9) self.assertTrue(result == 42) @@ -406,7 +406,7 @@ def test(): # None cannot be converted to a value type self.assertRaises(TypeError, test) - def testVoidSingleRefParam(self): + def test_void_single_ref_param(self): """Test void method with single ref-parameter.""" result = MethodTest.TestVoidSingleRefParam(9) self.assertTrue(result == 42) @@ -417,12 +417,12 @@ def test(): # None cannot be converted to a value type self.assertRaises(TypeError, test) - def testSingleDefaultParam(self): + def test_single_default_param(self): """Test void method with single ref-parameter.""" result = MethodTest.TestSingleDefaultParam() self.assertTrue(result == 5) - def testOneArgAndTwoDefaultParam(self): + def test_one_arg_and_two_default_param(self): """Test void method with single ref-parameter.""" result = MethodTest.TestOneArgAndTwoDefaultParam(11) self.assertTrue(result == 22) @@ -433,12 +433,12 @@ def testOneArgAndTwoDefaultParam(self): result = MethodTest.TestOneArgAndTwoDefaultParam(20) self.assertTrue(result == 31) - def testTwoDefaultParam(self): + def test_two_default_param(self): """Test void method with single ref-parameter.""" result = MethodTest.TestTwoDefaultParam() self.assertTrue(result == 11) - def testExplicitSelectionWithOutModifier(self): + def test_explicit_selection_with_out_modifier(self): """Check explicit overload selection with out modifiers.""" refstr = System.String("").GetType().MakeByRefType() result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( @@ -457,7 +457,7 @@ def testExplicitSelectionWithOutModifier(self): self.assertTrue(result[0] == True) self.assertTrue(result[1] == "output string") - def testExplicitSelectionWithRefModifier(self): + def test_explicit_selection_with_ref_modifier(self): """Check explicit overload selection with ref modifiers.""" refstr = System.String("").GetType().MakeByRefType() result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( @@ -476,7 +476,7 @@ def testExplicitSelectionWithRefModifier(self): self.assertTrue(result[0] == True) self.assertTrue(result[1] == "output string") - def testExplicitOverloadSelection(self): + def test_explicit_overload_selection(self): """Check explicit overload selection using [] syntax.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from System import Array @@ -580,7 +580,7 @@ def testExplicitOverloadSelection(self): value = MethodTest.Overloaded.__overloads__[int, str](1, "one") self.assertTrue(value == 1) - def testOverloadSelectionWithArrayTypes(self): + def test_overload_selection_with_array_types(self): """Check overload selection using array types.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from System import Array @@ -732,7 +732,7 @@ def testOverloadSelectionWithArrayTypes(self): self.assertTrue(value[0].__class__ == inst.__class__) self.assertTrue(value[1].__class__ == inst.__class__) - def testExplicitOverloadSelectionFailure(self): + def test_explicit_overload_selection_failure(self): """Check that overload selection fails correctly.""" def test(): @@ -757,7 +757,7 @@ def test(): self.assertRaises(TypeError, test) - def testWeCanBindToEncodingGetString(self): + def test_we_can_bind_to_encoding_get_string(self): """Check that we can bind to the Encoding.GetString method with variables.""" from System.Text import Encoding diff --git a/src/tests/test_module.py b/src/tests/test_module.py index 4748c0497..998124d67 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -16,21 +16,21 @@ class ModuleTests(unittest.TestCase): """Test CLR modules and the CLR import hook.""" - def testAAAImportHookWorks(self): + def test_import_hook_works(self): """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 - def test000importClr(self): + def test_import_clr(self): import clr self.assertTrue(isCLRRootModule(clr)) - def testVersionClr(self): + def test_version_clr(self): import clr self.assertTrue(clr.__version__ >= "2.2.0") - def testPreloadVar(self): + def test_preload_var(self): import clr self.assertTrue(clr.getPreload() is False, clr.getPreload()) clr.setPreload(False) @@ -49,7 +49,7 @@ def testPreloadVar(self): finally: clr.setPreload(False) - def testModuleInterface(self): + def test_module_interface(self): """Test the interface exposed by CLR module objects.""" import System self.assertEquals(type(System.__dict__), type({})) @@ -63,7 +63,7 @@ def testModuleInterface(self): self.assertTrue(isCLRClass(System.String)) self.assertTrue(isCLRClass(System.Int32)) - def testSimpleImport(self): + def test_simple_import(self): """Test simple import.""" import System self.assertTrue(isCLRModule(System)) @@ -82,7 +82,7 @@ def testSimpleImport(self): self.assertTrue(type(httplib) == types.ModuleType) self.assertTrue(httplib.__name__ == 'httplib') - def testSimpleImportWithAlias(self): + def test_simple_import_with_alias(self): """Test simple import with aliasing.""" import System as mySystem self.assertTrue(isCLRModule(mySystem)) @@ -101,7 +101,7 @@ def testSimpleImportWithAlias(self): self.assertTrue(type(myHttplib) == types.ModuleType) self.assertTrue(myHttplib.__name__ == 'httplib') - def testDottedNameImport(self): + def test_dotted_name_import(self): """Test dotted-name import.""" import System.Reflection self.assertTrue(isCLRModule(System.Reflection)) @@ -111,7 +111,7 @@ def testDottedNameImport(self): self.assertTrue(type(xml.dom) == types.ModuleType) self.assertTrue(xml.dom.__name__ == 'xml.dom') - def testMultipleDottedNameImport(self): + def test_multiple_dotted_name_import(self): """Test an import bug with multiple dotted imports.""" import System.Data self.assertTrue(isCLRModule(System.Data)) @@ -120,7 +120,7 @@ def testMultipleDottedNameImport(self): self.assertTrue(isCLRModule(System.Data)) self.assertTrue(System.Data.__name__ == 'System.Data') - def testDottedNameImportWithAlias(self): + def test_dotted_name_import_with_alias(self): """Test dotted-name import with aliasing.""" import System.Reflection as SysRef self.assertTrue(isCLRModule(SysRef)) @@ -130,7 +130,7 @@ def testDottedNameImportWithAlias(self): self.assertTrue(type(myDom) == types.ModuleType) self.assertTrue(myDom.__name__ == 'xml.dom') - def testSimpleImportFrom(self): + def test_simple_import_from(self): """Test simple 'import from'.""" from System import Reflection self.assertTrue(isCLRModule(Reflection)) @@ -140,7 +140,7 @@ def testSimpleImportFrom(self): self.assertTrue(type(dom) == types.ModuleType) self.assertTrue(dom.__name__ == 'xml.dom') - def testSimpleImportFromWithAlias(self): + def test_simple_import_from_with_alias(self): """Test simple 'import from' with aliasing.""" from System import Collections as Coll self.assertTrue(isCLRModule(Coll)) @@ -150,7 +150,7 @@ def testSimpleImportFromWithAlias(self): self.assertTrue(type(myDom) == types.ModuleType) self.assertTrue(myDom.__name__ == 'xml.dom') - def testDottedNameImportFrom(self): + def test_dotted_name_import_from(self): """Test dotted-name 'import from'.""" from System.Collections import Specialized self.assertTrue(isCLRModule(Specialized)) @@ -170,7 +170,7 @@ def testDottedNameImportFrom(self): self.assertTrue(type(PullDOM) == ClassType) self.assertTrue(PullDOM.__name__ == 'PullDOM') - def testDottedNameImportFromWithAlias(self): + def test_dotted_name_import_from_with_alias(self): """Test dotted-name 'import from' with aliasing.""" from System.Collections import Specialized as Spec self.assertTrue(isCLRModule(Spec)) @@ -188,7 +188,7 @@ def testDottedNameImportFromWithAlias(self): self.assertTrue(type(myPullDOM) == ClassType) self.assertTrue(myPullDOM.__name__ == 'PullDOM') - def testFromModuleImportStar(self): + def test_from_module_import_star(self): """Test from module import * behavior.""" count = len(locals().keys()) m = __import__('System.Xml', globals(), locals(), ['*']) @@ -196,7 +196,7 @@ def testFromModuleImportStar(self): self.assertTrue(isCLRModule(m)) self.assertTrue(len(locals().keys()) > count + 1) - def testImplicitAssemblyLoad(self): + def test_implicit_assembly_load(self): """Test implicit assembly loading via import.""" with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") @@ -218,7 +218,7 @@ def testImplicitAssemblyLoad(self): self.assertTrue(Form.__name__ == 'Form') self.assertEqual(len(w), 0) - def testExplicitAssemblyLoad(self): + def test_explicit_assembly_load(self): """Test explicit assembly loading using standard CLR tools.""" from System.Reflection import Assembly import System, sys @@ -232,7 +232,7 @@ def testExplicitAssemblyLoad(self): assembly = Assembly.LoadWithPartialName('SpamSpamSpamSpamEggsAndSpam') self.assertTrue(assembly == None) - def testImplicitLoadAlreadyValidNamespace(self): + def test_implicit_load_already_valid_namespace(self): """Test implicit assembly load over an already valid namespace.""" # In this case, the mscorlib assembly (loaded by default) defines # a number of types in the System namespace. There is also a System @@ -243,7 +243,7 @@ def testImplicitLoadAlreadyValidNamespace(self): import System self.assertTrue(isCLRClass(System.UriBuilder)) - def testImportNonExistantModule(self): + def test_import_non_existant_module(self): """Test import failure for a non-existant module.""" def test(): @@ -251,13 +251,13 @@ def test(): self.assertTrue(ImportError, test) - def testLookupNoNamespaceType(self): + def test_lookup_no_namespace_type(self): """Test lookup of types without a qualified namespace.""" import Python.Test import clr self.assertTrue(isCLRClass(clr.NoNamespaceType)) - def testModuleLookupRecursion(self): + def test_module_lookup_recursion(self): """Test for recursive lookup handling.""" def test1(): @@ -271,7 +271,7 @@ def test2(): self.assertTrue(AttributeError, test2) - def testModuleGetAttr(self): + def test_module_get_attr(self): """Test module getattr behavior.""" import System @@ -291,7 +291,7 @@ def test(): self.assertTrue(TypeError, test) - def testModuleAttrAbuse(self): + def test_module_attr_abuse(self): """Test handling of attempts to set module attributes.""" # It would be safer to use a dict-proxy as the __dict__ for CLR @@ -305,7 +305,7 @@ def test(): self.assertTrue(test()) - def testModuleTypeAbuse(self): + def test_module_type_abuse(self): """Test handling of attempts to break the module type.""" import System mtype = type(System) @@ -325,7 +325,7 @@ def test(): self.assertTrue(TypeError, test) - def test_ClrListAssemblies(self): + def test_clr_list_assemblies(self): from clr import ListAssemblies verbose = list(ListAssemblies(True)) short = list(ListAssemblies(False)) @@ -334,7 +334,7 @@ def test_ClrListAssemblies(self): self.assertTrue(u'Culture=' in verbose[0]) self.assertTrue(u'Version=' in verbose[0]) - def test_ClrAddReference(self): + def test_clr_add_reference(self): from clr import AddReference from System.IO import FileNotFoundException for name in ("System", "Python.Runtime"): @@ -345,7 +345,7 @@ def test_ClrAddReference(self): self.assertRaises(FileNotFoundException, AddReference, "somethingtotallysilly") - def test_AssemblyLoadThreadSafety(self): + def test_assembly_load_thread_safety(self): import time from Python.Test import ModuleTest # spin up .NET thread which loads assemblies and triggers AppDomain.AssemblyLoad event diff --git a/src/tests/test_property.py b/src/tests/test_property.py index b0676f6b1..d8d967658 100644 --- a/src/tests/test_property.py +++ b/src/tests/test_property.py @@ -8,7 +8,7 @@ class PropertyTests(unittest.TestCase): """Test CLR property support.""" - def testPublicInstanceProperty(self): + def test_public_instance_property(self): """Test public instance properties.""" ob = PropertyTest() @@ -21,7 +21,7 @@ def test(): self.assertRaises(TypeError, test) - def testPublicStaticProperty(self): + def test_public_static_property(self): """Test public static properties.""" ob = PropertyTest() @@ -43,7 +43,7 @@ def test(): self.assertRaises(TypeError, test) - def testProtectedInstanceProperty(self): + def test_protected_instance_property(self): """Test protected instance properties.""" ob = PropertyTest() @@ -56,7 +56,7 @@ def test(): self.assertRaises(TypeError, test) - def testProtectedStaticProperty(self): + def test_protected_static_property(self): """Test protected static properties.""" ob = PropertyTest() @@ -78,7 +78,7 @@ def test(): self.assertRaises(TypeError, test) - def testInternalProperty(self): + def test_internal_property(self): """Test internal properties.""" def test(): @@ -96,7 +96,7 @@ def test(): self.assertRaises(AttributeError, test) - def testPrivateProperty(self): + def test_private_property(self): """Test private properties.""" def test(): @@ -114,7 +114,7 @@ def test(): self.assertRaises(AttributeError, test) - def testPropertyDescriptorGetSet(self): + def test_property_descriptor_get_set(self): """Test property descriptor get / set.""" # This test ensures that setting an attribute implemented with @@ -137,7 +137,7 @@ def testPropertyDescriptorGetSet(self): descriptor = PropertyTest.__dict__['PublicStaticProperty'] self.assertTrue(type(descriptor) != int) - def testPropertyDescriptorWrongType(self): + def test_property_descriptor_wrong_type(self): """Test setting a property using a value of the wrong type.""" def test(): @@ -146,7 +146,7 @@ def test(): self.assertTrue(TypeError, test) - def testPropertyDescriptorAbuse(self): + def test_property_descriptor_abuse(self): """Test property descriptor abuse.""" desc = PropertyTest.__dict__['PublicProperty'] @@ -160,7 +160,7 @@ def test(): self.assertRaises(TypeError, test) - def testInterfaceProperty(self): + def test_interface_property(self): """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.""" diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index 444d0a116..a1caa27a9 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -69,7 +69,7 @@ def OnTestEvent(self, value): class SubClassTests(unittest.TestCase): """Test subclassing managed types""" - def testBaseClass(self): + def test_base_class(self): """Test base class managed type""" ob = SubClassTest() self.assertEqual(ob.foo(), "foo") @@ -80,7 +80,7 @@ def testBaseClass(self): self.assertEqual(list(ob.return_list()), ["a", "b", "c"]) self.assertEqual(list(SubClassTest.test_list(ob)), ["a", "b", "c"]) - def testInterface(self): + def test_interface(self): """Test python classes can derive from C# interfaces""" ob = InterfaceTestClass() self.assertEqual(ob.foo(), "InterfaceTestClass") @@ -91,7 +91,7 @@ def testInterface(self): x = TestFunctions.pass_through(ob) self.assertEqual(id(x), id(ob)) - def testDerivedClass(self): + def test_derived_class(self): """Test python class derived from managed type""" ob = DerivedClass() self.assertEqual(ob.foo(), "DerivedClass") @@ -107,7 +107,7 @@ def testDerivedClass(self): x = TestFunctions.pass_through(ob) self.assertEqual(id(x), id(ob)) - def testCreateInstance(self): + def test_create_instance(self): """Test derived instances can be created from managed code""" ob = TestFunctions.create_instance(DerivedClass) self.assertEqual(ob.foo(), "DerivedClass") @@ -128,7 +128,7 @@ def testCreateInstance(self): y = TestFunctions.pass_through(ob2) self.assertEqual(id(y), id(ob2)) - def testEvents(self): + def test_events(self): class EventHandler(object): def handler(self, x, args): self.value = args.value diff --git a/src/tests/test_suite/test_callback.py b/src/tests/test_suite/test_callback.py index 7a5e473be..412a27a66 100644 --- a/src/tests/test_suite/test_callback.py +++ b/src/tests/test_suite/test_callback.py @@ -10,7 +10,7 @@ def simpleDefaultArg(arg='test'): class CallbackTests(unittest.TestCase): """Test that callbacks from C# into python work.""" - def testDefaultForNull(self): + def test_default_for_null(self): """Test that C# can use null for an optional python argument""" from Python.Test import CallbackTest @@ -19,7 +19,7 @@ def testDefaultForNull(self): pythonRetVal = simpleDefaultArg(None) self.assertEquals(retVal, pythonRetVal) - def testDefaultForNone(self): + def test_default_for_none(self): """Test that C# can use no argument for an optional python argument""" from Python.Test import CallbackTest diff --git a/src/tests/test_suite/test_import.py b/src/tests/test_suite/test_import.py index f3ffbc870..baea6d5cf 100644 --- a/src/tests/test_suite/test_import.py +++ b/src/tests/test_suite/test_import.py @@ -6,7 +6,7 @@ class ImportTests(unittest.TestCase): """Test the import statement.""" - def testRelativeMissingImport(self): + def test_relative_missing_import(self): """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""" diff --git a/src/tests/test_suite/test_recursive_types.py b/src/tests/test_suite/test_recursive_types.py index 32bcad26e..a213937a5 100644 --- a/src/tests/test_suite/test_recursive_types.py +++ b/src/tests/test_suite/test_recursive_types.py @@ -6,7 +6,7 @@ class RecursiveTypesTests(unittest.TestCase): """Test if interop with recursive type inheritance works.""" - def testRecursiveTypeCreation(self): + def test_recursive_type_creation(self): """Test that a recursive types don't crash with a StackOverflowException""" from Python.Test import RecursiveInheritance diff --git a/src/tests/test_thread.py b/src/tests/test_thread.py index 5f395d9aa..0f947933a 100644 --- a/src/tests/test_thread.py +++ b/src/tests/test_thread.py @@ -18,7 +18,7 @@ def dprint(msg): class ThreadTests(unittest.TestCase): """Test CLR bridge threading and GIL handling.""" - def testSimpleCallbackToPython(self): + def test_simple_callback_to_python(self): """Test a call to managed code that then calls back into Python.""" from Python.Test import ThreadTest @@ -27,7 +27,7 @@ def testSimpleCallbackToPython(self): self.assertTrue(result == "spam") dprint("thread %s SimpleCallBack ret" % thread.get_ident()) - def testDoubleCallbackToPython(self): + def test_double_callback_to_python(self): """Test a call to managed code that then calls back into Python that then calls managed code that then calls Python again.""" from Python.Test import ThreadTest @@ -37,7 +37,7 @@ def testDoubleCallbackToPython(self): self.assertTrue(result == "spam") dprint("thread %s DoubleCallBack ret" % thread.get_ident()) - def testPythonThreadCallsToCLR(self): + def test_python_thread_calls_to_clr(self): """Test calls by Python-spawned threads into managed code.""" # This test is very likely to hang if something is wrong ;) import System From 04cf0b5ae8842f5af84e874fd723ccf701dcfdda Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 22 Jan 2017 00:13:43 -0700 Subject: [PATCH 041/245] Refactor assertRaises test_exceptions: Add exc_info test & fix Exception nameclash --- src/tests/test_array.py | 324 +++++++--------------------- src/tests/test_class.py | 19 +- src/tests/test_compat.py | 31 +-- src/tests/test_conversion.py | 304 +++++++------------------- src/tests/test_delegate.py | 36 +--- src/tests/test_enum.py | 32 +-- src/tests/test_event.py | 84 ++------ src/tests/test_exceptions.py | 188 +++++++--------- src/tests/test_field.py | 108 +++------- src/tests/test_generic.py | 28 +-- src/tests/test_indexer.py | 200 +++++------------ src/tests/test_interface.py | 18 +- src/tests/test_method.py | 124 +++-------- src/tests/test_module.py | 39 +--- src/tests/test_property.py | 72 ++----- src/tests/test_suite/test_import.py | 4 +- 16 files changed, 443 insertions(+), 1168 deletions(-) diff --git a/src/tests/test_array.py b/src/tests/test_array.py index b12c785e7..a107253c6 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -58,21 +58,17 @@ def test_protected_array(self): def test_internal_array(self): """Test internal arrays.""" - def test(): + with self.assertRaises(AttributeError): ob = Test.InternalArrayTest() items = ob.items - self.assertRaises(AttributeError, test) - def test_private_array(self): """Test private arrays.""" - def test(): + with self.assertRaises(AttributeError): ob = Test.PrivateArrayTest() items = ob.items - self.assertRaises(AttributeError, test) - def test_array_bounds_checking(self): """Test array bounds checking.""" @@ -91,30 +87,22 @@ def test_array_bounds_checking(self): self.assertTrue(items[-2] == 3) self.assertTrue(items[-1] == 4) - def test(): + with self.assertRaises(IndexError): ob = Test.Int32ArrayTest() ob.items[5] - self.assertRaises(IndexError, test) - - def test(): + with self.assertRaises(IndexError): ob = Test.Int32ArrayTest() ob.items[5] = 0 - self.assertRaises(IndexError, test) - - def test(): + with self.assertRaises(IndexError): ob = Test.Int32ArrayTest() items[-6] - self.assertRaises(IndexError, test) - - def test(): + with self.assertRaises(IndexError): ob = Test.Int32ArrayTest() items[-6] = 0 - self.assertRaises(IndexError, test) - def test_array_contains(self): """Test array support for __contains__.""" @@ -151,18 +139,14 @@ def test_boolean_array(self): items[0] = True self.assertTrue(items[0] == True) - def test(): + with self.assertRaises(TypeError): ob = Test.ByteArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.ByteArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_byte_array(self): """Test byte arrays.""" ob = Test.ByteArrayTest() @@ -188,30 +172,22 @@ def test_byte_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(OverflowError): ob = Test.ByteArrayTest() ob.items[0] = max + 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ob = Test.ByteArrayTest() ob.items[0] = min - 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.ByteArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.ByteArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_sbyte_array(self): """Test sbyte arrays.""" ob = Test.SByteArrayTest() @@ -237,30 +213,22 @@ def test_sbyte_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(OverflowError): ob = Test.SByteArrayTest() ob.items[0] = max + 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ob = Test.SByteArrayTest() ob.items[0] = min - 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.SByteArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.SByteArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_char_array(self): """Test char arrays.""" ob = Test.CharArrayTest() @@ -286,18 +254,14 @@ def test_char_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(TypeError): ob = Test.CharArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.CharArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_int16_array(self): """Test Int16 arrays.""" ob = Test.Int16ArrayTest() @@ -323,30 +287,22 @@ def test_int16_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(OverflowError): ob = Test.Int16ArrayTest() ob.items[0] = max + 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ob = Test.Int16ArrayTest() ob.items[0] = min - 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int16ArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int16ArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_int32_array(self): """Test Int32 arrays.""" ob = Test.Int32ArrayTest() @@ -372,30 +328,22 @@ def test_int32_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(OverflowError): ob = Test.Int32ArrayTest() ob.items[0] = max + 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ob = Test.Int32ArrayTest() ob.items[0] = min - 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int32ArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int32ArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_int64_array(self): """Test Int64 arrays.""" ob = Test.Int64ArrayTest() @@ -421,30 +369,22 @@ def test_int64_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(OverflowError): ob = Test.Int64ArrayTest() ob.items[0] = max + 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ob = Test.Int64ArrayTest() ob.items[0] = min - 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int64ArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int64ArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_uint16_array(self): """Test UInt16 arrays.""" ob = Test.UInt16ArrayTest() @@ -470,30 +410,22 @@ def test_uint16_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(OverflowError): ob = Test.UInt16ArrayTest() ob.items[0] = max + 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ob = Test.UInt16ArrayTest() ob.items[0] = min - 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.UInt16ArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.UInt16ArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_uint32_array(self): """Test UInt32 arrays.""" ob = Test.UInt32ArrayTest() @@ -519,30 +451,22 @@ def test_uint32_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(OverflowError): ob = Test.UInt32ArrayTest() ob.items[0] = max + 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ob = Test.UInt32ArrayTest() ob.items[0] = min - 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.UInt32ArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.UInt32ArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_uint64_array(self): """Test UInt64 arrays.""" ob = Test.UInt64ArrayTest() @@ -568,30 +492,22 @@ def test_uint64_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(OverflowError): ob = Test.UInt64ArrayTest() ob.items[0] = max + 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ob = Test.UInt64ArrayTest() ob.items[0] = min - 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.UInt64ArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.UInt64ArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_single_array(self): """Test Single arrays.""" ob = Test.SingleArrayTest() @@ -617,18 +533,14 @@ def test_single_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(TypeError): ob = Test.SingleArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.SingleArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_double_array(self): """Test Double arrays.""" ob = Test.DoubleArrayTest() @@ -654,18 +566,14 @@ def test_double_array(self): items[-1] = min self.assertTrue(items[-1] == min) - def test(): + with self.assertRaises(TypeError): ob = Test.DoubleArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.DoubleArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_decimal_array(self): """Test Decimal arrays.""" ob = Test.DecimalArrayTest() @@ -692,18 +600,14 @@ def test_decimal_array(self): items[-1] = min_d self.assertTrue(items[-1] == min_d) - def test(): + with self.assertRaises(TypeError): ob = Test.DecimalArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.DecimalArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_string_array(self): """Test String arrays.""" ob = Test.StringArrayTest() @@ -726,18 +630,14 @@ def test_string_array(self): items[-1] = "eggs" self.assertTrue(items[-1] == "eggs") - def test(): + with self.assertRaises(TypeError): ob = Test.StringArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int64ArrayTest() ob[0] = 0 - self.assertRaises(TypeError, test) - def test_enum_array(self): """Test enum arrays.""" from Python.Test import ShortEnum @@ -761,24 +661,18 @@ def test_enum_array(self): items[-1] = ShortEnum.Zero self.assertTrue(items[-1] == ShortEnum.Zero) - def test(): + with self.assertRaises(ValueError): ob = Test.EnumArrayTest() ob.items[0] = 99 - self.assertRaises(ValueError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.EnumArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.EnumArrayTest() ob[0] = "wrong" - self.assertRaises(TypeError, test) - def test_object_array(self): """Test ob arrays.""" from Python.Test import Spam @@ -808,18 +702,14 @@ def test_object_array(self): items[0] = None self.assertTrue(items[0] == None) - def test(): + with self.assertRaises(TypeError): ob = Test.ObjectArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.ObjectArrayTest() ob.items["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_null_array(self): """Test null arrays.""" ob = Test.NullArrayTest() @@ -845,12 +735,10 @@ def test_null_array(self): empty = ob.empty self.assertTrue(len(empty) == 0) - def test(): + with self.assertRaises(TypeError): ob = Test.NullArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - def test_interface_array(self): """Test interface arrays.""" from Python.Test import Spam @@ -877,24 +765,18 @@ def test_interface_array(self): items[0] = None self.assertTrue(items[0] == None) - def test(): + with self.assertRaises(TypeError): ob = Test.InterfaceArrayTest() ob.items[0] = 99 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.InterfaceArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.InterfaceArrayTest() ob.items["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_typed_array(self): """Test typed arrays.""" from Python.Test import Spam @@ -921,24 +803,18 @@ def test_typed_array(self): items[0] = None self.assertTrue(items[0] == None) - def test(): + with self.assertRaises(TypeError): ob = Test.TypedArrayTest() ob.items[0] = 99 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.TypedArrayTest() v = ob.items["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.TypedArrayTest() ob.items["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_multi_dimensional_array(self): """Test multi-dimensional arrays.""" ob = Test.MultiDimensionalArrayTest() @@ -987,30 +863,22 @@ def test_multi_dimensional_array(self): items[-1, -1] = min self.assertTrue(items[-1, -1] == min) - def test(): + with self.assertRaises(OverflowError): ob = Test.MultiDimensionalArrayTest() ob.items[0, 0] = max + 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ob = Test.MultiDimensionalArrayTest() ob.items[0, 0] = min - 1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.MultiDimensionalArrayTest() v = ob.items["wrong", 0] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.MultiDimensionalArrayTest() ob[0, 0] = "wrong" - self.assertRaises(TypeError, test) - def test_array_iteration(self): """Test array iteration.""" items = Test.Int32ArrayTest().items @@ -1143,22 +1011,16 @@ def test_tuple_array_conversion_type_checking(self): self.assertTrue(result[1] == None) self.assertTrue(len(result) == 10) - def test(items=items): + with self.assertRaises(TypeError): temp = list(items) temp[1] = 1 - result = ArrayConversionTest.EchoRange(tuple(temp)) - self.assertRaises(TypeError, test) - - def test(items=items): + with self.assertRaises(TypeError): temp = list(items) temp[1] = "spam" - result = ArrayConversionTest.EchoRange(tuple(temp)) - self.assertRaises(TypeError, test) - def test_list_array_conversion_type_checking(self): """Test error handling for list conversion to array arguments.""" from Python.Test import ArrayConversionTest @@ -1178,18 +1040,14 @@ def test_list_array_conversion_type_checking(self): self.assertTrue(result[1] == None) self.assertTrue(len(result) == 10) - def test(items=items): + with self.assertRaises(TypeError): items[1] = 1 result = ArrayConversionTest.EchoRange(items) - self.assertRaises(TypeError, test) - - def test(items=items): + with self.assertRaises(TypeError): items[1] = "spam" result = ArrayConversionTest.EchoRange(items) - self.assertRaises(TypeError, test) - def test_sequence_array_conversion_type_checking(self): """Test error handling for sequence conversion to array arguments.""" from Python.Test import ArrayConversionTest @@ -1209,18 +1067,14 @@ def test_sequence_array_conversion_type_checking(self): self.assertTrue(result[1] == None) self.assertTrue(len(result) == 10) - def test(items=items): + with self.assertRaises(TypeError): items[1] = 1 result = ArrayConversionTest.EchoRange(items) - self.assertRaises(TypeError, test) - - def test(items=items): + with self.assertRaises(TypeError): items[1] = "spam" result = ArrayConversionTest.EchoRange(items) - self.assertRaises(TypeError, test) - def test_md_array_conversion(self): """Test passing of multi-dimensional array arguments.""" from Python.Test import ArrayConversionTest @@ -1263,7 +1117,7 @@ def test_boxed_value_type_mutation_result(self): items[i] = Point(i, i) for i in range(5): - # Boxed items, so settr will not change the array member. + # Boxed items, so set_attr will not change the array member. self.assertTrue(items[i].X == i) self.assertTrue(items[i].Y == i) items[i].X = i + 1 @@ -1421,48 +1275,32 @@ def test_array_abuse(self): _class = Test.PublicArrayTest ob = Test.PublicArrayTest() - def test(): + with self.assertRaises(AttributeError): del _class.__getitem__ - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del ob.__getitem__ - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del _class.__setitem__ - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del ob.__setitem__ - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(TypeError): Test.PublicArrayTest.__getitem__(0, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): Test.PublicArrayTest.__setitem__(0, 0, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): desc = Test.PublicArrayTest.__dict__['__getitem__'] desc(0, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): desc = Test.PublicArrayTest.__dict__['__setitem__'] desc(0, 0, 0) - self.assertRaises(TypeError, test) - def test_suite(): return unittest.makeSuite(ArrayTests) diff --git a/src/tests/test_class.py b/src/tests/test_class.py index 02d5f1efc..373bb326d 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -59,17 +59,12 @@ def test_class_default_repr(self): def test_non_public_class(self): """Test that non-public classes are inaccessible.""" - - def test(): + with self.assertRaises(ImportError): from Python.Test import InternalClass - self.assertRaises(ImportError, test) - - def test(): + with self.assertRaises(AttributeError): x = Test.InternalClass - self.assertRaises(AttributeError, test) - def test_basic_subclass(self): """Test basic subclass of a managed class.""" from System.Collections import Hashtable @@ -256,13 +251,17 @@ def test_comparisons(self): self.assertEqual(d2 >= d1, True) self.assertEqual(d2 > d1, True) - self.assertRaises(TypeError, lambda: d1 < None) - self.assertRaises(TypeError, lambda: d1 < System.Guid()) + with self.assertRaises(TypeError): + d1 < None + + with self.assertRaises(TypeError): + d1 < System.Guid() # ClassTest does not implement IComparable c1 = ClassTest() c2 = ClassTest() - self.assertRaises(TypeError, lambda: c1 < c2) + with self.assertRaises(TypeError): + c1 < c2 def test_self_callback(self): """Test calling back and forth between this and a c# baseclass.""" diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index 6eaf752c9..6570f2c1c 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -182,17 +182,13 @@ def test_implicit_load_already_valid_namespace(self): self.assertTrue(isCLRClass(CLR.System.UriBuilder)) def test_import_non_existant_module(self): - """Test import failure for a non-existant module.""" - - def test(): + """Test import failure for a non-existent module.""" + with self.assertRaises(ImportError): import System.SpamSpamSpam - def testclr(): + with self.assertRaises(ImportError): import CLR.System.SpamSpamSpam - self.assertRaises(ImportError, test) - self.assertRaises(ImportError, testclr) - def test_lookup_no_namespace_type(self): """Test lookup of types without a qualified namespace.""" import CLR.Python.Test @@ -201,18 +197,13 @@ def test_lookup_no_namespace_type(self): def test_module_lookup_recursion(self): """Test for recursive lookup handling.""" - - def test1(): + with self.assertRaises(ImportError): from CLR import CLR - self.assertRaises(ImportError, test1) - - def test2(): + with self.assertRaises(AttributeError): import CLR x = CLR.CLR - self.assertRaises(AttributeError, test2) - def test_module_get_attr(self): """Test module getattr behavior.""" import CLR.System as System @@ -223,20 +214,16 @@ def test_module_get_attr(self): module = System.Xml self.assertTrue(isCLRModule(module)) - def test(): + with self.assertRaises(AttributeError): spam = System.Spam - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(TypeError): spam = getattr(System, 1) - self.assertRaises(TypeError, test) - - def test000_multiple_imports(self): + def test_multiple_imports(self): # import CLR did raise a Seg Fault once # test if the Exceptions.warn() method still causes it - for n in range(100): + for _ in range(100): import CLR diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index a63e0793d..7423e2201 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -83,36 +83,24 @@ def test_sbyte_conversion(self): ob.SByteField = System.SByte(-128) self.assertTrue(ob.SByteField == -128) - def test(): + with self.assertRaises(TypeError): ConversionTest().SByteField = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().SByteField = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().SByteField = 128 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().SByteField = -129 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.SByte(128) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.SByte(-129) - self.assertRaises(OverflowError, test) - def test_byte_conversion(self): """Test byte conversion.""" self.assertTrue(System.Byte.MaxValue == 255) @@ -133,36 +121,24 @@ def test_byte_conversion(self): ob.ByteField = System.Byte(0) self.assertTrue(ob.ByteField == 0) - def test(): + with self.assertRaises(TypeError): ConversionTest().ByteField = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().ByteField = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().ByteField = 256 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().ByteField = -1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Byte(256) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Byte(-1) - self.assertRaises(OverflowError, test) - def test_char_conversion(self): """Test char conversion.""" self.assertTrue(System.Char.MaxValue == unichr(65535)) @@ -180,21 +156,15 @@ def test_char_conversion(self): ob.CharField = 67 self.assertTrue(ob.CharField == u'C') - def test(): + with self.assertRaises(OverflowError): ConversionTest().CharField = 65536 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().CharField = -1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().CharField = None - self.assertRaises(TypeError, test) - def test_int16_conversion(self): """Test int16 conversion.""" self.assertTrue(System.Int16.MaxValue == 32767) @@ -215,36 +185,24 @@ def test_int16_conversion(self): ob.Int16Field = System.Int16(-32768) self.assertTrue(ob.Int16Field == -32768) - def test(): + with self.assertRaises(TypeError): ConversionTest().Int16Field = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().Int16Field = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().Int16Field = 32768 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().Int16Field = -32769 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Int16(32768) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Int16(-32769) - self.assertRaises(OverflowError, test) - def test_int32_conversion(self): """Test int32 conversion.""" self.assertTrue(System.Int32.MaxValue == 2147483647) @@ -265,36 +223,24 @@ def test_int32_conversion(self): ob.Int32Field = System.Int32(-2147483648) self.assertTrue(ob.Int32Field == -2147483648) - def test(): + with self.assertRaises(TypeError): ConversionTest().Int32Field = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().Int32Field = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().Int32Field = 2147483648 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().Int32Field = -2147483649 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Int32(2147483648) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Int32(-2147483649) - self.assertRaises(OverflowError, test) - def test_int64_conversion(self): """Test int64 conversion.""" self.assertTrue(System.Int64.MaxValue == long(9223372036854775807)) @@ -315,36 +261,24 @@ def test_int64_conversion(self): ob.Int64Field = System.Int64(long(-9223372036854775808)) self.assertTrue(ob.Int64Field == long(-9223372036854775808)) - def test(): + with self.assertRaises(TypeError): ConversionTest().Int64Field = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().Int64Field = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().Int64Field = long(9223372036854775808) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().Int64Field = long(-9223372036854775809) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Int64(long(9223372036854775808)) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Int64(long(-9223372036854775809)) - self.assertRaises(OverflowError, test) - def test_uint16_conversion(self): """Test uint16 conversion.""" self.assertTrue(System.UInt16.MaxValue == 65535) @@ -365,36 +299,24 @@ def test_uint16_conversion(self): ob.UInt16Field = System.UInt16(0) self.assertTrue(ob.UInt16Field == 0) - def test(): + with self.assertRaises(TypeError): ConversionTest().UInt16Field = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().UInt16Field = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().UInt16Field = 65536 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().UInt16Field = -1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.UInt16(65536) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.UInt16(-1) - self.assertRaises(OverflowError, test) - def test_uint32_conversion(self): """Test uint32 conversion.""" self.assertTrue(System.UInt32.MaxValue == long(4294967295)) @@ -415,36 +337,24 @@ def test_uint32_conversion(self): ob.UInt32Field = System.UInt32(0) self.assertTrue(ob.UInt32Field == 0) - def test(): + with self.assertRaises(TypeError): ConversionTest().UInt32Field = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().UInt32Field = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().UInt32Field = long(4294967296) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().UInt32Field = -1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.UInt32(long(4294967296)) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.UInt32(-1) - self.assertRaises(OverflowError, test) - def test_uint64_conversion(self): """Test uint64 conversion.""" self.assertTrue(System.UInt64.MaxValue == long(18446744073709551615)) @@ -465,36 +375,24 @@ def test_uint64_conversion(self): ob.UInt64Field = System.UInt64(0) self.assertTrue(ob.UInt64Field == 0) - def test(): + with self.assertRaises(TypeError): ConversionTest().UInt64Field = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().UInt64Field = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().UInt64Field = long(18446744073709551616) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().UInt64Field = -1 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.UInt64(long(18446744073709551616)) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.UInt64(-1) - self.assertRaises(OverflowError, test) - def test_single_conversion(self): """Test single conversion.""" self.assertTrue(System.Single.MaxValue == 3.402823e38) @@ -515,36 +413,24 @@ def test_single_conversion(self): ob.SingleField = System.Single(-3.402823e38) self.assertTrue(ob.SingleField == -3.402823e38) - def test(): + with self.assertRaises(TypeError): ConversionTest().SingleField = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().SingleField = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().SingleField = 3.402824e38 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().SingleField = -3.402824e38 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Single(3.402824e38) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Single(-3.402824e38) - self.assertRaises(OverflowError, test) - def test_double_conversion(self): """Test double conversion.""" self.assertTrue(System.Double.MaxValue == 1.7976931348623157e308) @@ -565,36 +451,24 @@ def test_double_conversion(self): ob.DoubleField = System.Double(-1.7976931348623157e308) self.assertTrue(ob.DoubleField == -1.7976931348623157e308) - def test(): + with self.assertRaises(TypeError): ConversionTest().DoubleField = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().DoubleField = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().DoubleField = 1.7976931348623159e308 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): ConversionTest().DoubleField = -1.7976931348623159e308 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Double(1.7976931348623159e308) - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(OverflowError): value = System.Double(-1.7976931348623159e308) - self.assertRaises(OverflowError, test) - def test_decimal_conversion(self): """Test decimal conversion.""" from System import Decimal @@ -622,21 +496,15 @@ def test_decimal_conversion(self): ob.DecimalField = min_d self.assertTrue(ob.DecimalField == min_d) - def test(): + with self.assertRaises(TypeError): ConversionTest().DecimalField = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().DecimalField = "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().DecimalField = 1 - self.assertRaises(TypeError, test) - def test_string_conversion(self): """Test string / unicode conversion.""" ob = ConversionTest() @@ -665,11 +533,9 @@ def test_string_conversion(self): ob.StringField = None self.assertTrue(ob.StringField == None) - def test(): + with self.assertRaises(TypeError): ConversionTest().StringField = 1 - self.assertRaises(TypeError, test) - def test_interface_conversion(self): """Test interface conversion.""" from Python.Test import Spam, ISpam @@ -688,18 +554,14 @@ def test_interface_conversion(self): ob.SpamField = None self.assertTrue(ob.SpamField == None) - def test(): + with self.assertRaises(TypeError): ob = ConversionTest() ob.SpamField = System.String("bad") - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = ConversionTest() ob.SpamField = System.Int32(1) - self.assertRaises(TypeError, test) - def test_object_conversion(self): """Test ob conversion.""" from Python.Test import Spam @@ -722,12 +584,10 @@ def test_object_conversion(self): # need to test subclass here - def test(): + with self.assertRaises(TypeError): ob = ConversionTest() ob.ObjectField = self - self.assertRaises(TypeError, test) - def test_enum_conversion(self): """Test enum conversion.""" from Python.Test import ShortEnum @@ -746,30 +606,22 @@ def test_enum_conversion(self): self.assertTrue(ob.EnumField == ShortEnum.One) self.assertTrue(ob.EnumField == 1) - def test(): + with self.assertRaises(ValueError): ob = ConversionTest() ob.EnumField = 10 - self.assertRaises(ValueError, test) - - def test(): + with self.assertRaises(ValueError): ob = ConversionTest() ob.EnumField = 255 - self.assertRaises(ValueError, test) - - def test(): + with self.assertRaises(OverflowError): ob = ConversionTest() ob.EnumField = 1000000 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): ob = ConversionTest() ob.EnumField = "spam" - self.assertRaises(TypeError, test) - def test_null_conversion(self): """Test null conversion.""" ob = ConversionTest() @@ -785,16 +637,12 @@ def test_null_conversion(self): # Primitive types and enums should not be set to null. - def test(): + with self.assertRaises(TypeError): ConversionTest().Int32Field = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ConversionTest().EnumField = None - self.assertRaises(TypeError, test) - def test_byte_array_conversion(self): """Test byte array conversion.""" ob = ConversionTest() diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index 37203e77d..0c51c2937 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -30,16 +30,12 @@ def test_global_delegate_visibility(self): self.assertTrue(PublicDelegate.__name__ == 'PublicDelegate') self.assertTrue(Test.PublicDelegate.__name__ == 'PublicDelegate') - def test(): + with self.assertRaises(ImportError): from Python.Test import InternalDelegate - self.assertRaises(ImportError, test) - - def test(): + with self.assertRaises(AttributeError): i = Test.InternalDelegate - self.assertRaises(AttributeError, test) - def test_nested_delegate_visibility(self): """Test visibility of nested delegates.""" ob = DelegateTest.PublicDelegate @@ -48,16 +44,12 @@ def test_nested_delegate_visibility(self): ob = DelegateTest.ProtectedDelegate self.assertTrue(ob.__name__ == 'ProtectedDelegate') - def test(): + with self.assertRaises(AttributeError): ob = DelegateTest.InternalDelegate - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): ob = DelegateTest.PrivateDelegate - self.assertRaises(AttributeError, test) - def test_delegate_from_function(self): """Test delegate implemented with a Python function.""" @@ -88,12 +80,10 @@ def test_delegate_from_method(self): def test_delegate_from_unbound_method(self): """Test failure mode for unbound methods.""" - def test(): + with self.assertRaises(TypeError): d = StringDelegate(HelloClass.hello) d() - self.assertRaises(TypeError, test) - def test_delegate_from_static_method(self): """Test delegate implemented with a Python static method.""" @@ -196,21 +186,15 @@ def test_delegate_from_delegate(self): def test_delegate_with_invalid_args(self): """Test delegate instantiation with invalid (non-callable) args.""" - def test(): + with self.assertRaises(TypeError): d = StringDelegate(None) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): d = StringDelegate("spam") - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): d = StringDelegate(1) - self.assertRaises(TypeError, test) - def test_multicast_delegate(self): """Test multicast delegates.""" @@ -231,12 +215,10 @@ def test_subclass_delegate_fails(self): """Test that subclassing of a delegate type fails.""" from Python.Test import PublicDelegate - def test(): + with self.assertRaises(TypeError): class Boom(PublicDelegate): pass - self.assertRaises(TypeError, test) - def test_delegate_equality(self): """Test delegate equality.""" diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index 6f6097029..170a47fd1 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -83,46 +83,36 @@ def test_instantiate_enum_fails(self): """Test that instantiation of an enum class fails.""" from System import DayOfWeek - def test(): + with self.assertRaises(TypeError): ob = DayOfWeek() - self.assertRaises(TypeError, test) - def test_subclass_enum_fails(self): """Test that subclassing of an enumeration fails.""" from System import DayOfWeek - def test(): + with self.assertRaises(TypeError): class Boom(DayOfWeek): pass - self.assertRaises(TypeError, test) - def test_enum_set_member_fails(self): """Test that setattr operations on enumerations fail.""" from System import DayOfWeek - def test(): + with self.assertRaises(TypeError): DayOfWeek.Sunday = 13 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del DayOfWeek.Sunday - self.assertRaises(TypeError, test) - def test_enum_with_flags_attr_conversion(self): """Test enumeration conversion with FlagsAttribute set.""" # This works because the FlagsField enum has FlagsAttribute. Test.FieldTest().FlagsField = 99 # This should fail because our test enum doesn't have it. - def test(): + with self.assertRaises(ValueError): Test.FieldTest().EnumField = 99 - self.assertRaises(ValueError, test) - def test_enum_conversion(self): """Test enumeration conversion.""" ob = Test.FieldTest() @@ -131,21 +121,15 @@ def test_enum_conversion(self): ob.EnumField = Test.ShortEnum.One self.assertTrue(ob.EnumField == 1) - def test(): + with self.assertRaises(ValueError): Test.FieldTest().EnumField = 20 - self.assertRaises(ValueError, test) - - def test(): + with self.assertRaises(OverflowError): Test.FieldTest().EnumField = 100000 - self.assertRaises(OverflowError, test) - - def test(): + with self.assertRaises(TypeError): Test.FieldTest().EnumField = "str" - self.assertRaises(TypeError, test) - def test_suite(): return unittest.makeSuite(EnumTests) diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 84a495430..64ecc615c 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -68,39 +68,27 @@ def test_protected_static_event(self): def test_internal_events(self): """Test internal events.""" - def test(): + with self.assertRaises(AttributeError): f = EventTest().InternalEvent - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = EventTest().InternalStaticEvent - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = EventTest.InternalStaticEvent - self.assertRaises(AttributeError, test) - def test_private_events(self): """Test private events.""" - def test(): + with self.assertRaises(AttributeError): f = EventTest().PrivateEvent - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = EventTest().PrivateStaticEvent - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = EventTest.PrivateStaticEvent - self.assertRaises(AttributeError, test) - def test_multicast_event(self): """Test multicast events.""" ob = EventTest() @@ -301,27 +289,21 @@ def handler(sender, args, dict=dict): def test_add_non_callable_handler(self): """Test handling of attempts to add non-callable handlers.""" - def test(): + with self.assertRaises(TypeError): ob = EventTest() ob.PublicEvent += 10 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = EventTest() ob.PublicEvent += "spam" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): class spam(object): pass ob = EventTest() ob.PublicEvent += spam() - self.assertRaises(TypeError, test) - def test_remove_multiple_handlers(self): """Test removing multiple instances of the same handler.""" ob = EventTest() @@ -478,14 +460,12 @@ def h(sender, args): def test_remove_unknown_handler(self): """Test removing an event handler that was never added.""" - def test(): + with self.assertRaises(ValueError): ob = EventTest() handler = GenericHandler() ob.PublicEvent -= handler.handler - self.assertRaises(ValueError, test) - def test_handler_callback_failure(self): """Test failure mode for inappropriate handlers.""" @@ -496,12 +476,10 @@ def handler(self, one): ob = EventTest() handler = BadHandler() - def test(): + with self.assertRaises(TypeError): ob.PublicEvent += handler.handler ob.OnPublicEvent(TestEventArgs(10)) - self.assertRaises(TypeError, test) - ob.PublicEvent -= handler.handler class BadHandler(object): @@ -511,12 +489,10 @@ def handler(self, one, two, three, four, five): ob = EventTest() handler = BadHandler() - def test(): + with self.assertRaises(TypeError): ob.PublicEvent += handler.handler ob.OnPublicEvent(TestEventArgs(10)) - self.assertRaises(TypeError, test) - ob.PublicEvent -= handler.handler def test_incorrect_invokation(self): @@ -526,16 +502,12 @@ def test_incorrect_invokation(self): handler = GenericHandler() ob.PublicEvent += handler.handler - def test(): + with self.assertRaises(TypeError): ob.OnPublicEvent() - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob.OnPublicEvent(32) - self.assertRaises(TypeError, test) - ob.PublicEvent -= handler.handler def test_explicit_cls_event_registration(self): @@ -561,49 +533,35 @@ def test_explicit_cls_event_registration(self): def test_implicit_cls_event_registration(self): """Test implicit CLS event registration.""" - def test(): + with self.assertRaises(TypeError): ob = EventTest() handler = GenericHandler() ob.add_PublicEvent(handler.handler) - self.assertRaises(TypeError, test) - def test_event_descriptor_abuse(self): """Test event descriptor abuse.""" - def test(): + with self.assertRaises(TypeError): del EventTest.PublicEvent - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del EventTest.__dict__['PublicEvent'] - self.assertRaises(TypeError, test) - desc = EventTest.__dict__['PublicEvent'] - def test(): + with self.assertRaises(TypeError): desc.__get__(0, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): desc.__set__(0, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = EventTest() ob.PublicEvent = 0 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): EventTest.PublicStaticEvent = 0 - self.assertRaises(TypeError, test) - def test_suite(): return unittest.makeSuite(EventTests) diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index ffd9445eb..aeec1fee3 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -61,95 +61,84 @@ def test_raise_class_exception(self): """Test class exception propagation.""" from System import NullReferenceException - def test(): + with self.assertRaises(NullReferenceException) as cm: raise NullReferenceException - self.assertRaises(NullReferenceException, test) + exc = cm.exception + self.assertTrue(isinstance(exc, NullReferenceException)) + def test_exc_info(self): + """Test class exception propagation. + Behavior of exc_info changed in Py3. Refactoring its test""" + from System import NullReferenceException try: - raise NullReferenceException - except: - type, value, tb = sys.exc_info() - self.assertTrue(type is NullReferenceException) - self.assertTrue(isinstance(value, NullReferenceException)) + raise NullReferenceException("message") + except Exception as exc: + type_, value, tb = sys.exc_info() + self.assertTrue(type_ is NullReferenceException) + self.assertTrue(value.Message == "message") + self.assertTrue(exc.Message == "message") + # FIXME: Lower-case message isn't implemented + # self.assertTrue(exc.message == "message") + self.assertTrue(value is exc) def test_raise_class_exception_with_value(self): """Test class exception propagation with associated value.""" from System import NullReferenceException - def test(): + with self.assertRaises(NullReferenceException) as cm: raise NullReferenceException('Aiiieee!') - self.assertRaises(NullReferenceException, test) - - try: - raise NullReferenceException('Aiiieee!') - except: - type, value, tb = sys.exc_info() - self.assertTrue(type is NullReferenceException) - self.assertTrue(isinstance(value, NullReferenceException)) - self.assertTrue(value.Message == 'Aiiieee!') + exc = cm.exception + self.assertTrue(isinstance(exc, NullReferenceException)) + self.assertTrue(exc.Message == 'Aiiieee!') def test_raise_instance_exception(self): """Test instance exception propagation.""" from System import NullReferenceException - def test(): + with self.assertRaises(NullReferenceException) as cm: raise NullReferenceException() - self.assertRaises(NullReferenceException, test) - - try: - raise NullReferenceException() - except: - type, value, tb = sys.exc_info() - self.assertTrue(type is NullReferenceException) - self.assertTrue(isinstance(value, NullReferenceException)) - self.assertTrue(len(value.Message) > 0) + exc = cm.exception + self.assertTrue(isinstance(exc, NullReferenceException)) + self.assertTrue(len(exc.Message) > 0) def test_raise_instance_exception_with_args(self): """Test instance exception propagation with args.""" from System import NullReferenceException - def test(): - raise NullReferenceException("Aiieeee!") - - self.assertRaises(NullReferenceException, test) + with self.assertRaises(NullReferenceException) as cm: + raise NullReferenceException("Aiiieee!") - try: - raise NullReferenceException('Aiiieee!') - except: - type, value, tb = sys.exc_info() - self.assertTrue(type is NullReferenceException) - self.assertTrue(isinstance(value, NullReferenceException)) - self.assertTrue(value.Message == 'Aiiieee!') + exc = cm.exception + self.assertTrue(isinstance(exc, NullReferenceException)) + self.assertTrue(exc.Message == 'Aiiieee!') def test_managed_exception_propagation(self): """Test propagation of exceptions raised in managed code.""" from System import Decimal, OverflowException - def test(): - l = Decimal.ToInt64(Decimal.MaxValue) - - self.assertRaises(OverflowException, test) + with self.assertRaises(OverflowException): + Decimal.ToInt64(Decimal.MaxValue) def test_managed_exception_conversion(self): """Test conversion of managed exceptions.""" - from System import Exception, OverflowException + from System import OverflowException from Python.Test import ExceptionTest e = ExceptionTest.GetBaseException() - self.assertTrue(isinstance(e, Exception)) + self.assertTrue(isinstance(e, System.Exception)) e = ExceptionTest.GetExplicitException() self.assertTrue(isinstance(e, OverflowException)) - self.assertTrue(isinstance(e, Exception)) + self.assertTrue(isinstance(e, System.Exception)) e = ExceptionTest.GetWidenedException() self.assertTrue(isinstance(e, OverflowException)) - self.assertTrue(isinstance(e, Exception)) + self.assertTrue(isinstance(e, System.Exception)) - v = ExceptionTest.SetBaseException(Exception('error')) + v = ExceptionTest.SetBaseException(System.Exception('error')) self.assertTrue(v) v = ExceptionTest.SetExplicitException(OverflowException('error')) @@ -163,93 +152,66 @@ def test_catch_exception_from_managed_method(self): from Python.Test import ExceptionTest from System import OverflowException - try: + with self.assertRaises(OverflowException) as cm: ExceptionTest().ThrowException() - except OverflowException: - e = sys.exc_info()[1] - self.assertTrue(isinstance(e, OverflowException)) - return - raise SystemError('failed to catch exception from managed method') + e = cm.exception + self.assertTrue(isinstance(e, OverflowException)) def test_catch_exception_from_managed_property(self): """Test catching an exception from a managed property.""" from Python.Test import ExceptionTest from System import OverflowException - try: - v = ExceptionTest().ThrowProperty - except OverflowException: - e = sys.exc_info()[1] - self.assertTrue(isinstance(e, OverflowException)) - return + with self.assertRaises(OverflowException) as cm: + _ = ExceptionTest().ThrowProperty - try: + e = cm.exception + self.assertTrue(isinstance(e, OverflowException)) + + with self.assertRaises(OverflowException) as cm: ExceptionTest().ThrowProperty = 1 - except OverflowException: - e = sys.exc_info()[1] - self.assertTrue(isinstance(e, OverflowException)) - return - raise SystemError('failed to catch exception from managed property') + e = cm.exception + self.assertTrue(isinstance(e, OverflowException)) def test_catch_exception_managed_class(self): """Test catching the managed class of an exception.""" from System import OverflowException - try: + with self.assertRaises(OverflowException): raise OverflowException('overflow') - except OverflowException: - return - - raise SystemError('failed to catch managed class exception') def test_catch_exception_python_class(self): """Test catching the python class of an exception.""" from System import OverflowException - if PY3: - from builtins import Exception - elif PY2: - from exceptions import Exception - try: + with self.assertRaises(Exception): raise OverflowException('overflow') - except Exception: - return - - raise SystemError('failed to catch python class exception') def test_catch_exception_base_class(self): """Test catching the base of an exception.""" from System import OverflowException, ArithmeticException - try: + with self.assertRaises(ArithmeticException): raise OverflowException('overflow') - except ArithmeticException: - return - - raise SystemError('failed to catch base exception') def test_catch_exception_nested_base_class(self): """Test catching the nested base of an exception.""" from System import OverflowException, SystemException - try: + with self.assertRaises(SystemException): raise OverflowException('overflow') - except SystemException: - return - - raise SystemError('failed to catch nested base exception') def test_catch_exception_with_assignment(self): """Test catching an exception with assignment.""" from System import OverflowException - try: + with self.assertRaises(OverflowException) as cm: raise OverflowException('overflow') - except OverflowException: - e = sys.exc_info()[1] - self.assertTrue(isinstance(e, OverflowException)) + + e = cm.exception + self.assertTrue(isinstance(e, OverflowException)) def test_catch_exception_unqualified(self): """Test catching an unqualified exception.""" @@ -259,14 +221,21 @@ def test_catch_exception_unqualified(self): raise OverflowException('overflow') except: return + else: + self.fail("failed to catch unqualified exception") + + def test_catch_baseexception(self): + """Test catching an unqualified exception with BaseException.""" + from System import OverflowException - raise SystemError('failed to catch unqualified exception') + with self.assertRaises(BaseException): + raise OverflowException('overflow') def test_apparent_module_of_exception(self): """Test the apparent module of an exception.""" - from System import Exception, OverflowException + from System import OverflowException - self.assertTrue(Exception.__module__ == 'System') + self.assertTrue(System.Exception.__module__ == 'System') self.assertTrue(OverflowException.__module__ == 'System') def test_str_of_exception(self): @@ -283,14 +252,15 @@ def test_str_of_exception(self): Convert.ToDateTime('this will fail') except FormatException: e = sys.exc_info()[1] - msg = text_type(e).encode("utf8") # fix for international installation - self.assertTrue(msg.find(text_type('System.Convert.ToDateTime').encode("utf8")) > -1, msg) + # fix for international installation + msg = text_type(e).encode("utf8") + fnd = text_type('System.Convert.ToDateTime').encode("utf8") + self.assertTrue(msg.find(fnd) > -1, msg) def test_python_compat_of_managed_exceptions(self): - """Test if managed exceptions are compatible with Python's implementation - """ + """Test managed exceptions compatible with Python's implementation""" from System import OverflowException - msg = "A simple message" + msg = "Simple message" e = OverflowException(msg) self.assertEqual(str(e), msg) @@ -299,9 +269,9 @@ def test_python_compat_of_managed_exceptions(self): self.assertEqual(e.args, (msg,)) self.assertTrue(isinstance(e.args, tuple)) if PY3: - self.assertEqual(repr(e), "OverflowException('A simple message',)") + self.assertEqual(repr(e), "OverflowException('Simple message',)") elif PY2: - self.assertEqual(repr(e), "OverflowException(u'A simple message',)") + self.assertEqual(repr(e), "OverflowException(u'Simple message',)") def test_exception_is_instance_of_system_object(self): """Test behavior of isinstance(, System.Object).""" @@ -338,24 +308,20 @@ def test_pickling_exceptions(self): self.assertEqual(exc.args, loaded.args) def test_chained_exceptions(self): - # TODO: Why is this test PY3 only? + # __cause__ is py3 only if PY3: from Python.Test import ExceptionTest try: ExceptionTest.ThrowChainedExceptions() except Exception as exc: - msgs = [ - "Outer exception", - "Inner exception", - "Innermost exception", - ] - + msgs = ("Outer exception", + "Inner exception", + "Innermost exception",) for msg in msgs: self.assertEqual(exc.Message, msg) self.assertEqual(exc.__cause__, exc.InnerException) exc = exc.__cause__ - else: self.fail("Test should raise an exception") diff --git a/src/tests/test_field.py b/src/tests/test_field.py index f3ec8b382..1f2ca87ea 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -17,11 +17,9 @@ def test_public_instance_field(self): ob.PublicField = 1 self.assertTrue(ob.PublicField == 1) - def test(): + with self.assertRaises(TypeError): del FieldTest().PublicField - self.assertRaises(TypeError, test) - def test_public_static_field(self): """Test public static fields.""" ob = FieldTest() @@ -34,16 +32,12 @@ def test_public_static_field(self): ob.PublicStaticField = 0 self.assertTrue(ob.PublicStaticField == 0) - def test(): + with self.assertRaises(TypeError): del FieldTest.PublicStaticField - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del FieldTest().PublicStaticField - self.assertRaises(TypeError, test) - def test_protected_instance_field(self): """Test protected instance fields.""" ob = FieldTest() @@ -52,11 +46,9 @@ def test_protected_instance_field(self): ob.ProtectedField = 1 self.assertTrue(ob.ProtectedField == 1) - def test(): + with self.assertRaises(TypeError): del FieldTest().ProtectedField - self.assertRaises(TypeError, test) - def test_protected_static_field(self): """Test protected static fields.""" ob = FieldTest() @@ -69,30 +61,22 @@ def test_protected_static_field(self): ob.ProtectedStaticField = 0 self.assertTrue(ob.ProtectedStaticField == 0) - def test(): + with self.assertRaises(TypeError): del FieldTest.ProtectedStaticField - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del FieldTest().ProtectedStaticField - self.assertRaises(TypeError, test) - def test_read_only_instance_field(self): """Test readonly instance fields.""" self.assertTrue(FieldTest().ReadOnlyField == 0) - def test(): + with self.assertRaises(TypeError): FieldTest().ReadOnlyField = 1 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del FieldTest().ReadOnlyField - self.assertRaises(TypeError, test) - def test_read_only_static_field(self): """Test readonly static fields.""" ob = FieldTest() @@ -100,26 +84,18 @@ def test_read_only_static_field(self): self.assertTrue(FieldTest.ReadOnlyStaticField == 0) self.assertTrue(ob.ReadOnlyStaticField == 0) - def test(): + with self.assertRaises(TypeError): FieldTest.ReadOnlyStaticField = 1 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): FieldTest().ReadOnlyStaticField = 1 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del FieldTest.ReadOnlyStaticField - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del FieldTest().ReadOnlyStaticField - self.assertRaises(TypeError, test) - def test_constant_field(self): """Test const fields.""" ob = FieldTest() @@ -127,62 +103,42 @@ def test_constant_field(self): self.assertTrue(FieldTest.ConstField == 0) self.assertTrue(ob.ConstField == 0) - def test(): + with self.assertRaises(TypeError): FieldTest().ConstField = 1 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): FieldTest.ConstField = 1 - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del FieldTest().ConstField - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del FieldTest.ConstField - self.assertRaises(TypeError, test) - def test_internal_field(self): """Test internal fields.""" - def test(): + with self.assertRaises(AttributeError): f = FieldTest().InternalField - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = FieldTest().InternalStaticField - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = FieldTest.InternalStaticField - self.assertRaises(AttributeError, test) - def test_private_field(self): """Test private fields.""" - def test(): + with self.assertRaises(AttributeError): f = FieldTest().PrivateField - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = FieldTest().PrivateStaticField - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = FieldTest.PrivateStaticField - self.assertRaises(AttributeError, test) - def test_field_descriptor_get_set(self): """Test field descriptor get / set.""" @@ -209,25 +165,19 @@ def test_field_descriptor_get_set(self): def test_field_descriptor_wrong_type(self): """Test setting a field using a value of the wrong type.""" - def test(): + with self.assertRaises(TypeError): FieldTest().PublicField = "spam" - self.assertRaises(TypeError, test) - def test_field_descriptor_abuse(self): """Test field descriptor abuse.""" desc = FieldTest.__dict__['PublicField'] - def test(): + with self.assertRaises(TypeError): desc.__get__(0, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): desc.__set__(0, 0) - self.assertRaises(TypeError, test) - def test_boolean_field(self): """Test boolean fields.""" # change this to true / false later for Python 2.3? @@ -408,16 +358,12 @@ def test_nullable_field(self): # Primitive types and enums should not be set to null. - def test(): + with self.assertRaises(TypeError): FieldTest().Int32Field = None - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): FieldTest().EnumField = None - self.assertRaises(TypeError, test) - def test_suite(): return unittest.makeSuite(FieldTests) diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index d4c93c060..e85e76667 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -194,16 +194,12 @@ def test_open_generic_type(self): OpenGenericType = DerivedFromOpenGeneric.__bases__[0] - def test(): + with self.assertRaises(TypeError): inst = OpenGenericType() - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): type = OpenGenericType[System.String] - self.assertRaises(TypeError, test) - def test_derived_from_open_generic_type(self): """Test a generic type derived from an open generic type.""" from Python.Test import DerivedFromOpenGeneric @@ -228,11 +224,9 @@ def test_generic_type_name_resolution(self): # If no non-generic type exists for a name, the unadorned name # cannot be instantiated. It can only be used to bind a generic. - def test(): + with self.assertRaises(TypeError): inst = GenericNameTest2() - self.assertRaises(TypeError, test) - _class = GenericNameTest2[int] self.assertTrue(_class().value == 1) self.assertTrue(_class.value == 1) @@ -281,23 +275,19 @@ def test_generic_method_binding(self): value = GenericStaticMethodTest[str].Overloaded() self.assertTrue(value == 1) - def test(): + with self.assertRaises(InvalidOperationException): # Cannot invoke a static member on an open type. GenericStaticMethodTest.Overloaded() - self.assertRaises(InvalidOperationException, test) - # Can invoke an instance member on a closed generic type. value = GenericMethodTest[str]().Overloaded() self.assertTrue(value == 1) - def test(): + with self.assertRaises(TypeError): # Cannot invoke an instance member on an open type, # because the open type cannot be instantiated. GenericMethodTest().Overloaded() - self.assertRaises(TypeError, test) - def test_generic_method_type_handling(self): """Test argument conversion / binding for generic methods.""" from Python.Test import InterfaceTest, ISayHello1, ShortEnum @@ -442,16 +432,12 @@ def test_generic_method_overload_selection(self): value = inst.Overloaded[str](123, 456, "success") self.assertTrue(value == "success") - def test(): + with self.assertRaises(TypeError): value = type.Overloaded[str, bool, int]("true", True, 1) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): value = inst.Overloaded[str, bool, int]("true", True, 1) - self.assertRaises(TypeError, test) - def test_method_overload_selection_with_generic_types(self): """Check method overload selection using generic types.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index daec3d7f7..90a8d71f0 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -38,40 +38,28 @@ def test_internal_indexer(self): """Test internal indexers.""" ob = Test.InternalIndexerTest() - def test(): + with self.assertRaises(TypeError): ob[0] = "zero" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): Test.InternalIndexerTest.__getitem__(ob, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob.__getitem__(0) - self.assertRaises(TypeError, test) - def test_private_indexer(self): """Test private indexers.""" ob = Test.PrivateIndexerTest() - def test(): + with self.assertRaises(TypeError): ob[0] = "zero" - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): Test.PrivateIndexerTest.__getitem__(ob, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob.__getitem__(0) - self.assertRaises(TypeError, test) - def test_boolean_indexer(self): """Test boolean indexers.""" ob = Test.BooleanIndexerTest() @@ -105,18 +93,14 @@ def test_byte_indexer(self): ob[min] = str(min) self.assertTrue(ob[min] == str(min)) - def test(): + with self.assertRaises(TypeError): ob = Test.ByteIndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.ByteIndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_sbyte_indexer(self): """Test sbyte indexers.""" ob = Test.SByteIndexerTest() @@ -131,18 +115,14 @@ def test_sbyte_indexer(self): ob[min] = str(min) self.assertTrue(ob[min] == str(min)) - def test(): + with self.assertRaises(TypeError): ob = Test.SByteIndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.SByteIndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_char_indexer(self): """Test char indexers.""" ob = Test.CharIndexerTest() @@ -157,18 +137,14 @@ def test_char_indexer(self): ob[min] = "min" self.assertTrue(ob[min] == "min") - def test(): + with self.assertRaises(TypeError): ob = Test.CharIndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.CharIndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_int16_indexer(self): """Test Int16 indexers.""" ob = Test.Int16IndexerTest() @@ -183,18 +159,14 @@ def test_int16_indexer(self): ob[min] = str(min) self.assertTrue(ob[min] == str(min)) - def test(): + with self.assertRaises(TypeError): ob = Test.Int16IndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int16IndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_int32_indexer(self): """Test Int32 indexers.""" ob = Test.Int32IndexerTest() @@ -209,18 +181,14 @@ def test_int32_indexer(self): ob[min] = str(min) self.assertTrue(ob[min] == str(min)) - def test(): + with self.assertRaises(TypeError): ob = Test.Int32IndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int32IndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_int64_indexer(self): """Test Int64 indexers.""" ob = Test.Int64IndexerTest() @@ -235,18 +203,14 @@ def test_int64_indexer(self): ob[min] = str(min) self.assertTrue(ob[min] == str(min)) - def test(): + with self.assertRaises(TypeError): ob = Test.Int64IndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.Int64IndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_uint16_indexer(self): """Test UInt16 indexers.""" ob = Test.UInt16IndexerTest() @@ -261,18 +225,14 @@ def test_uint16_indexer(self): ob[min] = str(min) self.assertTrue(ob[min] == str(min)) - def test(): + with self.assertRaises(TypeError): ob = Test.UInt16IndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.UInt16IndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_uint32_indexer(self): """Test UInt32 indexers.""" ob = Test.UInt32IndexerTest() @@ -287,18 +247,14 @@ def test_uint32_indexer(self): ob[min] = str(min) self.assertTrue(ob[min] == str(min)) - def test(): + with self.assertRaises(TypeError): ob = Test.UInt32IndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.UInt32IndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_uint64_indexer(self): """Test UInt64 indexers.""" ob = Test.UInt64IndexerTest() @@ -313,18 +269,14 @@ def test_uint64_indexer(self): ob[min] = str(min) self.assertTrue(ob[min] == str(min)) - def test(): + with self.assertRaises(TypeError): ob = Test.UInt64IndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.UInt64IndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_single_indexer(self): """Test Single indexers.""" ob = Test.SingleIndexerTest() @@ -339,18 +291,14 @@ def test_single_indexer(self): ob[min] = "min" self.assertTrue(ob[min] == "min") - def test(): + with self.assertRaises(TypeError): ob = Test.SingleIndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.SingleIndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_double_indexer(self): """Test Double indexers.""" ob = Test.DoubleIndexerTest() @@ -365,18 +313,14 @@ def test_double_indexer(self): ob[min] = "min" self.assertTrue(ob[min] == "min") - def test(): + with self.assertRaises(TypeError): ob = Test.DoubleIndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.DoubleIndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_decimal_indexer(self): """Test Decimal indexers.""" ob = Test.DecimalIndexerTest() @@ -393,18 +337,14 @@ def test_decimal_indexer(self): ob[min_d] = "min" self.assertTrue(ob[min_d] == "min") - def test(): + with self.assertRaises(TypeError): ob = Test.DecimalIndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.DecimalIndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_string_indexer(self): """Test String indexers.""" ob = Test.StringIndexerTest() @@ -424,18 +364,14 @@ def test_string_indexer(self): self.assertTrue(ob[u"eggs"] == "eggs") self.assertTrue(ob[u"eggs"] == u"eggs") - def test(): + with self.assertRaises(TypeError): ob = Test.StringIndexerTest() ob[1] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.StringIndexerTest() ob[1] = "wrong" - self.assertRaises(TypeError, test) - def test_enum_indexer(self): """Test enum indexers.""" ob = Test.EnumIndexerTest() @@ -453,18 +389,14 @@ def test_enum_indexer(self): ob[1] = "spam" self.assertTrue(ob[1] == "spam") - def test(): + with self.assertRaises(TypeError): ob = Test.EnumIndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.EnumIndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_object_indexer(self): """Test ob indexers.""" ob = Test.ObjectIndexerTest() @@ -489,7 +421,7 @@ def test_object_indexer(self): ob[long(1)] = "long" self.assertTrue(ob[long(1)] == "long") - def test(): + with self.assertRaises(TypeError): class eggs(object): pass @@ -497,8 +429,6 @@ class eggs(object): ob = Test.ObjectIndexerTest() ob[key] = "wrong" - self.assertRaises(TypeError, test) - def test_interface_indexer(self): """Test interface indexers.""" ob = Test.InterfaceIndexerTest() @@ -514,18 +444,14 @@ def test_interface_indexer(self): ob[spam] = "eggs" self.assertTrue(ob[spam] == "eggs") - def test(): + with self.assertRaises(TypeError): ob = Test.InterfaceIndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.InterfaceIndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_typed_indexer(self): """Test typed indexers.""" ob = Test.TypedIndexerTest() @@ -541,18 +467,14 @@ def test_typed_indexer(self): ob[spam] = "eggs" self.assertTrue(ob[spam] == "eggs") - def test(): + with self.assertRaises(TypeError): ob = Test.TypedIndexerTest() ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.TypedIndexerTest() ob["wrong"] = "wrong" - self.assertRaises(TypeError, test) - def test_multi_arg_indexer(self): """Test indexers that take multiple index arguments.""" ob = Test.MultiArgIndexerTest() @@ -565,18 +487,14 @@ def test_multi_arg_indexer(self): self.assertTrue(ob[10, 50] == None) - def test(): + with self.assertRaises(TypeError): ob = Test.MultiArgIndexerTest() v = ob[0, "one"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.MultiArgIndexerTest() ob[0, "one"] = "wrong" - self.assertRaises(TypeError, test) - def test_multi_type_indexer(self): """Test indexers that take multiple indices of different types.""" ob = Test.MultiTypeIndexerTest() @@ -588,18 +506,14 @@ def test_multi_type_indexer(self): ob[1, "nine", spam] = "one nine spam" self.assertTrue(ob[1, "nine", spam] == "one nine spam") - def test(): + with self.assertRaises(TypeError): ob = Test.MultiTypeIndexerTest() v = ob[0, 1, spam] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.MultiTypeIndexerTest() ob[0, 1, spam] = "wrong" - self.assertRaises(TypeError, test) - def test_multi_default_key_indexer(self): """Test indexers that take multiple indices with a default key arguments.""" # default argument is 2 in the MultiDefaultKeyIndexerTest object @@ -613,27 +527,21 @@ def test_multi_default_key_indexer(self): def test_indexer_wrong_key_type(self): """Test calling an indexer using a key of the wrong type.""" - def test(): + with self.assertRaises(TypeError): ob = Test.PublicIndexerTest() v = ob["wrong"] - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): ob = Test.PublicIndexerTest() ob["wrong"] = "spam" - self.assertRaises(TypeError, test) - def test_indexer_wrong_value_type(self): """Test calling an indexer using a value of the wrong type.""" - def test(): + with self.assertRaises(TypeError): ob = Test.PublicIndexerTest() ob[1] = 9993.9 - self.assertRaises(TypeError, test) - def test_unbound_indexer(self): """Test calling an unbound indexer.""" ob = Test.PublicIndexerTest() @@ -651,26 +559,18 @@ def test_indexer_abuse(self): _class = Test.PublicIndexerTest ob = Test.PublicIndexerTest() - def test(): + with self.assertRaises(AttributeError): del _class.__getitem__ - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del ob.__getitem__ - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del _class.__setitem__ - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del ob.__setitem__ - self.assertRaises(AttributeError, test) - def test_suite(): return unittest.makeSuite(IndexerTests) diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index d47c6279a..ab109458b 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -24,15 +24,11 @@ def test_global_interface_visibility(self): self.assertTrue(IPublicInterface.__name__ == 'IPublicInterface') - def test(): + with self.assertRaises(ImportError): from Python.Test import IInternalInterface - self.assertRaises(ImportError, test) - - def test(): - i = Test.IInternalInterface - - self.assertRaises(AttributeError, test) + with self.assertRaises(AttributeError): + Test.IInternalInterface def test_nested_interface_visibility(self): """Test visibility of nested interfaces.""" @@ -44,16 +40,12 @@ def test_nested_interface_visibility(self): ob = InterfaceTest.IProtected self.assertTrue(ob.__name__ == 'IProtected') - def test(): + with self.assertRaises(AttributeError): ob = InterfaceTest.IInternal - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): ob = InterfaceTest.IPrivate - self.assertRaises(AttributeError, test) - def test_explicit_cast_to_interface(self): """Test explicit cast to an interface.""" from Python.Test import InterfaceTest diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 677a69b52..29d921dac 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -14,49 +14,33 @@ class MethodTests(unittest.TestCase): def test_instance_method_descriptor(self): """Test instance method descriptor behavior.""" - def test(): + with self.assertRaises(AttributeError): MethodTest().PublicMethod = 0 - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): MethodTest.PublicMethod = 0 - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del MethodTest().PublicMethod - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del MethodTest.PublicMethod - self.assertRaises(AttributeError, test) - def test_static_method_descriptor(self): """Test static method descriptor behavior.""" - def test(): + with self.assertRaises(AttributeError): MethodTest().PublicStaticMethod = 0 - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): MethodTest.PublicStaticMethod = 0 - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del MethodTest().PublicStaticMethod - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): del MethodTest.PublicStaticMethod - self.assertRaises(AttributeError, test) - def test_public_instance_method(self): """Test public instance method visibility.""" ob = MethodTest() @@ -83,49 +67,33 @@ def test_protected_static_method(self): def test_internal_method(self): """Test internal method visibility.""" - def test(): + with self.assertRaises(AttributeError): f = MethodTest().InternalMethod - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = MethodTest.InternalMethod - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = MethodTest().InternalStaticMethod - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = MethodTest.InternalStaticMethod - self.assertRaises(AttributeError, test) - def test_private_method(self): """Test private method visibility.""" - def test(): + with self.assertRaises(AttributeError): f = MethodTest().PrivateMethod - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = MethodTest.PrivateMethod - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = MethodTest().PrivateStaticMethod - self.assertRaises(AttributeError, test) - - def test(): + with self.assertRaises(AttributeError): f = MethodTest.PrivateStaticMethod - self.assertRaises(AttributeError, test) - def test_unbound_managed_method_call(self): """Test calling unbound managed methods.""" from Python.Test import MethodTestSub @@ -133,20 +101,16 @@ def test_unbound_managed_method_call(self): ob = MethodTest() self.assertTrue(MethodTest.PublicMethod(ob) == "public") - def test(): + with self.assertRaises(TypeError): MethodTest.PublicMethod() - self.assertRaises(TypeError, test) - ob = MethodTestSub() self.assertTrue(MethodTestSub.PublicMethod(ob) == "public") self.assertTrue(MethodTestSub.PublicMethod(ob, "echo") == "echo") - def test(): + with self.assertRaises(TypeError): MethodTestSub.PublicMethod("echo") - self.assertRaises(TypeError, test) - def test_overloaded_method_inheritance(self): """Test that overloads are inherited properly.""" from Python.Test import MethodTestSub @@ -154,12 +118,10 @@ def test_overloaded_method_inheritance(self): ob = MethodTest() self.assertTrue(ob.PublicMethod() == "public") - def test(): + with self.assertRaises(TypeError): ob = MethodTest() ob.PublicMethod("echo") - self.assertRaises(TypeError, test) - ob = MethodTestSub() self.assertTrue(ob.PublicMethod() == "public") @@ -169,16 +131,12 @@ def test_method_descriptor_abuse(self): """Test method descriptor abuse.""" desc = MethodTest.__dict__['PublicMethod'] - def test(): + with self.assertRaises(TypeError): desc.__get__(0, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(AttributeError): desc.__set__(0, 0) - self.assertRaises(AttributeError, test) - def test_method_docstrings(self): """Test standard method docstring generation""" method = MethodTest.GetType @@ -319,12 +277,10 @@ def test_value_out_params(self): self.assertTrue(result[0] == True) self.assertTrue(result[1] == 42) - def test(): + with self.assertRaises(TypeError): MethodTest.TestValueOutParams("hi", None) # None cannot be converted to a value type like int, long, etc. - self.assertRaises(TypeError, test) - def test_value_ref_params(self): """Test use of value type byref parameters.""" result = MethodTest.TestValueRefParams("hi", 1) @@ -333,12 +289,10 @@ def test_value_ref_params(self): self.assertTrue(result[0] == True) self.assertTrue(result[1] == 42) - def test(): + with self.assertRaises(TypeError): MethodTest.TestValueRefParams("hi", None) # None cannot be converted to a value type like int, long, etc. - self.assertRaises(TypeError, test) - def test_object_out_params(self): """Test use of object out-parameters.""" result = MethodTest.TestObjectOutParams("hi", MethodTest()) @@ -375,12 +329,10 @@ def test_struct_out_params(self): self.assertTrue(result[0] == True) self.assertTrue(isinstance(result[1], System.Guid)) - def test(): + with self.assertRaises(TypeError): MethodTest.TestValueRefParams("hi", None) # None cannot be converted to a value type like a struct - self.assertRaises(TypeError, test) - def test_struct_ref_params(self): """Test use of struct byref parameters.""" result = MethodTest.TestStructRefParams("hi", System.Guid.NewGuid()) @@ -389,34 +341,28 @@ def test_struct_ref_params(self): self.assertTrue(result[0] == True) self.assertTrue(isinstance(result[1], System.Guid)) - def test(): + with self.assertRaises(TypeError): MethodTest.TestValueRefParams("hi", None) # None cannot be converted to a value type like a struct - self.assertRaises(TypeError, test) - def test_void_single_out_param(self): """Test void method with single out-parameter.""" result = MethodTest.TestVoidSingleOutParam(9) self.assertTrue(result == 42) - def test(): + with self.assertRaises(TypeError): MethodTest.TestVoidSingleOutParam(None) # None cannot be converted to a value type - self.assertRaises(TypeError, test) - def test_void_single_ref_param(self): """Test void method with single ref-parameter.""" result = MethodTest.TestVoidSingleRefParam(9) self.assertTrue(result == 42) - def test(): + with self.assertRaises(TypeError): MethodTest.TestVoidSingleRefParam(None) # None cannot be converted to a value type - self.assertRaises(TypeError, test) - def test_single_default_param(self): """Test void method with single ref-parameter.""" result = MethodTest.TestSingleDefaultParam() @@ -735,28 +681,20 @@ def test_overload_selection_with_array_types(self): def test_explicit_overload_selection_failure(self): """Check that overload selection fails correctly.""" - def test(): + with self.assertRaises(TypeError): value = MethodTest.Overloaded.__overloads__[System.Type](True) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): value = MethodTest.Overloaded.__overloads__[int, int](1, 1) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): value = MethodTest.Overloaded.__overloads__[str, int, int]( "", 1, 1 ) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): value = MethodTest.Overloaded.__overloads__[int, long](1) - self.assertRaises(TypeError, test) - def test_we_can_bind_to_encoding_get_string(self): """Check that we can bind to the Encoding.GetString method with variables.""" diff --git a/src/tests/test_module.py b/src/tests/test_module.py index 998124d67..ad27cae9b 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -244,13 +244,10 @@ def test_implicit_load_already_valid_namespace(self): self.assertTrue(isCLRClass(System.UriBuilder)) def test_import_non_existant_module(self): - """Test import failure for a non-existant module.""" - - def test(): + """Test import failure for a non-existent module.""" + with self.assertRaises(ImportError): import System.SpamSpamSpam - self.assertTrue(ImportError, test) - def test_lookup_no_namespace_type(self): """Test lookup of types without a qualified namespace.""" import Python.Test @@ -260,17 +257,13 @@ def test_lookup_no_namespace_type(self): def test_module_lookup_recursion(self): """Test for recursive lookup handling.""" - def test1(): + with self.assertRaises(ImportError): from System import System - self.assertTrue(ImportError, test1) - - def test2(): + with self.assertRaises(AttributeError): import System x = System.System - self.assertTrue(AttributeError, test2) - def test_module_get_attr(self): """Test module getattr behavior.""" import System @@ -281,16 +274,12 @@ def test_module_get_attr(self): module = System.Xml self.assertTrue(isCLRModule(module)) - def test(): + with self.assertRaises(AttributeError): spam = System.Spam - self.assertTrue(AttributeError, test) - - def test(): + with self.assertRaises(TypeError): spam = getattr(System, 1) - self.assertTrue(TypeError, test) - def test_module_attr_abuse(self): """Test handling of attempts to set module attributes.""" @@ -310,21 +299,15 @@ def test_module_type_abuse(self): import System mtype = type(System) - def test(): + with self.assertRaises(TypeError): mtype.__getattribute__(0, 'spam') - self.assertTrue(TypeError, test) - - def test(): + with self.assertRaises(TypeError): mtype.__setattr__(0, 'spam', 1) - self.assertTrue(TypeError, test) - - def test(): + with self.assertRaises(TypeError): mtype.__repr__(0) - self.assertTrue(TypeError, test) - def test_clr_list_assemblies(self): from clr import ListAssemblies verbose = list(ListAssemblies(True)) @@ -342,8 +325,8 @@ def test_clr_add_reference(self): assyName = assy.GetName().Name self.assertEqual(assyName, name) - self.assertRaises(FileNotFoundException, - AddReference, "somethingtotallysilly") + with self.assertRaises(FileNotFoundException): + AddReference("somethingtotallysilly") def test_assembly_load_thread_safety(self): import time diff --git a/src/tests/test_property.py b/src/tests/test_property.py index d8d967658..8f1d5f9e1 100644 --- a/src/tests/test_property.py +++ b/src/tests/test_property.py @@ -16,11 +16,9 @@ def test_public_instance_property(self): ob.PublicProperty = 1 self.assertTrue(ob.PublicProperty == 1) - def test(): + with self.assertRaises(TypeError): del PropertyTest().PublicProperty - self.assertRaises(TypeError, test) - def test_public_static_property(self): """Test public static properties.""" ob = PropertyTest() @@ -33,16 +31,12 @@ def test_public_static_property(self): ob.PublicStaticProperty = 0 self.assertTrue(ob.PublicStaticProperty == 0) - def test(): + with self.assertRaises(TypeError): del PropertyTest.PublicStaticProperty - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del PropertyTest().PublicStaticProperty - self.assertRaises(TypeError, test) - def test_protected_instance_property(self): """Test protected instance properties.""" ob = PropertyTest() @@ -51,11 +45,9 @@ def test_protected_instance_property(self): ob.ProtectedProperty = 1 self.assertTrue(ob.ProtectedProperty == 1) - def test(): + with self.assertRaises(TypeError): del PropertyTest().ProtectedProperty - self.assertRaises(TypeError, test) - def test_protected_static_property(self): """Test protected static properties.""" ob = PropertyTest() @@ -68,51 +60,35 @@ def test_protected_static_property(self): ob.ProtectedStaticProperty = 0 self.assertTrue(ob.ProtectedStaticProperty == 0) - def test(): + with self.assertRaises(TypeError): del PropertyTest.ProtectedStaticProperty - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): del PropertyTest().ProtectedStaticProperty - self.assertRaises(TypeError, test) - def test_internal_property(self): """Test internal properties.""" - def test(): - return PropertyTest().InternalProperty - - self.assertRaises(AttributeError, test) - - def test(): - return PropertyTest().InternalStaticProperty + with self.assertRaises(AttributeError): + PropertyTest().InternalProperty - self.assertRaises(AttributeError, test) + with self.assertRaises(AttributeError): + PropertyTest().InternalStaticProperty - def test(): - return PropertyTest.InternalStaticProperty - - self.assertRaises(AttributeError, test) + with self.assertRaises(AttributeError): + PropertyTest.InternalStaticProperty def test_private_property(self): """Test private properties.""" - def test(): - return PropertyTest().PrivateProperty - - self.assertRaises(AttributeError, test) - - def test(): - return PropertyTest().PrivateStaticProperty - - self.assertRaises(AttributeError, test) + with self.assertRaises(AttributeError): + PropertyTest().PrivateProperty - def test(): - return PropertyTest.PrivateStaticProperty + with self.assertRaises(AttributeError): + PropertyTest().PrivateStaticProperty - self.assertRaises(AttributeError, test) + with self.assertRaises(AttributeError): + PropertyTest.PrivateStaticProperty def test_property_descriptor_get_set(self): """Test property descriptor get / set.""" @@ -140,26 +116,20 @@ def test_property_descriptor_get_set(self): def test_property_descriptor_wrong_type(self): """Test setting a property using a value of the wrong type.""" - def test(): + with self.assertRaises(TypeError): ob = PropertyTest() ob.PublicProperty = "spam" - self.assertTrue(TypeError, test) - def test_property_descriptor_abuse(self): """Test property descriptor abuse.""" desc = PropertyTest.__dict__['PublicProperty'] - def test(): + with self.assertRaises(TypeError): desc.__get__(0, 0) - self.assertRaises(TypeError, test) - - def test(): + with self.assertRaises(TypeError): desc.__set__(0, 0) - self.assertRaises(TypeError, test) - def test_interface_property(self): """Test properties of interfaces. Added after a bug report that an IsAbstract check was inappropriate and prevented diff --git a/src/tests/test_suite/test_import.py b/src/tests/test_suite/test_import.py index baea6d5cf..9bae9ca5f 100644 --- a/src/tests/test_suite/test_import.py +++ b/src/tests/test_suite/test_import.py @@ -10,10 +10,8 @@ def test_relative_missing_import(self): """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""" - try: + with self.assertRaises(ImportError): from . import _missing_import - except ImportError: - pass def test_suite(): From 2b42cdf0377d9aff1c5cf8e8d6f4b173d852be55 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 22 Jan 2017 01:59:32 -0700 Subject: [PATCH 042/245] Format for pep8 and linters Fix max min nameclash --- src/tests/leaktest.py | 12 +- src/tests/profile.py | 4 +- src/tests/runtests.py | 2 +- src/tests/stress.py | 35 +-- src/tests/stresstest.py | 2 +- src/tests/test_array.py | 340 ++++++++++---------- src/tests/test_class.py | 40 +-- src/tests/test_compat.py | 46 +-- src/tests/test_constructors.py | 4 +- src/tests/test_conversion.py | 46 +-- src/tests/test_delegate.py | 20 +- src/tests/test_engine.py | 9 +- src/tests/test_enum.py | 3 +- src/tests/test_event.py | 42 ++- src/tests/test_exceptions.py | 25 +- src/tests/test_field.py | 12 +- src/tests/test_generic.py | 426 +++++++++++++------------- src/tests/test_indexer.py | 175 +++++------ src/tests/test_interface.py | 7 +- src/tests/test_method.py | 186 ++++++----- src/tests/test_module.py | 65 ++-- src/tests/test_property.py | 14 +- src/tests/test_subclass.py | 8 +- src/tests/test_suite/test_callback.py | 12 +- src/tests/test_thread.py | 9 +- src/tests/utils.py | 14 +- 26 files changed, 763 insertions(+), 795 deletions(-) diff --git a/src/tests/leaktest.py b/src/tests/leaktest.py index a54774566..2167060ad 100644 --- a/src/tests/leaktest.py +++ b/src/tests/leaktest.py @@ -43,10 +43,10 @@ def end_test(self): end = System.Environment.WorkingSet diff = end - start if diff > 0: - diff = '+%d' % diff + diff = '+{0}'.format(diff) else: - diff = '%d' % diff - print(" start: %d end: %d diff: %s" % (start, end, diff)) + diff = '{0}'.format(diff) + print(" start: {0} end: {1} diff: {2}".format(start, end, diff)) print("") def run(self): @@ -203,10 +203,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 + def handler(sender, args, dict_=dict_): + dict_['value'] = args.value testob.PublicEvent += handler testob.PublicEvent(testob, TestEventArgs(10)) diff --git a/src/tests/profile.py b/src/tests/profile.py index ddc076e7b..f6576ddce 100644 --- a/src/tests/profile.py +++ b/src/tests/profile.py @@ -26,12 +26,12 @@ def main(): start = time.clock() for i in range(50): - print('iteration: %d' % i) + print('iteration: {0:d}'.format(i)) runtests.main() stop = time.clock() took = str(stop - start) - print('Total Time: %s' % took) + print('Total Time: {0}'.format(took)) for item in gc.get_objects(): print(item, sys.getrefcount(item)) diff --git a/src/tests/runtests.py b/src/tests/runtests.py index 3b7ffa08e..919d4b7e5 100644 --- a/src/tests/runtests.py +++ b/src/tests/runtests.py @@ -58,7 +58,7 @@ def remove_pyc(): path = os.path.dirname(os.path.abspath(__file__)) for name in test_modules: - pyc = os.path.join(path, "%s.pyc" % name) + pyc = os.path.join(path, "{0}.pyc".format(name)) if os.path.isfile(pyc): os.unlink(pyc) diff --git a/src/tests/stress.py b/src/tests/stress.py index ebc975d38..2ffe06958 100644 --- a/src/tests/stress.py +++ b/src/tests/stress.py @@ -18,12 +18,7 @@ import time from _compat import range, thread - - -def dprint(msg): - # Debugging helper to trace thread-related tests. - if 1: - print(msg) +from utils import dprint class StressTest(object): @@ -35,47 +30,47 @@ def __init__(self): self.module = runtests self.done = [] - def markStart(self): + def mark_start(self): self._start = time.clock() - def markFinish(self): + def mark_finish(self): self._finish = time.clock() def elapsed(self): return self._finish - self._start - def printGCReport(self): + def print_gc_report(self): for item in gc.get_objects(): print(item, sys.getrefcount(item)) - def runThread(self, iterations): + def run_thread(self, iterations): thread_id = thread.get_ident() - dprint("thread %s starting..." % thread_id) + dprint("thread {0} starting...".format(thread_id)) time.sleep(0.1) for i in range(iterations): - dprint("thread %s iter %d start" % (thread_id, i)) + dprint("thread {0} iter {1} start".format(thread_id, i)) self.module.main() - dprint("thread %s iter %d end" % (thread_id, i)) + dprint("thread {0} iter {1} end".format(thread_id, i)) self.done.append(None) - dprint("thread %s done" % thread_id) + dprint("thread {0} done".format(thread_id)) - def stressTest(self, iterations=1, threads=1): + def stress_test(self, iterations=1, threads=1): args = (iterations,) - self.markStart() + self.mark_start() for _ in range(threads): - thread = threading.Thread(target=self.runThread, args=args) + thread = threading.Thread(target=self.run_thread, args=args) thread.start() while len(self.done) < (iterations * threads): dprint(len(self.done)) time.sleep(0.1) - self.markFinish() + self.mark_finish() took = self.elapsed() - self.printGCReport() + self.print_gc_report() def main(): test = StressTest() - test.stressTest(2, 10) + test.stress_test(2, 10) if __name__ == '__main__': diff --git a/src/tests/stresstest.py b/src/tests/stresstest.py index 6c02bf566..947959239 100644 --- a/src/tests/stresstest.py +++ b/src/tests/stresstest.py @@ -50,7 +50,7 @@ def main(): stop = time.clock() took = str(stop - start) - print('Total Time: %s' % took) + print('Total Time: {0}'.format(took)) for i in gc.get_objects(): print(i) diff --git a/src/tests/test_array.py b/src/tests/test_array.py index a107253c6..bcd50e386 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -60,14 +60,14 @@ def test_internal_array(self): with self.assertRaises(AttributeError): ob = Test.InternalArrayTest() - items = ob.items + _ = ob.items def test_private_array(self): """Test private arrays.""" with self.assertRaises(AttributeError): ob = Test.PrivateArrayTest() - items = ob.items + _ = ob.items def test_array_bounds_checking(self): """Test array bounds checking.""" @@ -89,7 +89,7 @@ def test_array_bounds_checking(self): with self.assertRaises(IndexError): ob = Test.Int32ArrayTest() - ob.items[5] + _ = ob.items[5] with self.assertRaises(IndexError): ob = Test.Int32ArrayTest() @@ -141,7 +141,7 @@ def test_boolean_array(self): with self.assertRaises(TypeError): ob = Test.ByteArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.ByteArrayTest() @@ -157,32 +157,32 @@ def test_byte_array(self): self.assertTrue(items[0] == 0) self.assertTrue(items[4] == 4) - max = 255 - min = 0 + max_ = 255 + min_ = 0 - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(OverflowError): ob = Test.ByteArrayTest() - ob.items[0] = max + 1 + ob.items[0] = max_ + 1 with self.assertRaises(OverflowError): ob = Test.ByteArrayTest() - ob.items[0] = min - 1 + ob.items[0] = min_ - 1 with self.assertRaises(TypeError): ob = Test.ByteArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.ByteArrayTest() @@ -198,32 +198,32 @@ def test_sbyte_array(self): self.assertTrue(items[0] == 0) self.assertTrue(items[4] == 4) - max = 127 - min = -128 + max_ = 127 + min_ = -128 - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(OverflowError): ob = Test.SByteArrayTest() - ob.items[0] = max + 1 + ob.items[0] = max_ + 1 with self.assertRaises(OverflowError): ob = Test.SByteArrayTest() - ob.items[0] = min - 1 + ob.items[0] = min_ - 1 with self.assertRaises(TypeError): ob = Test.SByteArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.SByteArrayTest() @@ -239,24 +239,24 @@ def test_char_array(self): self.assertTrue(items[0] == 'a') self.assertTrue(items[4] == 'e') - max = unichr(65535) - min = unichr(0) + max_ = unichr(65535) + min_ = unichr(0) - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(TypeError): ob = Test.CharArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.CharArrayTest() @@ -272,32 +272,32 @@ def test_int16_array(self): self.assertTrue(items[0] == 0) self.assertTrue(items[4] == 4) - max = 32767 - min = -32768 + max_ = 32767 + min_ = -32768 - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(OverflowError): ob = Test.Int16ArrayTest() - ob.items[0] = max + 1 + ob.items[0] = max_ + 1 with self.assertRaises(OverflowError): ob = Test.Int16ArrayTest() - ob.items[0] = min - 1 + ob.items[0] = min_ - 1 with self.assertRaises(TypeError): ob = Test.Int16ArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.Int16ArrayTest() @@ -313,32 +313,32 @@ def test_int32_array(self): self.assertTrue(items[0] == 0) self.assertTrue(items[4] == 4) - max = 2147483647 - min = -2147483648 + max_ = 2147483647 + min_ = -2147483648 - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(OverflowError): ob = Test.Int32ArrayTest() - ob.items[0] = max + 1 + ob.items[0] = max_ + 1 with self.assertRaises(OverflowError): ob = Test.Int32ArrayTest() - ob.items[0] = min - 1 + ob.items[0] = min_ - 1 with self.assertRaises(TypeError): ob = Test.Int32ArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.Int32ArrayTest() @@ -354,32 +354,32 @@ def test_int64_array(self): self.assertTrue(items[0] == 0) self.assertTrue(items[4] == 4) - max = long(9223372036854775807) - min = long(-9223372036854775808) + max_ = long(9223372036854775807) + min_ = long(-9223372036854775808) - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(OverflowError): ob = Test.Int64ArrayTest() - ob.items[0] = max + 1 + ob.items[0] = max_ + 1 with self.assertRaises(OverflowError): ob = Test.Int64ArrayTest() - ob.items[0] = min - 1 + ob.items[0] = min_ - 1 with self.assertRaises(TypeError): ob = Test.Int64ArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.Int64ArrayTest() @@ -395,32 +395,32 @@ def test_uint16_array(self): self.assertTrue(items[0] == 0) self.assertTrue(items[4] == 4) - max = 65535 - min = 0 + max_ = 65535 + min_ = 0 - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(OverflowError): ob = Test.UInt16ArrayTest() - ob.items[0] = max + 1 + ob.items[0] = max_ + 1 with self.assertRaises(OverflowError): ob = Test.UInt16ArrayTest() - ob.items[0] = min - 1 + ob.items[0] = min_ - 1 with self.assertRaises(TypeError): ob = Test.UInt16ArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.UInt16ArrayTest() @@ -436,32 +436,32 @@ def test_uint32_array(self): self.assertTrue(items[0] == 0) self.assertTrue(items[4] == 4) - max = long(4294967295) - min = 0 + max_ = long(4294967295) + min_ = 0 - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(OverflowError): ob = Test.UInt32ArrayTest() - ob.items[0] = max + 1 + ob.items[0] = max_ + 1 with self.assertRaises(OverflowError): ob = Test.UInt32ArrayTest() - ob.items[0] = min - 1 + ob.items[0] = min_ - 1 with self.assertRaises(TypeError): ob = Test.UInt32ArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.UInt32ArrayTest() @@ -477,32 +477,32 @@ def test_uint64_array(self): self.assertTrue(items[0] == 0) self.assertTrue(items[4] == 4) - max = long(18446744073709551615) - min = 0 + max_ = long(18446744073709551615) + min_ = 0 - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(OverflowError): ob = Test.UInt64ArrayTest() - ob.items[0] = max + 1 + ob.items[0] = max_ + 1 with self.assertRaises(OverflowError): ob = Test.UInt64ArrayTest() - ob.items[0] = min - 1 + ob.items[0] = min_ - 1 with self.assertRaises(TypeError): ob = Test.UInt64ArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.UInt64ArrayTest() @@ -518,24 +518,24 @@ def test_single_array(self): self.assertTrue(items[0] == 0.0) self.assertTrue(items[4] == 4.0) - max = 3.402823e38 - min = -3.402823e38 + max_ = 3.402823e38 + min_ = -3.402823e38 - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(TypeError): ob = Test.SingleArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.SingleArrayTest() @@ -551,24 +551,24 @@ def test_double_array(self): self.assertTrue(items[0] == 0.0) self.assertTrue(items[4] == 4.0) - max = 1.7976931348623157e308 - min = -1.7976931348623157e308 + max_ = 1.7976931348623157e308 + min_ = -1.7976931348623157e308 - items[0] = max - self.assertTrue(items[0] == max) + items[0] = max_ + self.assertTrue(items[0] == max_) - items[0] = min - self.assertTrue(items[0] == min) + items[0] = min_ + self.assertTrue(items[0] == min_) - items[-4] = max - self.assertTrue(items[-4] == max) + items[-4] = max_ + self.assertTrue(items[-4] == max_) - items[-1] = min - self.assertTrue(items[-1] == min) + items[-1] = min_ + self.assertTrue(items[-1] == min_) with self.assertRaises(TypeError): ob = Test.DoubleArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.DoubleArrayTest() @@ -602,7 +602,7 @@ def test_decimal_array(self): with self.assertRaises(TypeError): ob = Test.DecimalArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.DecimalArrayTest() @@ -632,7 +632,7 @@ def test_string_array(self): with self.assertRaises(TypeError): ob = Test.StringArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.Int64ArrayTest() @@ -667,7 +667,7 @@ def test_enum_array(self): with self.assertRaises(TypeError): ob = Test.EnumArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.EnumArrayTest() @@ -704,7 +704,7 @@ def test_object_array(self): with self.assertRaises(TypeError): ob = Test.ObjectArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.ObjectArrayTest() @@ -737,7 +737,7 @@ def test_null_array(self): with self.assertRaises(TypeError): ob = Test.NullArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] def test_interface_array(self): """Test interface arrays.""" @@ -771,7 +771,7 @@ def test_interface_array(self): with self.assertRaises(TypeError): ob = Test.InterfaceArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.InterfaceArrayTest() @@ -809,7 +809,7 @@ def test_typed_array(self): with self.assertRaises(TypeError): ob = Test.TypedArrayTest() - v = ob.items["wrong"] + _ = ob.items["wrong"] with self.assertRaises(TypeError): ob = Test.TypedArrayTest() @@ -848,32 +848,32 @@ def test_multi_dimensional_array(self): self.assertTrue(items[4, 3] == 23) self.assertTrue(items[4, 4] == 24) - max = 2147483647 - min = -2147483648 + max_ = 2147483647 + min_ = -2147483648 - items[0, 0] = max - self.assertTrue(items[0, 0] == max) + items[0, 0] = max_ + self.assertTrue(items[0, 0] == max_) - items[0, 0] = min - self.assertTrue(items[0, 0] == min) + items[0, 0] = min_ + self.assertTrue(items[0, 0] == min_) - items[-4, 0] = max - self.assertTrue(items[-4, 0] == max) + items[-4, 0] = max_ + self.assertTrue(items[-4, 0] == max_) - items[-1, -1] = min - self.assertTrue(items[-1, -1] == min) + items[-1, -1] = min_ + self.assertTrue(items[-1, -1] == min_) with self.assertRaises(OverflowError): ob = Test.MultiDimensionalArrayTest() - ob.items[0, 0] = max + 1 + ob.items[0, 0] = max_ + 1 with self.assertRaises(OverflowError): ob = Test.MultiDimensionalArrayTest() - ob.items[0, 0] = min - 1 + ob.items[0, 0] = min_ - 1 with self.assertRaises(TypeError): ob = Test.MultiDimensionalArrayTest() - v = ob.items["wrong", 0] + _ = ob.items["wrong", 0] with self.assertRaises(TypeError): ob = Test.MultiDimensionalArrayTest() @@ -918,7 +918,7 @@ def test_tuple_nested_array_conversion(self): items = [] for i in range(10): subs = [] - for n in range(10): + for _ in range(10): subs.append(Spam(str(i))) items.append(tuple(subs)) items = tuple(items) @@ -950,7 +950,7 @@ def test_list_nested_array_conversion(self): items = [] for i in range(10): subs = [] - for n in range(10): + for _ in range(10): subs.append(Spam(str(i))) items.append(subs) @@ -981,7 +981,7 @@ def test_sequence_nested_array_conversion(self): items = UserList() for i in range(10): subs = UserList() - for n in range(10): + for _ in range(10): subs.append(Spam(str(i))) items.append(subs) @@ -1014,12 +1014,12 @@ def test_tuple_array_conversion_type_checking(self): with self.assertRaises(TypeError): temp = list(items) temp[1] = 1 - result = ArrayConversionTest.EchoRange(tuple(temp)) + _ = ArrayConversionTest.EchoRange(tuple(temp)) with self.assertRaises(TypeError): temp = list(items) temp[1] = "spam" - result = ArrayConversionTest.EchoRange(tuple(temp)) + _ = ArrayConversionTest.EchoRange(tuple(temp)) def test_list_array_conversion_type_checking(self): """Test error handling for list conversion to array arguments.""" @@ -1042,11 +1042,11 @@ def test_list_array_conversion_type_checking(self): with self.assertRaises(TypeError): items[1] = 1 - result = ArrayConversionTest.EchoRange(items) + _ = ArrayConversionTest.EchoRange(items) with self.assertRaises(TypeError): items[1] = "spam" - result = ArrayConversionTest.EchoRange(items) + _ = ArrayConversionTest.EchoRange(items) def test_sequence_array_conversion_type_checking(self): """Test error handling for sequence conversion to array arguments.""" @@ -1069,11 +1069,11 @@ def test_sequence_array_conversion_type_checking(self): with self.assertRaises(TypeError): items[1] = 1 - result = ArrayConversionTest.EchoRange(items) + _ = ArrayConversionTest.EchoRange(items) with self.assertRaises(TypeError): items[1] = "spam" - result = ArrayConversionTest.EchoRange(items) + _ = ArrayConversionTest.EchoRange(items) def test_md_array_conversion(self): """Test passing of multi-dimensional array arguments.""" diff --git a/src/tests/test_class.py b/src/tests/test_class.py index 373bb326d..80cee9009 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +# TODO: Add tests for ClassicClass, NewStyleClass? import unittest @@ -8,28 +9,16 @@ from _compat import DictProxyType, range -class ClassicClass: - def kind(self): - return 'classic' - - -class NewStyleClass(object): - def kind(self): - return 'new-style' - - class ClassTests(unittest.TestCase): """Test CLR class support.""" def test_basic_reference_type(self): """Test usage of CLR defined reference types.""" - String = System.String - self.assertEquals(String.Empty, "") + self.assertEquals(System.String.Empty, "") def test_basic_value_type(self): """Test usage of CLR defined value types.""" - Int32 = System.Int32 - self.assertEquals(Int32.MaxValue, 2147483647) + self.assertEquals(System.Int32.MaxValue, 2147483647) def test_class_standard_attrs(self): """Test standard class attributes.""" @@ -63,14 +52,14 @@ def test_non_public_class(self): from Python.Test import InternalClass with self.assertRaises(AttributeError): - x = Test.InternalClass + _ = Test.InternalClass def test_basic_subclass(self): """Test basic subclass of a managed class.""" from System.Collections import Hashtable class MyTable(Hashtable): - def howMany(self): + def how_many(self): return self.Count table = MyTable() @@ -80,16 +69,14 @@ def howMany(self): self.assertTrue(len(table.__class__.__bases__) == 1) self.assertTrue(table.__class__.__bases__[0] == Hashtable) - self.assertTrue(table.howMany() == 0) + self.assertTrue(table.how_many() == 0) self.assertTrue(table.Count == 0) table.set_Item('one', 'one') - self.assertTrue(table.howMany() == 1) + self.assertTrue(table.how_many() == 1) self.assertTrue(table.Count == 1) - MyTable = None - def test_subclass_with_no_arg_constructor(self): """Test subclass of a managed class with a no-arg constructor.""" from Python.Test import ClassCtorTest1 @@ -99,7 +86,7 @@ def __init__(self, name): self.name = name # This failed in earlier versions - inst = SubClass('test') + _ = SubClass('test') def test_subclass_with_various_constructors(self): """Test subclass of a managed class with various constructors.""" @@ -145,19 +132,18 @@ def test_struct_construction(self): # test recursion # test - def test_ienumerable_iteration(self): """Test iteration over objects supporting IEnumerable.""" from Python.Test import ClassTest - list = ClassTest.GetArrayList() + list_ = ClassTest.GetArrayList() - for item in list: + for item in list_: self.assertTrue((item > -1) and (item < 10)) - dict = ClassTest.GetHashtable() + dict_ = ClassTest.GetHashtable() - for item in dict: + for item in dict_: cname = item.__class__.__name__ self.assertTrue(cname.endswith('DictionaryEntry')) @@ -214,7 +200,7 @@ def test_add_and_remove_class_attribute(self): from System import TimeSpan for _ in range(100): - TimeSpan.new_method = lambda self: self.TotalMinutes + TimeSpan.new_method = lambda self_: self_.TotalMinutes ts = TimeSpan.FromHours(1) self.assertTrue(ts.new_method() == 60) del TimeSpan.new_method diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index 6570f2c1c..c26bb9e5d 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -1,10 +1,11 @@ # -*- coding: utf-8 -*- +# TODO: Complete removal of methods below. Similar to test_module import types import unittest from _compat import ClassType, PY2, PY3, range -from utils import isCLRClass, isCLRModule, isCLRRootModule +from utils import is_clr_class, is_clr_module, is_clr_root_module class CompatibilityTests(unittest.TestCase): @@ -15,7 +16,7 @@ class CompatibilityTests(unittest.TestCase): def test_simple_import(self): """Test simple import.""" import CLR - self.assertTrue(isCLRRootModule(CLR)) + self.assertTrue(is_clr_root_module(CLR)) self.assertTrue(CLR.__name__ == 'clr') import sys @@ -35,7 +36,7 @@ def test_simple_import(self): def test_simple_import_with_alias(self): """Test simple import with aliasing.""" import CLR as myCLR - self.assertTrue(isCLRRootModule(myCLR)) + self.assertTrue(is_clr_root_module(myCLR)) self.assertTrue(myCLR.__name__ == 'clr') import sys as mySys @@ -55,11 +56,11 @@ def test_simple_import_with_alias(self): def test_dotted_name_import(self): """Test dotted-name import.""" import CLR.System - self.assertTrue(isCLRModule(CLR.System)) + self.assertTrue(is_clr_module(CLR.System)) self.assertTrue(CLR.System.__name__ == 'System') import System - self.assertTrue(isCLRModule(System)) + self.assertTrue(is_clr_module(System)) self.assertTrue(System.__name__ == 'System') self.assertTrue(System is CLR.System) @@ -71,11 +72,11 @@ def test_dotted_name_import(self): def test_dotted_name_import_with_alias(self): """Test dotted-name import with aliasing.""" import CLR.System as myCLRSystem - self.assertTrue(isCLRModule(myCLRSystem)) + self.assertTrue(is_clr_module(myCLRSystem)) self.assertTrue(myCLRSystem.__name__ == 'System') import System as mySystem - self.assertTrue(isCLRModule(mySystem)) + self.assertTrue(is_clr_module(mySystem)) self.assertTrue(mySystem.__name__ == 'System') self.assertTrue(mySystem is myCLRSystem) @@ -87,7 +88,7 @@ def test_dotted_name_import_with_alias(self): def test_simple_import_from(self): """Test simple 'import from'.""" from CLR import System - self.assertTrue(isCLRModule(System)) + self.assertTrue(is_clr_module(System)) self.assertTrue(System.__name__ == 'System') from xml import dom @@ -97,7 +98,7 @@ def test_simple_import_from(self): def test_simple_import_from_with_alias(self): """Test simple 'import from' with aliasing.""" from CLR import System as mySystem - self.assertTrue(isCLRModule(mySystem)) + self.assertTrue(is_clr_module(mySystem)) self.assertTrue(mySystem.__name__ == 'System') from xml import dom as myDom @@ -107,11 +108,11 @@ def test_simple_import_from_with_alias(self): def test_dotted_name_import_from(self): """Test dotted-name 'import from'.""" from CLR.System import Xml - self.assertTrue(isCLRModule(Xml)) + self.assertTrue(is_clr_module(Xml)) self.assertTrue(Xml.__name__ == 'System.Xml') from CLR.System.Xml import XmlDocument - self.assertTrue(isCLRClass(XmlDocument)) + self.assertTrue(is_clr_class(XmlDocument)) self.assertTrue(XmlDocument.__name__ == 'XmlDocument') from xml.dom import pulldom @@ -125,11 +126,11 @@ def test_dotted_name_import_from(self): def test_dotted_name_import_from_with_alias(self): """Test dotted-name 'import from' with aliasing.""" from CLR.System import Xml as myXml - self.assertTrue(isCLRModule(myXml)) + self.assertTrue(is_clr_module(myXml)) self.assertTrue(myXml.__name__ == 'System.Xml') from CLR.System.Xml import XmlDocument as myXmlDocument - self.assertTrue(isCLRClass(myXmlDocument)) + self.assertTrue(is_clr_class(myXmlDocument)) self.assertTrue(myXmlDocument.__name__ == 'XmlDocument') from xml.dom import pulldom as myPulldom @@ -145,12 +146,12 @@ def test_from_module_import_star(self): count = len(locals().keys()) m = __import__('CLR.System.Management', globals(), locals(), ['*']) self.assertTrue(m.__name__ == 'System.Management') - self.assertTrue(isCLRModule(m)) + self.assertTrue(is_clr_module(m)) self.assertTrue(len(locals().keys()) > count + 1) m2 = __import__('System.Management', globals(), locals(), ['*']) self.assertTrue(m2.__name__ == 'System.Management') - self.assertTrue(isCLRModule(m2)) + self.assertTrue(is_clr_module(m2)) self.assertTrue(len(locals().keys()) > count + 1) self.assertTrue(m is m2) @@ -179,7 +180,7 @@ def test_implicit_load_already_valid_namespace(self): # Python runtime to "do the right thing", allowing types from both # assemblies to be found in the CLR.System module implicitly. import CLR.System - self.assertTrue(isCLRClass(CLR.System.UriBuilder)) + self.assertTrue(is_clr_class(CLR.System.UriBuilder)) def test_import_non_existant_module(self): """Test import failure for a non-existent module.""" @@ -193,7 +194,7 @@ def test_lookup_no_namespace_type(self): """Test lookup of types without a qualified namespace.""" import CLR.Python.Test import CLR - self.assertTrue(isCLRClass(CLR.NoNamespaceType)) + self.assertTrue(is_clr_class(CLR.NoNamespaceType)) def test_module_lookup_recursion(self): """Test for recursive lookup handling.""" @@ -202,29 +203,30 @@ def test_module_lookup_recursion(self): with self.assertRaises(AttributeError): import CLR - x = CLR.CLR + _ = CLR.CLR def test_module_get_attr(self): """Test module getattr behavior.""" import CLR.System as System int_type = System.Int32 - self.assertTrue(isCLRClass(int_type)) + self.assertTrue(is_clr_class(int_type)) module = System.Xml - self.assertTrue(isCLRModule(module)) + self.assertTrue(is_clr_module(module)) with self.assertRaises(AttributeError): - spam = System.Spam + _ = System.Spam with self.assertRaises(TypeError): - spam = getattr(System, 1) + _ = getattr(System, 1) def test_multiple_imports(self): # import CLR did raise a Seg Fault once # test if the Exceptions.warn() method still causes it for _ in range(100): import CLR + _ = CLR def test_suite(): diff --git a/src/tests/test_constructors.py b/src/tests/test_constructors.py index b1f3aacb1..0039f9bf3 100644 --- a/src/tests/test_constructors.py +++ b/src/tests/test_constructors.py @@ -38,10 +38,10 @@ def test_subclass_constructor(self): """Test subclass constructor args""" from Python.Test import SubclassConstructorTest - class sub(System.Exception): + class Sub(System.Exception): pass - instance = sub() + instance = Sub() ob = SubclassConstructorTest(instance) self.assertTrue(isinstance(ob.value, System.Exception)) diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index 7423e2201..8400292d5 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -5,7 +5,7 @@ import System from Python.Test import ConversionTest -from _compat import indexbytes, long, range, unichr +from _compat import indexbytes, long, unichr class ConversionTests(unittest.TestCase): @@ -96,10 +96,10 @@ def test_sbyte_conversion(self): ConversionTest().SByteField = -129 with self.assertRaises(OverflowError): - value = System.SByte(128) + _ = System.SByte(128) with self.assertRaises(OverflowError): - value = System.SByte(-129) + _ = System.SByte(-129) def test_byte_conversion(self): """Test byte conversion.""" @@ -134,10 +134,10 @@ def test_byte_conversion(self): ConversionTest().ByteField = -1 with self.assertRaises(OverflowError): - value = System.Byte(256) + _ = System.Byte(256) with self.assertRaises(OverflowError): - value = System.Byte(-1) + _ = System.Byte(-1) def test_char_conversion(self): """Test char conversion.""" @@ -198,10 +198,10 @@ def test_int16_conversion(self): ConversionTest().Int16Field = -32769 with self.assertRaises(OverflowError): - value = System.Int16(32768) + _ = System.Int16(32768) with self.assertRaises(OverflowError): - value = System.Int16(-32769) + _ = System.Int16(-32769) def test_int32_conversion(self): """Test int32 conversion.""" @@ -236,10 +236,10 @@ def test_int32_conversion(self): ConversionTest().Int32Field = -2147483649 with self.assertRaises(OverflowError): - value = System.Int32(2147483648) + _ = System.Int32(2147483648) with self.assertRaises(OverflowError): - value = System.Int32(-2147483649) + _ = System.Int32(-2147483649) def test_int64_conversion(self): """Test int64 conversion.""" @@ -274,10 +274,10 @@ def test_int64_conversion(self): ConversionTest().Int64Field = long(-9223372036854775809) with self.assertRaises(OverflowError): - value = System.Int64(long(9223372036854775808)) + _ = System.Int64(long(9223372036854775808)) with self.assertRaises(OverflowError): - value = System.Int64(long(-9223372036854775809)) + _ = System.Int64(long(-9223372036854775809)) def test_uint16_conversion(self): """Test uint16 conversion.""" @@ -312,10 +312,10 @@ def test_uint16_conversion(self): ConversionTest().UInt16Field = -1 with self.assertRaises(OverflowError): - value = System.UInt16(65536) + _ = System.UInt16(65536) with self.assertRaises(OverflowError): - value = System.UInt16(-1) + _ = System.UInt16(-1) def test_uint32_conversion(self): """Test uint32 conversion.""" @@ -350,10 +350,10 @@ def test_uint32_conversion(self): ConversionTest().UInt32Field = -1 with self.assertRaises(OverflowError): - value = System.UInt32(long(4294967296)) + _ = System.UInt32(long(4294967296)) with self.assertRaises(OverflowError): - value = System.UInt32(-1) + _ = System.UInt32(-1) def test_uint64_conversion(self): """Test uint64 conversion.""" @@ -388,10 +388,10 @@ def test_uint64_conversion(self): ConversionTest().UInt64Field = -1 with self.assertRaises(OverflowError): - value = System.UInt64(long(18446744073709551616)) + _ = System.UInt64(long(18446744073709551616)) with self.assertRaises(OverflowError): - value = System.UInt64(-1) + _ = System.UInt64(-1) def test_single_conversion(self): """Test single conversion.""" @@ -426,10 +426,10 @@ def test_single_conversion(self): ConversionTest().SingleField = -3.402824e38 with self.assertRaises(OverflowError): - value = System.Single(3.402824e38) + _ = System.Single(3.402824e38) with self.assertRaises(OverflowError): - value = System.Single(-3.402824e38) + _ = System.Single(-3.402824e38) def test_double_conversion(self): """Test double conversion.""" @@ -464,10 +464,10 @@ def test_double_conversion(self): ConversionTest().DoubleField = -1.7976931348623159e308 with self.assertRaises(OverflowError): - value = System.Double(1.7976931348623159e308) + _ = System.Double(1.7976931348623159e308) with self.assertRaises(OverflowError): - value = System.Double(-1.7976931348623159e308) + _ = System.Double(-1.7976931348623159e308) def test_decimal_conversion(self): """Test decimal conversion.""" @@ -658,7 +658,7 @@ def test_byte_array_conversion(self): value = b"testing" ob.ByteArrayField = value array = ob.ByteArrayField - for i in range(len(value)): + for i, _ in enumerate(value): self.assertTrue(array[i] == indexbytes(value, i)) def test_sbyte_array_conversion(self): @@ -676,7 +676,7 @@ def test_sbyte_array_conversion(self): value = b"testing" ob.SByteArrayField = value array = ob.SByteArrayField - for i in range(len(value)): + for i, _ in enumerate(value): self.assertTrue(array[i] == indexbytes(value, i)) diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index 0c51c2937..1d0c30533 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -32,9 +32,10 @@ def test_global_delegate_visibility(self): with self.assertRaises(ImportError): from Python.Test import InternalDelegate + _ = InternalDelegate with self.assertRaises(AttributeError): - i = Test.InternalDelegate + _ = Test.InternalDelegate def test_nested_delegate_visibility(self): """Test visibility of nested delegates.""" @@ -45,10 +46,10 @@ def test_nested_delegate_visibility(self): self.assertTrue(ob.__name__ == 'ProtectedDelegate') with self.assertRaises(AttributeError): - ob = DelegateTest.InternalDelegate + _ = DelegateTest.InternalDelegate with self.assertRaises(AttributeError): - ob = DelegateTest.PrivateDelegate + _ = DelegateTest.PrivateDelegate def test_delegate_from_function(self): """Test delegate implemented with a Python function.""" @@ -187,13 +188,13 @@ def test_delegate_with_invalid_args(self): """Test delegate instantiation with invalid (non-callable) args.""" with self.assertRaises(TypeError): - d = StringDelegate(None) + _ = StringDelegate(None) with self.assertRaises(TypeError): - d = StringDelegate("spam") + _ = StringDelegate("spam") with self.assertRaises(TypeError): - d = StringDelegate(1) + _ = StringDelegate(1) def test_multicast_delegate(self): """Test multicast delegates.""" @@ -218,14 +219,12 @@ def test_subclass_delegate_fails(self): with self.assertRaises(TypeError): class Boom(PublicDelegate): pass + _ = Boom def test_delegate_equality(self): """Test delegate equality.""" - def sayhello(): - return "hello" - - d = StringDelegate(sayhello) + d = StringDelegate(hello_func) ob = DelegateTest() ob.stringDelegate = d self.assertTrue(ob.stringDelegate == d) @@ -242,7 +241,6 @@ def always_so_negative(): ob.CallBoolDelegate(d) self.assertTrue(not d()) - self.assertTrue(not ob.CallBoolDelegate(d)) # test async delegates diff --git a/src/tests/test_engine.py b/src/tests/test_engine.py index cfc019b5f..a39cb4aa8 100644 --- a/src/tests/test_engine.py +++ b/src/tests/test_engine.py @@ -13,9 +13,12 @@ class EngineTests(unittest.TestCase): def test_multiple_calls_to_initialize(self): """Test that multiple initialize calls are harmless.""" - PythonEngine.Initialize() - PythonEngine.Initialize() - PythonEngine.Initialize() + try: + PythonEngine.Initialize() + PythonEngine.Initialize() + PythonEngine.Initialize() + except BaseException: + self.fail("Initialize() raise an exception.") def test_import_module(self): """Test module import.""" diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index 170a47fd1..c24f5aabd 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -84,7 +84,7 @@ def test_instantiate_enum_fails(self): from System import DayOfWeek with self.assertRaises(TypeError): - ob = DayOfWeek() + _ = DayOfWeek() def test_subclass_enum_fails(self): """Test that subclassing of an enumeration fails.""" @@ -93,6 +93,7 @@ def test_subclass_enum_fails(self): with self.assertRaises(TypeError): class Boom(DayOfWeek): pass + _ = Boom def test_enum_set_member_fails(self): """Test that setattr operations on enumerations fail.""" diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 64ecc615c..de337c00b 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -53,8 +53,6 @@ def test_protected_instance_event(self): def test_protected_static_event(self): """Test protected static events.""" - ob = EventTest - handler = GenericHandler() self.assertTrue(handler.value == None) @@ -69,25 +67,25 @@ def test_internal_events(self): """Test internal events.""" with self.assertRaises(AttributeError): - f = EventTest().InternalEvent + _ = EventTest().InternalEvent with self.assertRaises(AttributeError): - f = EventTest().InternalStaticEvent + _ = EventTest().InternalStaticEvent with self.assertRaises(AttributeError): - f = EventTest.InternalStaticEvent + _ = EventTest.InternalStaticEvent def test_private_events(self): """Test private events.""" with self.assertRaises(AttributeError): - f = EventTest().PrivateEvent + _ = EventTest().PrivateEvent with self.assertRaises(AttributeError): - f = EventTest().PrivateStaticEvent + _ = EventTest().PrivateStaticEvent with self.assertRaises(AttributeError): - f = EventTest.PrivateStaticEvent + _ = EventTest.PrivateStaticEvent def test_multicast_event(self): """Test multicast events.""" @@ -258,33 +256,31 @@ def test_unbound_method_handler(self): """Test failure mode for unbound method handlers.""" ob = EventTest() ob.PublicEvent += GenericHandler.handler - try: + + with self.assertRaises(TypeError): ob.OnPublicEvent(TestEventArgs(10)) - except TypeError: - ob.PublicEvent -= GenericHandler.handler - return - raise TypeError("should have raised a TypeError") + ob.PublicEvent -= GenericHandler.handler def test_function_handler(self): """Test function handlers.""" ob = EventTest() - dict = {'value': None} + dict_ = {'value': None} - def handler(sender, args, dict=dict): - dict['value'] = args.value + def handler(sender, args, dict_=dict_): + dict_['value'] = args.value ob.PublicEvent += handler - self.assertTrue(dict['value'] == None) + self.assertTrue(dict_['value'] == None) ob.OnPublicEvent(TestEventArgs(10)) - self.assertTrue(dict['value'] == 10) + self.assertTrue(dict_['value'] == 10) ob.PublicEvent -= handler - self.assertTrue(dict['value'] == 10) + self.assertTrue(dict_['value'] == 10) ob.OnPublicEvent(TestEventArgs(20)) - self.assertTrue(dict['value'] == 10) + self.assertTrue(dict_['value'] == 10) def test_add_non_callable_handler(self): """Test handling of attempts to add non-callable handlers.""" @@ -298,11 +294,11 @@ def test_add_non_callable_handler(self): ob.PublicEvent += "spam" with self.assertRaises(TypeError): - class spam(object): + class Spam(object): pass ob = EventTest() - ob.PublicEvent += spam() + ob.PublicEvent += Spam() def test_remove_multiple_handlers(self): """Test removing multiple instances of the same handler.""" @@ -411,7 +407,7 @@ def test_random_multiple_handlers(self): ob.PublicEvent += handler2.handler handlers = [] - for i in range(30): + for _ in range(30): method = handler.handler ob.PublicEvent += method handlers.append(method) diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index aeec1fee3..7d60e0732 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -220,7 +220,7 @@ def test_catch_exception_unqualified(self): try: raise OverflowException('overflow') except: - return + pass else: self.fail("failed to catch unqualified exception") @@ -240,22 +240,22 @@ def test_apparent_module_of_exception(self): def test_str_of_exception(self): """Test the str() representation of an exception.""" - from System import NullReferenceException - from System import Convert, FormatException + from System import NullReferenceException, Convert, FormatException + e = NullReferenceException('') self.assertEqual(str(e), '') e = NullReferenceException('Something bad happened') self.assertTrue(str(e).startswith('Something bad happened')) - try: + with self.assertRaises(FormatException) as cm: Convert.ToDateTime('this will fail') - except FormatException: - e = sys.exc_info()[1] - # fix for international installation - msg = text_type(e).encode("utf8") - fnd = text_type('System.Convert.ToDateTime').encode("utf8") - self.assertTrue(msg.find(fnd) > -1, msg) + + e = cm.exception + # fix for international installation + msg = text_type(e).encode("utf8") + fnd = text_type('System.Convert.ToDateTime').encode("utf8") + self.assertTrue(msg.find(fnd) > -1, msg) def test_python_compat_of_managed_exceptions(self): """Test managed exceptions compatible with Python's implementation""" @@ -286,12 +286,11 @@ def test_exception_is_instance_of_system_object(self): # here mainly to remind me to update the caveat in the documentation # one day when when exceptions can be new-style classes. - # This behaviour is now over-shadowed by the implementation of + # This behavior is now over-shadowed by the implementation of # __instancecheck__ (i.e., overloading isinstance), so for all Python # version >= 2.6 we expect isinstance(, Object) to # be true, even though it does not really subclass Object. - from System import OverflowException - from System import Object + from System import OverflowException, Object o = OverflowException('error') diff --git a/src/tests/test_field.py b/src/tests/test_field.py index 1f2ca87ea..6300309ce 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -119,25 +119,25 @@ def test_internal_field(self): """Test internal fields.""" with self.assertRaises(AttributeError): - f = FieldTest().InternalField + _ = FieldTest().InternalField with self.assertRaises(AttributeError): - f = FieldTest().InternalStaticField + _ = FieldTest().InternalStaticField with self.assertRaises(AttributeError): - f = FieldTest.InternalStaticField + _ = FieldTest.InternalStaticField def test_private_field(self): """Test private fields.""" with self.assertRaises(AttributeError): - f = FieldTest().PrivateField + _ = FieldTest().PrivateField with self.assertRaises(AttributeError): - f = FieldTest().PrivateStaticField + _ = FieldTest().PrivateStaticField with self.assertRaises(AttributeError): - f = FieldTest.PrivateStaticField + _ = FieldTest.PrivateStaticField def test_field_descriptor_get_set(self): """Test field descriptor get / set.""" diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index e85e76667..fb5e0e5ea 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -11,7 +11,7 @@ class GenericTests(unittest.TestCase): """Test CLR generics support.""" - def _testGenericWrapperByType(self, ptype, value): + def _assert_generic_wrapper_by_type(self, ptype, value): """Test Helper""" from Python.Test import GenericWrapper import System @@ -26,7 +26,7 @@ def _testGenericWrapperByType(self, ptype, value): self.assertTrue(inst.value[0] == value) self.assertTrue(inst.value[1] == value) - def _testGenericMethodByType(self, ptype, value, test_type=0): + def _assert_generic_method_by_type(self, ptype, value, test_type=0): """Test Helper""" from Python.Test import GenericMethodTest, GenericStaticMethodTest import System @@ -116,55 +116,55 @@ def test_python_type_aliasing(self): """Test python type alias support with generics.""" from System.Collections.Generic import Dictionary - dict = Dictionary[str, str]() - self.assertEquals(dict.Count, 0) - dict.Add("one", "one") - self.assertTrue(dict["one"] == "one") - - dict = Dictionary[System.String, System.String]() - self.assertEquals(dict.Count, 0) - dict.Add("one", "one") - self.assertTrue(dict["one"] == "one") - - dict = Dictionary[int, int]() - self.assertEquals(dict.Count, 0) - dict.Add(1, 1) - self.assertTrue(dict[1] == 1) - - dict = Dictionary[System.Int32, System.Int32]() - self.assertEquals(dict.Count, 0) - dict.Add(1, 1) - self.assertTrue(dict[1] == 1) - - dict = Dictionary[long, long]() - self.assertEquals(dict.Count, 0) - dict.Add(long(1), long(1)) - self.assertTrue(dict[long(1)] == long(1)) - - dict = Dictionary[System.Int64, System.Int64]() - self.assertEquals(dict.Count, 0) - dict.Add(long(1), long(1)) - self.assertTrue(dict[long(1)] == long(1)) - - dict = Dictionary[float, float]() - self.assertEquals(dict.Count, 0) - dict.Add(1.5, 1.5) - self.assertTrue(dict[1.5] == 1.5) - - dict = Dictionary[System.Double, System.Double]() - self.assertEquals(dict.Count, 0) - dict.Add(1.5, 1.5) - self.assertTrue(dict[1.5] == 1.5) - - dict = Dictionary[bool, bool]() - self.assertEquals(dict.Count, 0) - dict.Add(True, False) - self.assertTrue(dict[True] == False) - - dict = Dictionary[System.Boolean, System.Boolean]() - self.assertEquals(dict.Count, 0) - dict.Add(True, False) - self.assertTrue(dict[True] == False) + dict_ = Dictionary[str, str]() + self.assertEquals(dict_.Count, 0) + dict_.Add("one", "one") + self.assertTrue(dict_["one"] == "one") + + dict_ = Dictionary[System.String, System.String]() + self.assertEquals(dict_.Count, 0) + dict_.Add("one", "one") + self.assertTrue(dict_["one"] == "one") + + dict_ = Dictionary[int, int]() + self.assertEquals(dict_.Count, 0) + dict_.Add(1, 1) + self.assertTrue(dict_[1] == 1) + + dict_ = Dictionary[System.Int32, System.Int32]() + self.assertEquals(dict_.Count, 0) + dict_.Add(1, 1) + self.assertTrue(dict_[1] == 1) + + dict_ = Dictionary[long, long]() + self.assertEquals(dict_.Count, 0) + dict_.Add(long(1), long(1)) + self.assertTrue(dict_[long(1)] == long(1)) + + dict_ = Dictionary[System.Int64, System.Int64]() + self.assertEquals(dict_.Count, 0) + dict_.Add(long(1), long(1)) + self.assertTrue(dict_[long(1)] == long(1)) + + dict_ = Dictionary[float, float]() + self.assertEquals(dict_.Count, 0) + dict_.Add(1.5, 1.5) + self.assertTrue(dict_[1.5] == 1.5) + + dict_ = Dictionary[System.Double, System.Double]() + self.assertEquals(dict_.Count, 0) + dict_.Add(1.5, 1.5) + self.assertTrue(dict_[1.5] == 1.5) + + dict_ = Dictionary[bool, bool]() + self.assertEquals(dict_.Count, 0) + dict_.Add(True, False) + self.assertTrue(dict_[True] == False) + + dict_ = Dictionary[System.Boolean, System.Boolean]() + self.assertEquals(dict_.Count, 0) + dict_.Add(True, False) + self.assertTrue(dict_[True] == False) def test_generic_reference_type(self): """Test usage of generic reference type definitions.""" @@ -192,20 +192,20 @@ def test_open_generic_type(self): """Test behavior of reflected open constructed generic types.""" from Python.Test import DerivedFromOpenGeneric - OpenGenericType = DerivedFromOpenGeneric.__bases__[0] + open_generic_type = DerivedFromOpenGeneric.__bases__[0] with self.assertRaises(TypeError): - inst = OpenGenericType() + _ = open_generic_type() with self.assertRaises(TypeError): - type = OpenGenericType[System.String] + _ = open_generic_type[System.String] def test_derived_from_open_generic_type(self): """Test a generic type derived from an open generic type.""" from Python.Test import DerivedFromOpenGeneric - type = DerivedFromOpenGeneric[System.String, System.String] - inst = type(1, 'two', 'three') + type_ = DerivedFromOpenGeneric[System.String, System.String] + inst = type_(1, 'two', 'three') self.assertTrue(inst.value1 == 1) self.assertTrue(inst.value2 == 'two') @@ -225,7 +225,7 @@ def test_generic_type_name_resolution(self): # cannot be instantiated. It can only be used to bind a generic. with self.assertRaises(TypeError): - inst = GenericNameTest2() + _ = GenericNameTest2() _class = GenericNameTest2[int] self.assertTrue(_class().value == 1) @@ -240,32 +240,32 @@ def test_generic_type_binding(self): from Python.Test import InterfaceTest, ISayHello1, ShortEnum import System - self._testGenericWrapperByType(System.Boolean, True) - self._testGenericWrapperByType(bool, True) - self._testGenericWrapperByType(System.Byte, 255) - self._testGenericWrapperByType(System.SByte, 127) - self._testGenericWrapperByType(System.Char, u'A') - self._testGenericWrapperByType(System.Int16, 32767) - self._testGenericWrapperByType(System.Int32, 2147483647) - self._testGenericWrapperByType(int, 2147483647) - self._testGenericWrapperByType(System.Int64, long(9223372036854775807)) + self._assert_generic_wrapper_by_type(System.Boolean, True) + self._assert_generic_wrapper_by_type(bool, True) + self._assert_generic_wrapper_by_type(System.Byte, 255) + self._assert_generic_wrapper_by_type(System.SByte, 127) + self._assert_generic_wrapper_by_type(System.Char, u'A') + self._assert_generic_wrapper_by_type(System.Int16, 32767) + self._assert_generic_wrapper_by_type(System.Int32, 2147483647) + self._assert_generic_wrapper_by_type(int, 2147483647) + self._assert_generic_wrapper_by_type(System.Int64, long(9223372036854775807)) # Python 3 has no explicit long type, use System.Int64 instead if PY2: - self._testGenericWrapperByType(long, long(9223372036854775807)) - self._testGenericWrapperByType(System.UInt16, 65000) - self._testGenericWrapperByType(System.UInt32, long(4294967295)) - self._testGenericWrapperByType(System.UInt64, long(18446744073709551615)) - self._testGenericWrapperByType(System.Single, 3.402823e38) - self._testGenericWrapperByType(System.Double, 1.7976931348623157e308) - self._testGenericWrapperByType(float, 1.7976931348623157e308) - self._testGenericWrapperByType(System.Decimal, System.Decimal.One) - self._testGenericWrapperByType(System.String, "test") - self._testGenericWrapperByType(unicode, "test") - self._testGenericWrapperByType(str, "test") - self._testGenericWrapperByType(ShortEnum, ShortEnum.Zero) - self._testGenericWrapperByType(System.Object, InterfaceTest()) - self._testGenericWrapperByType(InterfaceTest, InterfaceTest()) - self._testGenericWrapperByType(ISayHello1, InterfaceTest()) + self._assert_generic_wrapper_by_type(long, long(9223372036854775807)) + self._assert_generic_wrapper_by_type(System.UInt16, 65000) + self._assert_generic_wrapper_by_type(System.UInt32, long(4294967295)) + self._assert_generic_wrapper_by_type(System.UInt64, long(18446744073709551615)) + self._assert_generic_wrapper_by_type(System.Single, 3.402823e38) + self._assert_generic_wrapper_by_type(System.Double, 1.7976931348623157e308) + self._assert_generic_wrapper_by_type(float, 1.7976931348623157e308) + self._assert_generic_wrapper_by_type(System.Decimal, System.Decimal.One) + self._assert_generic_wrapper_by_type(System.String, "test") + self._assert_generic_wrapper_by_type(unicode, "test") + self._assert_generic_wrapper_by_type(str, "test") + self._assert_generic_wrapper_by_type(ShortEnum, ShortEnum.Zero) + self._assert_generic_wrapper_by_type(System.Object, InterfaceTest()) + self._assert_generic_wrapper_by_type(InterfaceTest, InterfaceTest()) + self._assert_generic_wrapper_by_type(ISayHello1, InterfaceTest()) def test_generic_method_binding(self): from Python.Test import GenericMethodTest, GenericStaticMethodTest @@ -293,40 +293,38 @@ def test_generic_method_type_handling(self): from Python.Test import InterfaceTest, ISayHello1, ShortEnum import System - # XXX BUG: The value doesn't fit into Int64 and PythonNet doesn't + # FIXME: The value doesn't fit into Int64 and PythonNet doesn't # recognize it as UInt64 for unknown reasons. - # self._testGenericMethodByType(System.UInt64, 18446744073709551615L) - self._testGenericMethodByType(System.Boolean, True) - self._testGenericMethodByType(bool, True) - self._testGenericMethodByType(System.Byte, 255) - self._testGenericMethodByType(System.SByte, 127) - self._testGenericMethodByType(System.Char, u'A') - self._testGenericMethodByType(System.Int16, 32767) - self._testGenericMethodByType(System.Int32, 2147483647) - self._testGenericMethodByType(int, 2147483647) + # self._assert_generic_method_by_type(System.UInt64, 18446744073709551615L) + self._assert_generic_method_by_type(System.Boolean, True) + self._assert_generic_method_by_type(bool, True) + self._assert_generic_method_by_type(System.Byte, 255) + self._assert_generic_method_by_type(System.SByte, 127) + self._assert_generic_method_by_type(System.Char, u'A') + self._assert_generic_method_by_type(System.Int16, 32767) + self._assert_generic_method_by_type(System.Int32, 2147483647) + self._assert_generic_method_by_type(int, 2147483647) # Python 3 has no explicit long type, use System.Int64 instead if PY2: - self._testGenericMethodByType(System.Int64, long(9223372036854775807)) - self._testGenericMethodByType(long, long(9223372036854775807)) - self._testGenericMethodByType(System.UInt32, long(4294967295)) - self._testGenericMethodByType(System.Int64, long(1844674407370955161)) - self._testGenericMethodByType(System.UInt16, 65000) - self._testGenericMethodByType(System.Single, 3.402823e38) - self._testGenericMethodByType(System.Double, 1.7976931348623157e308) - self._testGenericMethodByType(float, 1.7976931348623157e308) - self._testGenericMethodByType(System.Decimal, System.Decimal.One) - self._testGenericMethodByType(System.String, "test") - self._testGenericMethodByType(unicode, "test") - self._testGenericMethodByType(str, "test") - self._testGenericMethodByType(ShortEnum, ShortEnum.Zero) - self._testGenericMethodByType(System.Object, InterfaceTest()) - self._testGenericMethodByType(InterfaceTest, InterfaceTest(), 1) - self._testGenericMethodByType(ISayHello1, InterfaceTest(), 1) + self._assert_generic_method_by_type(System.Int64, long(9223372036854775807)) + self._assert_generic_method_by_type(long, long(9223372036854775807)) + self._assert_generic_method_by_type(System.UInt32, long(4294967295)) + self._assert_generic_method_by_type(System.Int64, long(1844674407370955161)) + self._assert_generic_method_by_type(System.UInt16, 65000) + self._assert_generic_method_by_type(System.Single, 3.402823e38) + self._assert_generic_method_by_type(System.Double, 1.7976931348623157e308) + self._assert_generic_method_by_type(float, 1.7976931348623157e308) + self._assert_generic_method_by_type(System.Decimal, System.Decimal.One) + self._assert_generic_method_by_type(System.String, "test") + self._assert_generic_method_by_type(unicode, "test") + self._assert_generic_method_by_type(str, "test") + self._assert_generic_method_by_type(ShortEnum, ShortEnum.Zero) + self._assert_generic_method_by_type(System.Object, InterfaceTest()) + self._assert_generic_method_by_type(InterfaceTest, InterfaceTest(), 1) + self._assert_generic_method_by_type(ISayHello1, InterfaceTest(), 1) def test_correct_overload_selection(self): """Test correct overloading selection for common types.""" - from System.Drawing import Font - from System import (String, Double, Single, Int16, Int32, Int64) from System import Math @@ -345,21 +343,19 @@ def test_correct_overload_selection(self): self.assertTrue( Math.Max(atype(value1), atype(value2)) == Math.Max.__overloads__[atype, atype]( - atype(value1), - atype(value2))) + atype(value1), atype(value2))) if PY2 and atype is Int64: value2 = long(value2) self.assertTrue( Math.Max(atype(value1), value2) == Math.Max.__overloads__[atype, atype]( - atype(value1), - atype(value2))) + atype(value1), atype(value2))) clr.AddReference("System.Runtime.InteropServices") from System.Runtime.InteropServices import GCHandle, GCHandleType from System import Array, Byte - CSArray = Array.CreateInstance(Byte, 1000) - handler = GCHandle.Alloc(CSArray, GCHandleType.Pinned) + cs_array = Array.CreateInstance(Byte, 1000) + handler = GCHandle.Alloc(cs_array, GCHandleType.Pinned) def test_generic_method_overload_selection(self): """Test explicit overload selection with generic methods.""" @@ -433,10 +429,10 @@ def test_generic_method_overload_selection(self): self.assertTrue(value == "success") with self.assertRaises(TypeError): - value = type.Overloaded[str, bool, int]("true", True, 1) + _ = type.Overloaded[str, bool, int]("true", True, 1) with self.assertRaises(TypeError): - value = inst.Overloaded[str, bool, int]("true", True, 1) + _ = inst.Overloaded[str, bool, int]("true", True, 1) def test_method_overload_selection_with_generic_types(self): """Check method overload selection using generic types.""" @@ -446,130 +442,130 @@ def test_method_overload_selection_with_generic_types(self): inst = InterfaceTest() vtype = GenericWrapper[System.Boolean] - input = vtype(True) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(True) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == True) vtype = GenericWrapper[bool] - input = vtype(True) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(True) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == True) vtype = GenericWrapper[System.Byte] - input = vtype(255) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(255) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == 255) vtype = GenericWrapper[System.SByte] - input = vtype(127) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(127) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == 127) vtype = GenericWrapper[System.Char] - input = vtype(u'A') - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(u'A') + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == u'A') vtype = GenericWrapper[System.Char] - input = vtype(65535) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(65535) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == unichr(65535)) vtype = GenericWrapper[System.Int16] - input = vtype(32767) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(32767) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == 32767) vtype = GenericWrapper[System.Int32] - input = vtype(2147483647) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(2147483647) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == 2147483647) vtype = GenericWrapper[int] - input = vtype(2147483647) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(2147483647) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == 2147483647) vtype = GenericWrapper[System.Int64] - input = vtype(long(9223372036854775807)) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(long(9223372036854775807)) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == long(9223372036854775807)) # Python 3 has no explicit long type, use System.Int64 instead if PY2: vtype = GenericWrapper[long] - input = vtype(long(9223372036854775807)) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(long(9223372036854775807)) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == long(9223372036854775807)) vtype = GenericWrapper[System.UInt16] - input = vtype(65000) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(65000) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == 65000) vtype = GenericWrapper[System.UInt32] - input = vtype(long(4294967295)) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(long(4294967295)) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == long(4294967295)) vtype = GenericWrapper[System.UInt64] - input = vtype(long(18446744073709551615)) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(long(18446744073709551615)) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == long(18446744073709551615)) vtype = GenericWrapper[System.Single] - input = vtype(3.402823e38) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(3.402823e38) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == 3.402823e38) vtype = GenericWrapper[System.Double] - input = vtype(1.7976931348623157e308) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(1.7976931348623157e308) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == 1.7976931348623157e308) vtype = GenericWrapper[float] - input = vtype(1.7976931348623157e308) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(1.7976931348623157e308) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == 1.7976931348623157e308) vtype = GenericWrapper[System.Decimal] - input = vtype(System.Decimal.One) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(System.Decimal.One) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == System.Decimal.One) vtype = GenericWrapper[System.String] - input = vtype("spam") - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype("spam") + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == "spam") vtype = GenericWrapper[str] - input = vtype("spam") - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype("spam") + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == "spam") vtype = GenericWrapper[ShortEnum] - input = vtype(ShortEnum.Zero) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(ShortEnum.Zero) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value == ShortEnum.Zero) vtype = GenericWrapper[System.Object] - input = vtype(inst) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(inst) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value.__class__ == inst.__class__) vtype = GenericWrapper[InterfaceTest] - input = vtype(inst) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(inst) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value.__class__ == inst.__class__) vtype = GenericWrapper[ISayHello1] - input = vtype(inst) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(inst) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value.value.__class__ == inst.__class__) vtype = System.Array[GenericWrapper[int]] - input = vtype([GenericWrapper[int](0), GenericWrapper[int](1)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([GenericWrapper[int](0), GenericWrapper[int](1)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 0) self.assertTrue(value[1].value == 1) @@ -582,72 +578,72 @@ def test_overload_selection_with_arrays_of_generic_types(self): gtype = GenericWrapper[System.Boolean] vtype = System.Array[gtype] - input = vtype([gtype(True), gtype(True)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(True), gtype(True)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == True) self.assertTrue(value.Length == 2) gtype = GenericWrapper[bool] vtype = System.Array[gtype] - input = vtype([gtype(True), gtype(True)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(True), gtype(True)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == True) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Byte] vtype = System.Array[gtype] - input = vtype([gtype(255), gtype(255)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(255), gtype(255)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 255) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.SByte] vtype = System.Array[gtype] - input = vtype([gtype(127), gtype(127)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(127), gtype(127)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 127) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Char] vtype = System.Array[gtype] - input = vtype([gtype(u'A'), gtype(u'A')]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(u'A'), gtype(u'A')]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == u'A') self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Char] vtype = System.Array[gtype] - input = vtype([gtype(65535), gtype(65535)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(65535), gtype(65535)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == unichr(65535)) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Int16] vtype = System.Array[gtype] - input = vtype([gtype(32767), gtype(32767)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(32767), gtype(32767)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 32767) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Int32] vtype = System.Array[gtype] - input = vtype([gtype(2147483647), gtype(2147483647)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(2147483647), gtype(2147483647)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 2147483647) self.assertTrue(value.Length == 2) gtype = GenericWrapper[int] vtype = System.Array[gtype] - input = vtype([gtype(2147483647), gtype(2147483647)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(2147483647), gtype(2147483647)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 2147483647) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Int64] vtype = System.Array[gtype] - input = vtype([gtype(long(9223372036854775807)), + input_ = vtype([gtype(long(9223372036854775807)), gtype(long(9223372036854775807))]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == long(9223372036854775807)) self.assertTrue(value.Length == 2) @@ -655,104 +651,104 @@ def test_overload_selection_with_arrays_of_generic_types(self): if PY2: gtype = GenericWrapper[long] vtype = System.Array[gtype] - input = vtype([gtype(long(9223372036854775807)), + input_ = vtype([gtype(long(9223372036854775807)), gtype(long(9223372036854775807))]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == long(9223372036854775807)) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.UInt16] vtype = System.Array[gtype] - input = vtype([gtype(65000), gtype(65000)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(65000), gtype(65000)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 65000) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.UInt32] vtype = System.Array[gtype] - input = vtype([gtype(long(4294967295)), gtype(long(4294967295))]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(long(4294967295)), gtype(long(4294967295))]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == long(4294967295)) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.UInt64] vtype = System.Array[gtype] - input = vtype([gtype(long(18446744073709551615)), + input_ = vtype([gtype(long(18446744073709551615)), gtype(long(18446744073709551615))]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == long(18446744073709551615)) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Single] vtype = System.Array[gtype] - input = vtype([gtype(3.402823e38), gtype(3.402823e38)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(3.402823e38), gtype(3.402823e38)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 3.402823e38) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Double] vtype = System.Array[gtype] - input = vtype([gtype(1.7976931348623157e308), + input_ = vtype([gtype(1.7976931348623157e308), gtype(1.7976931348623157e308)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 1.7976931348623157e308) self.assertTrue(value.Length == 2) gtype = GenericWrapper[float] vtype = System.Array[gtype] - input = vtype([gtype(1.7976931348623157e308), + input_ = vtype([gtype(1.7976931348623157e308), gtype(1.7976931348623157e308)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == 1.7976931348623157e308) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Decimal] vtype = System.Array[gtype] - input = vtype([gtype(System.Decimal.One), + input_ = vtype([gtype(System.Decimal.One), gtype(System.Decimal.One)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == System.Decimal.One) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.String] vtype = System.Array[gtype] - input = vtype([gtype("spam"), gtype("spam")]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype("spam"), gtype("spam")]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == "spam") self.assertTrue(value.Length == 2) gtype = GenericWrapper[str] vtype = System.Array[gtype] - input = vtype([gtype("spam"), gtype("spam")]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype("spam"), gtype("spam")]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == "spam") self.assertTrue(value.Length == 2) gtype = GenericWrapper[ShortEnum] vtype = System.Array[gtype] - input = vtype([gtype(ShortEnum.Zero), gtype(ShortEnum.Zero)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(ShortEnum.Zero), gtype(ShortEnum.Zero)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value == ShortEnum.Zero) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Object] vtype = System.Array[gtype] - input = vtype([gtype(inst), gtype(inst)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(inst), gtype(inst)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value.__class__ == inst.__class__) self.assertTrue(value.Length == 2) gtype = GenericWrapper[InterfaceTest] vtype = System.Array[gtype] - input = vtype([gtype(inst), gtype(inst)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(inst), gtype(inst)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value.__class__ == inst.__class__) self.assertTrue(value.Length == 2) gtype = GenericWrapper[ISayHello1] vtype = System.Array[gtype] - input = vtype([gtype(inst), gtype(inst)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([gtype(inst), gtype(inst)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].value.__class__ == inst.__class__) self.assertTrue(value.Length == 2) diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index 90a8d71f0..62581aed4 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -82,16 +82,16 @@ def test_boolean_indexer(self): def test_byte_indexer(self): """Test byte indexers.""" ob = Test.ByteIndexerTest() - max = 255 - min = 0 + max_ = 255 + min_ = 0 - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = str(max) - self.assertTrue(ob[max] == str(max)) + ob[max_] = str(max_) + self.assertTrue(ob[max_] == str(max_)) - ob[min] = str(min) - self.assertTrue(ob[min] == str(min)) + ob[min_] = str(min_) + self.assertTrue(ob[min_] == str(min_)) with self.assertRaises(TypeError): ob = Test.ByteIndexerTest() @@ -104,16 +104,16 @@ def test_byte_indexer(self): def test_sbyte_indexer(self): """Test sbyte indexers.""" ob = Test.SByteIndexerTest() - max = 127 - min = -128 + max_ = 127 + min_ = -128 - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = str(max) - self.assertTrue(ob[max] == str(max)) + ob[max_] = str(max_) + self.assertTrue(ob[max_] == str(max_)) - ob[min] = str(min) - self.assertTrue(ob[min] == str(min)) + ob[min_] = str(min_) + self.assertTrue(ob[min_] == str(min_)) with self.assertRaises(TypeError): ob = Test.SByteIndexerTest() @@ -126,16 +126,16 @@ def test_sbyte_indexer(self): def test_char_indexer(self): """Test char indexers.""" ob = Test.CharIndexerTest() - max = unichr(65535) - min = unichr(0) + max_ = unichr(65535) + min_ = unichr(0) - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = "max" - self.assertTrue(ob[max] == "max") + ob[max_] = "max_" + self.assertTrue(ob[max_] == "max_") - ob[min] = "min" - self.assertTrue(ob[min] == "min") + ob[min_] = "min_" + self.assertTrue(ob[min_] == "min_") with self.assertRaises(TypeError): ob = Test.CharIndexerTest() @@ -148,16 +148,16 @@ def test_char_indexer(self): def test_int16_indexer(self): """Test Int16 indexers.""" ob = Test.Int16IndexerTest() - max = 32767 - min = -32768 + max_ = 32767 + min_ = -32768 - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = str(max) - self.assertTrue(ob[max] == str(max)) + ob[max_] = str(max_) + self.assertTrue(ob[max_] == str(max_)) - ob[min] = str(min) - self.assertTrue(ob[min] == str(min)) + ob[min_] = str(min_) + self.assertTrue(ob[min_] == str(min_)) with self.assertRaises(TypeError): ob = Test.Int16IndexerTest() @@ -170,16 +170,16 @@ def test_int16_indexer(self): def test_int32_indexer(self): """Test Int32 indexers.""" ob = Test.Int32IndexerTest() - max = 2147483647 - min = -2147483648 + max_ = 2147483647 + min_ = -2147483648 - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = str(max) - self.assertTrue(ob[max] == str(max)) + ob[max_] = str(max_) + self.assertTrue(ob[max_] == str(max_)) - ob[min] = str(min) - self.assertTrue(ob[min] == str(min)) + ob[min_] = str(min_) + self.assertTrue(ob[min_] == str(min_)) with self.assertRaises(TypeError): ob = Test.Int32IndexerTest() @@ -192,16 +192,16 @@ def test_int32_indexer(self): def test_int64_indexer(self): """Test Int64 indexers.""" ob = Test.Int64IndexerTest() - max = long(9223372036854775807) - min = long(-9223372036854775808) + max_ = long(9223372036854775807) + min_ = long(-9223372036854775808) - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = str(max) - self.assertTrue(ob[max] == str(max)) + ob[max_] = str(max_) + self.assertTrue(ob[max_] == str(max_)) - ob[min] = str(min) - self.assertTrue(ob[min] == str(min)) + ob[min_] = str(min_) + self.assertTrue(ob[min_] == str(min_)) with self.assertRaises(TypeError): ob = Test.Int64IndexerTest() @@ -214,16 +214,16 @@ def test_int64_indexer(self): def test_uint16_indexer(self): """Test UInt16 indexers.""" ob = Test.UInt16IndexerTest() - max = 65535 - min = 0 + max_ = 65535 + min_ = 0 - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = str(max) - self.assertTrue(ob[max] == str(max)) + ob[max_] = str(max_) + self.assertTrue(ob[max_] == str(max_)) - ob[min] = str(min) - self.assertTrue(ob[min] == str(min)) + ob[min_] = str(min_) + self.assertTrue(ob[min_] == str(min_)) with self.assertRaises(TypeError): ob = Test.UInt16IndexerTest() @@ -236,16 +236,16 @@ def test_uint16_indexer(self): def test_uint32_indexer(self): """Test UInt32 indexers.""" ob = Test.UInt32IndexerTest() - max = long(4294967295) - min = 0 + max_ = long(4294967295) + min_ = 0 - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = str(max) - self.assertTrue(ob[max] == str(max)) + ob[max_] = str(max_) + self.assertTrue(ob[max_] == str(max_)) - ob[min] = str(min) - self.assertTrue(ob[min] == str(min)) + ob[min_] = str(min_) + self.assertTrue(ob[min_] == str(min_)) with self.assertRaises(TypeError): ob = Test.UInt32IndexerTest() @@ -258,16 +258,16 @@ def test_uint32_indexer(self): def test_uint64_indexer(self): """Test UInt64 indexers.""" ob = Test.UInt64IndexerTest() - max = long(18446744073709551615) - min = 0 + max_ = long(18446744073709551615) + min_ = 0 - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = str(max) - self.assertTrue(ob[max] == str(max)) + ob[max_] = str(max_) + self.assertTrue(ob[max_] == str(max_)) - ob[min] = str(min) - self.assertTrue(ob[min] == str(min)) + ob[min_] = str(min_) + self.assertTrue(ob[min_] == str(min_)) with self.assertRaises(TypeError): ob = Test.UInt64IndexerTest() @@ -280,16 +280,16 @@ def test_uint64_indexer(self): def test_single_indexer(self): """Test Single indexers.""" ob = Test.SingleIndexerTest() - max = 3.402823e38 - min = -3.402823e38 + max_ = 3.402823e38 + min_ = -3.402823e38 - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = "max" - self.assertTrue(ob[max] == "max") + ob[max_] = "max_" + self.assertTrue(ob[max_] == "max_") - ob[min] = "min" - self.assertTrue(ob[min] == "min") + ob[min_] = "min_" + self.assertTrue(ob[min_] == "min_") with self.assertRaises(TypeError): ob = Test.SingleIndexerTest() @@ -302,16 +302,16 @@ def test_single_indexer(self): def test_double_indexer(self): """Test Double indexers.""" ob = Test.DoubleIndexerTest() - max = 1.7976931348623157e308 - min = -1.7976931348623157e308 + max_ = 1.7976931348623157e308 + min_ = -1.7976931348623157e308 - self.assertTrue(ob[max] == None) + self.assertTrue(ob[max_] == None) - ob[max] = "max" - self.assertTrue(ob[max] == "max") + ob[max_] = "max_" + self.assertTrue(ob[max_] == "max_") - ob[min] = "min" - self.assertTrue(ob[min] == "min") + ob[min_] = "min_" + self.assertTrue(ob[min_] == "min_") with self.assertRaises(TypeError): ob = Test.DoubleIndexerTest() @@ -331,11 +331,11 @@ def test_decimal_indexer(self): self.assertTrue(ob[max_d] == None) - ob[max_d] = "max" - self.assertTrue(ob[max_d] == "max") + ob[max_d] = "max_" + self.assertTrue(ob[max_d] == "max_") - ob[min_d] = "min" - self.assertTrue(ob[min_d] == "min") + ob[min_d] = "min_" + self.assertTrue(ob[min_d] == "min_") with self.assertRaises(TypeError): ob = Test.DecimalIndexerTest() @@ -422,10 +422,10 @@ def test_object_indexer(self): self.assertTrue(ob[long(1)] == "long") with self.assertRaises(TypeError): - class eggs(object): + class Eggs(object): pass - key = eggs() + key = Eggs() ob = Test.ObjectIndexerTest() ob[key] = "wrong" @@ -489,7 +489,7 @@ def test_multi_arg_indexer(self): with self.assertRaises(TypeError): ob = Test.MultiArgIndexerTest() - v = ob[0, "one"] + _ = ob[0, "one"] with self.assertRaises(TypeError): ob = Test.MultiArgIndexerTest() @@ -508,14 +508,15 @@ def test_multi_type_indexer(self): with self.assertRaises(TypeError): ob = Test.MultiTypeIndexerTest() - v = ob[0, 1, spam] + _ = ob[0, 1, spam] with self.assertRaises(TypeError): ob = Test.MultiTypeIndexerTest() ob[0, 1, spam] = "wrong" def test_multi_default_key_indexer(self): - """Test indexers that take multiple indices with a default key arguments.""" + """Test indexers that take multiple indices with a default + key arguments.""" # default argument is 2 in the MultiDefaultKeyIndexerTest object ob = Test.MultiDefaultKeyIndexerTest() ob[0, 2] = "zero one spam" @@ -529,7 +530,7 @@ def test_indexer_wrong_key_type(self): with self.assertRaises(TypeError): ob = Test.PublicIndexerTest() - v = ob["wrong"] + _ = ob["wrong"] with self.assertRaises(TypeError): ob = Test.PublicIndexerTest() diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index ab109458b..d83a7a9f1 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -26,9 +26,10 @@ def test_global_interface_visibility(self): with self.assertRaises(ImportError): from Python.Test import IInternalInterface + _ = IInternalInterface with self.assertRaises(AttributeError): - Test.IInternalInterface + _ = Test.IInternalInterface def test_nested_interface_visibility(self): """Test visibility of nested interfaces.""" @@ -41,10 +42,10 @@ def test_nested_interface_visibility(self): self.assertTrue(ob.__name__ == 'IProtected') with self.assertRaises(AttributeError): - ob = InterfaceTest.IInternal + _ = InterfaceTest.IInternal with self.assertRaises(AttributeError): - ob = InterfaceTest.IPrivate + _ = InterfaceTest.IPrivate def test_explicit_cast_to_interface(self): """Test explicit cast to an interface.""" diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 29d921dac..07b73a1e7 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -68,31 +68,31 @@ def test_internal_method(self): """Test internal method visibility.""" with self.assertRaises(AttributeError): - f = MethodTest().InternalMethod + _ = MethodTest().InternalMethod with self.assertRaises(AttributeError): - f = MethodTest.InternalMethod + _ = MethodTest.InternalMethod with self.assertRaises(AttributeError): - f = MethodTest().InternalStaticMethod + _ = MethodTest().InternalStaticMethod with self.assertRaises(AttributeError): - f = MethodTest.InternalStaticMethod + _ = MethodTest.InternalStaticMethod def test_private_method(self): """Test private method visibility.""" with self.assertRaises(AttributeError): - f = MethodTest().PrivateMethod + _ = MethodTest().PrivateMethod with self.assertRaises(AttributeError): - f = MethodTest.PrivateMethod + _ = MethodTest.PrivateMethod with self.assertRaises(AttributeError): - f = MethodTest().PrivateStaticMethod + _ = MethodTest().PrivateStaticMethod with self.assertRaises(AttributeError): - f = MethodTest.PrivateStaticMethod + _ = MethodTest.PrivateStaticMethod def test_unbound_managed_method_call(self): """Test calling unbound managed methods.""" @@ -187,8 +187,6 @@ class TestSubException(System.Exception): def test_null_array_conversion(self): """Test null array conversion in method call.""" - from System import Type - ob = MethodTest() r = ob.TestNullArrayConversion(None) self.assertTrue(r == None) @@ -237,7 +235,8 @@ def test_value_params_args(self): self.assertTrue(result[2] == 3) def test_non_params_array_in_last_place(self): - """Test overload resolution with of non-"params" array as last parameter.""" + """Test overload resolution with of non-"params" array as + last parameter.""" result = MethodTest.TestNonParamsArrayInLastPlace(1, 2, 3) self.assertTrue(result) @@ -277,10 +276,10 @@ def test_value_out_params(self): self.assertTrue(result[0] == True) self.assertTrue(result[1] == 42) + # None cannot be converted to a value type like int, long, etc. with self.assertRaises(TypeError): MethodTest.TestValueOutParams("hi", None) - # None cannot be converted to a value type like int, long, etc. def test_value_ref_params(self): """Test use of value type byref parameters.""" result = MethodTest.TestValueRefParams("hi", 1) @@ -289,10 +288,10 @@ def test_value_ref_params(self): self.assertTrue(result[0] == True) self.assertTrue(result[1] == 42) + # None cannot be converted to a value type like int, long, etc. with self.assertRaises(TypeError): MethodTest.TestValueRefParams("hi", None) - # None cannot be converted to a value type like int, long, etc. def test_object_out_params(self): """Test use of object out-parameters.""" result = MethodTest.TestObjectOutParams("hi", MethodTest()) @@ -329,10 +328,10 @@ def test_struct_out_params(self): self.assertTrue(result[0] == True) self.assertTrue(isinstance(result[1], System.Guid)) + # None cannot be converted to a value type like a struct with self.assertRaises(TypeError): MethodTest.TestValueRefParams("hi", None) - # None cannot be converted to a value type like a struct def test_struct_ref_params(self): """Test use of struct byref parameters.""" result = MethodTest.TestStructRefParams("hi", System.Guid.NewGuid()) @@ -341,28 +340,28 @@ def test_struct_ref_params(self): self.assertTrue(result[0] == True) self.assertTrue(isinstance(result[1], System.Guid)) + # None cannot be converted to a value type like a struct with self.assertRaises(TypeError): MethodTest.TestValueRefParams("hi", None) - # None cannot be converted to a value type like a struct def test_void_single_out_param(self): """Test void method with single out-parameter.""" result = MethodTest.TestVoidSingleOutParam(9) self.assertTrue(result == 42) + # None cannot be converted to a value type with self.assertRaises(TypeError): MethodTest.TestVoidSingleOutParam(None) - # None cannot be converted to a value type def test_void_single_ref_param(self): """Test void method with single ref-parameter.""" result = MethodTest.TestVoidSingleRefParam(9) self.assertTrue(result == 42) + # None cannot be converted to a value type with self.assertRaises(TypeError): MethodTest.TestVoidSingleRefParam(None) - # None cannot be converted to a value type def test_single_default_param(self): """Test void method with single ref-parameter.""" result = MethodTest.TestSingleDefaultParam() @@ -388,16 +387,14 @@ def test_explicit_selection_with_out_modifier(self): """Check explicit overload selection with out modifiers.""" refstr = System.String("").GetType().MakeByRefType() result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( - "hi", "there" - ) + "hi", "there") self.assertTrue(type(result) == type(())) self.assertTrue(len(result) == 2) self.assertTrue(result[0] == True) self.assertTrue(result[1] == "output string") result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( - "hi", None - ) + "hi", None) self.assertTrue(type(result) == type(())) self.assertTrue(len(result) == 2) self.assertTrue(result[0] == True) @@ -407,16 +404,14 @@ def test_explicit_selection_with_ref_modifier(self): """Check explicit overload selection with ref modifiers.""" refstr = System.String("").GetType().MakeByRefType() result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( - "hi", "there" - ) + "hi", "there") self.assertTrue(type(result) == type(())) self.assertTrue(len(result) == 2) self.assertTrue(result[0] == True) self.assertTrue(result[1] == "output string") result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( - "hi", None - ) + "hi", None) self.assertTrue(type(result) == type(())) self.assertTrue(len(result) == 2) self.assertTrue(result[0] == True) @@ -426,6 +421,7 @@ def test_explicit_overload_selection(self): """Check explicit overload selection using [] syntax.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from System import Array + inst = InterfaceTest() value = MethodTest.Overloaded.__overloads__[System.Boolean](True) @@ -456,44 +452,39 @@ def test_explicit_overload_selection(self): self.assertTrue(value == 2147483647) value = MethodTest.Overloaded.__overloads__[System.Int64]( - long(9223372036854775807) - ) + long(9223372036854775807)) self.assertTrue(value == long(9223372036854775807)) # Python 3 has no explicit long type, use System.Int64 instead if PY2: value = MethodTest.Overloaded.__overloads__[long]( - long(9223372036854775807) - ) + long(9223372036854775807)) self.assertTrue(value == long(9223372036854775807)) value = MethodTest.Overloaded.__overloads__[System.UInt16](65000) self.assertTrue(value == 65000) - value = MethodTest.Overloaded.__overloads__[System.UInt32](long(4294967295)) + value = MethodTest.Overloaded.__overloads__[System.UInt32]( + long(4294967295)) self.assertTrue(value == long(4294967295)) value = MethodTest.Overloaded.__overloads__[System.UInt64]( - long(18446744073709551615) - ) + long(18446744073709551615)) self.assertTrue(value == long(18446744073709551615)) value = MethodTest.Overloaded.__overloads__[System.Single](3.402823e38) self.assertTrue(value == 3.402823e38) value = MethodTest.Overloaded.__overloads__[System.Double]( - 1.7976931348623157e308 - ) + 1.7976931348623157e308) self.assertTrue(value == 1.7976931348623157e308) value = MethodTest.Overloaded.__overloads__[float]( - 1.7976931348623157e308 - ) + 1.7976931348623157e308) self.assertTrue(value == 1.7976931348623157e308) value = MethodTest.Overloaded.__overloads__[System.Decimal]( - System.Decimal.One - ) + System.Decimal.One) self.assertTrue(value == System.Decimal.One) value = MethodTest.Overloaded.__overloads__[System.String]("spam") @@ -516,8 +507,7 @@ def test_explicit_overload_selection(self): atype = Array[System.Object] value = MethodTest.Overloaded.__overloads__[str, int, atype]( - "one", 1, atype([1, 2, 3]) - ) + "one", 1, atype([1, 2, 3])) self.assertTrue(value == 3) value = MethodTest.Overloaded.__overloads__[str, int]("one", 1) @@ -530,151 +520,152 @@ def test_overload_selection_with_array_types(self): """Check overload selection using array types.""" from Python.Test import ISayHello1, InterfaceTest, ShortEnum from System import Array + inst = InterfaceTest() vtype = Array[System.Boolean] - input = vtype([True, True]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([True, True]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == True) self.assertTrue(value[1] == True) vtype = Array[bool] - input = vtype([True, True]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([True, True]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == True) self.assertTrue(value[1] == True) vtype = Array[System.Byte] - input = vtype([0, 255]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, 255]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == 255) vtype = Array[System.SByte] - input = vtype([0, 127]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, 127]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == 127) vtype = Array[System.Char] - input = vtype([u'A', u'Z']) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([u'A', u'Z']) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == u'A') self.assertTrue(value[1] == u'Z') vtype = Array[System.Char] - input = vtype([0, 65535]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, 65535]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == unichr(0)) self.assertTrue(value[1] == unichr(65535)) vtype = Array[System.Int16] - input = vtype([0, 32767]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, 32767]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == 32767) vtype = Array[System.Int32] - input = vtype([0, 2147483647]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, 2147483647]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == 2147483647) vtype = Array[int] - input = vtype([0, 2147483647]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, 2147483647]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == 2147483647) vtype = Array[System.Int64] - input = vtype([0, long(9223372036854775807)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, long(9223372036854775807)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == long(9223372036854775807)) # Python 3 has no explicit long type, use System.Int64 instead if PY2: vtype = Array[long] - input = vtype([0, long(9223372036854775807)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, long(9223372036854775807)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == long(9223372036854775807)) vtype = Array[System.UInt16] - input = vtype([0, 65000]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, 65000]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == 65000) vtype = Array[System.UInt32] - input = vtype([0, long(4294967295)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, long(4294967295)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == long(4294967295)) vtype = Array[System.UInt64] - input = vtype([0, long(18446744073709551615)]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0, long(18446744073709551615)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0) self.assertTrue(value[1] == long(18446744073709551615)) vtype = Array[System.Single] - input = vtype([0.0, 3.402823e38]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0.0, 3.402823e38]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0.0) self.assertTrue(value[1] == 3.402823e38) vtype = Array[System.Double] - input = vtype([0.0, 1.7976931348623157e308]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0.0, 1.7976931348623157e308]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0.0) self.assertTrue(value[1] == 1.7976931348623157e308) vtype = Array[float] - input = vtype([0.0, 1.7976931348623157e308]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([0.0, 1.7976931348623157e308]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == 0.0) self.assertTrue(value[1] == 1.7976931348623157e308) vtype = Array[System.Decimal] - input = vtype([System.Decimal.Zero, System.Decimal.One]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([System.Decimal.Zero, System.Decimal.One]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == System.Decimal.Zero) self.assertTrue(value[1] == System.Decimal.One) vtype = Array[System.String] - input = vtype(["one", "two"]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(["one", "two"]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == "one") self.assertTrue(value[1] == "two") vtype = Array[str] - input = vtype(["one", "two"]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype(["one", "two"]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == "one") self.assertTrue(value[1] == "two") vtype = Array[ShortEnum] - input = vtype([ShortEnum.Zero, ShortEnum.One]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([ShortEnum.Zero, ShortEnum.One]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0] == ShortEnum.Zero) self.assertTrue(value[1] == ShortEnum.One) vtype = Array[System.Object] - input = vtype([inst, inst]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([inst, inst]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].__class__ == inst.__class__) self.assertTrue(value[1].__class__ == inst.__class__) vtype = Array[InterfaceTest] - input = vtype([inst, inst]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([inst, inst]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].__class__ == inst.__class__) self.assertTrue(value[1].__class__ == inst.__class__) vtype = Array[ISayHello1] - input = vtype([inst, inst]) - value = MethodTest.Overloaded.__overloads__[vtype](input) + input_ = vtype([inst, inst]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) self.assertTrue(value[0].__class__ == inst.__class__) self.assertTrue(value[1].__class__ == inst.__class__) @@ -682,27 +673,26 @@ def test_explicit_overload_selection_failure(self): """Check that overload selection fails correctly.""" with self.assertRaises(TypeError): - value = MethodTest.Overloaded.__overloads__[System.Type](True) + _ = MethodTest.Overloaded.__overloads__[System.Type](True) with self.assertRaises(TypeError): - value = MethodTest.Overloaded.__overloads__[int, int](1, 1) + _ = MethodTest.Overloaded.__overloads__[int, int](1, 1) with self.assertRaises(TypeError): - value = MethodTest.Overloaded.__overloads__[str, int, int]( - "", 1, 1 - ) + _ = MethodTest.Overloaded.__overloads__[str, int, int]("", 1, 1) with self.assertRaises(TypeError): - value = MethodTest.Overloaded.__overloads__[int, long](1) + _ = MethodTest.Overloaded.__overloads__[int, long](1) def test_we_can_bind_to_encoding_get_string(self): - """Check that we can bind to the Encoding.GetString method with variables.""" - + """Check that we can bind to the Encoding.GetString method + with variables.""" from System.Text import Encoding from System.IO import MemoryStream - myBytes = Encoding.UTF8.GetBytes('Some testing string') + + my_bytes = Encoding.UTF8.GetBytes('Some testing string') stream = MemoryStream() - stream.Write(myBytes, 0, myBytes.Length) + stream.Write(my_bytes, 0, my_bytes.Length) stream.Position = 0 buff = System.Array.CreateInstance(System.Byte, 3) diff --git a/src/tests/test_module.py b/src/tests/test_module.py index ad27cae9b..45f20a911 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -1,13 +1,14 @@ # -*- coding: utf-8 -*- import clr +import time import types import unittest import warnings from fnmatch import fnmatch from _compat import ClassType, PY2, PY3, range -from utils import isCLRClass, isCLRModule, isCLRRootModule +from utils import is_clr_class, is_clr_module, is_clr_root_module # testImplicitAssemblyLoad() passes on deprecation warning; perfect! # @@ -24,7 +25,7 @@ def test_import_hook_works(self): def test_import_clr(self): import clr - self.assertTrue(isCLRRootModule(clr)) + self.assertTrue(is_clr_root_module(clr)) def test_version_clr(self): import clr @@ -60,13 +61,13 @@ def test_module_interface(self): self.assertTrue(fnmatch(system_file, "*System*.dll") or fnmatch(system_file, "*mscorlib.dll"), "unexpected System.__file__: " + system_file) self.assertTrue(System.__doc__.startswith("Namespace containing types from the following assemblies:")) - self.assertTrue(isCLRClass(System.String)) - self.assertTrue(isCLRClass(System.Int32)) + self.assertTrue(is_clr_class(System.String)) + self.assertTrue(is_clr_class(System.Int32)) def test_simple_import(self): """Test simple import.""" import System - self.assertTrue(isCLRModule(System)) + self.assertTrue(is_clr_module(System)) self.assertTrue(System.__name__ == 'System') import sys @@ -85,7 +86,7 @@ def test_simple_import(self): def test_simple_import_with_alias(self): """Test simple import with aliasing.""" import System as mySystem - self.assertTrue(isCLRModule(mySystem)) + self.assertTrue(is_clr_module(mySystem)) self.assertTrue(mySystem.__name__ == 'System') import sys as mySys @@ -104,7 +105,7 @@ def test_simple_import_with_alias(self): def test_dotted_name_import(self): """Test dotted-name import.""" import System.Reflection - self.assertTrue(isCLRModule(System.Reflection)) + self.assertTrue(is_clr_module(System.Reflection)) self.assertTrue(System.Reflection.__name__ == 'System.Reflection') import xml.dom @@ -114,16 +115,16 @@ def test_dotted_name_import(self): def test_multiple_dotted_name_import(self): """Test an import bug with multiple dotted imports.""" import System.Data - self.assertTrue(isCLRModule(System.Data)) + self.assertTrue(is_clr_module(System.Data)) self.assertTrue(System.Data.__name__ == 'System.Data') import System.Data - self.assertTrue(isCLRModule(System.Data)) + self.assertTrue(is_clr_module(System.Data)) self.assertTrue(System.Data.__name__ == 'System.Data') def test_dotted_name_import_with_alias(self): """Test dotted-name import with aliasing.""" import System.Reflection as SysRef - self.assertTrue(isCLRModule(SysRef)) + self.assertTrue(is_clr_module(SysRef)) self.assertTrue(SysRef.__name__ == 'System.Reflection') import xml.dom as myDom @@ -133,7 +134,7 @@ def test_dotted_name_import_with_alias(self): def test_simple_import_from(self): """Test simple 'import from'.""" from System import Reflection - self.assertTrue(isCLRModule(Reflection)) + self.assertTrue(is_clr_module(Reflection)) self.assertTrue(Reflection.__name__ == 'System.Reflection') from xml import dom @@ -143,7 +144,7 @@ def test_simple_import_from(self): def test_simple_import_from_with_alias(self): """Test simple 'import from' with aliasing.""" from System import Collections as Coll - self.assertTrue(isCLRModule(Coll)) + self.assertTrue(is_clr_module(Coll)) self.assertTrue(Coll.__name__ == 'System.Collections') from xml import dom as myDom @@ -153,13 +154,12 @@ def test_simple_import_from_with_alias(self): def test_dotted_name_import_from(self): """Test dotted-name 'import from'.""" from System.Collections import Specialized - self.assertTrue(isCLRModule(Specialized)) + self.assertTrue(is_clr_module(Specialized)) self.assertTrue( - Specialized.__name__ == 'System.Collections.Specialized' - ) + Specialized.__name__ == 'System.Collections.Specialized') from System.Collections.Specialized import StringCollection - self.assertTrue(isCLRClass(StringCollection)) + self.assertTrue(is_clr_class(StringCollection)) self.assertTrue(StringCollection.__name__ == 'StringCollection') from xml.dom import pulldom @@ -173,11 +173,11 @@ def test_dotted_name_import_from(self): def test_dotted_name_import_from_with_alias(self): """Test dotted-name 'import from' with aliasing.""" from System.Collections import Specialized as Spec - self.assertTrue(isCLRModule(Spec)) + self.assertTrue(is_clr_module(Spec)) self.assertTrue(Spec.__name__ == 'System.Collections.Specialized') from System.Collections.Specialized import StringCollection as SC - self.assertTrue(isCLRClass(SC)) + self.assertTrue(is_clr_class(SC)) self.assertTrue(SC.__name__ == 'StringCollection') from xml.dom import pulldom as myPulldom @@ -193,7 +193,7 @@ def test_from_module_import_star(self): count = len(locals().keys()) m = __import__('System.Xml', globals(), locals(), ['*']) self.assertTrue(m.__name__ == 'System.Xml') - self.assertTrue(isCLRModule(m)) + self.assertTrue(is_clr_module(m)) self.assertTrue(len(locals().keys()) > count + 1) def test_implicit_assembly_load(self): @@ -211,10 +211,10 @@ def test_implicit_assembly_load(self): with warnings.catch_warnings(record=True) as w: clr.AddReference("System.Windows.Forms") import System.Windows.Forms as Forms - self.assertTrue(isCLRModule(Forms)) + self.assertTrue(is_clr_module(Forms)) self.assertTrue(Forms.__name__ == 'System.Windows.Forms') from System.Windows.Forms import Form - self.assertTrue(isCLRClass(Form)) + self.assertTrue(is_clr_class(Form)) self.assertTrue(Form.__name__ == 'Form') self.assertEqual(len(w), 0) @@ -241,7 +241,7 @@ def test_implicit_load_already_valid_namespace(self): # Python runtime to "do the right thing", allowing types from both # assemblies to be found in the System module implicitly. import System - self.assertTrue(isCLRClass(System.UriBuilder)) + self.assertTrue(is_clr_class(System.UriBuilder)) def test_import_non_existant_module(self): """Test import failure for a non-existent module.""" @@ -252,7 +252,7 @@ def test_lookup_no_namespace_type(self): """Test lookup of types without a qualified namespace.""" import Python.Test import clr - self.assertTrue(isCLRClass(clr.NoNamespaceType)) + self.assertTrue(is_clr_class(clr.NoNamespaceType)) def test_module_lookup_recursion(self): """Test for recursive lookup handling.""" @@ -262,23 +262,23 @@ def test_module_lookup_recursion(self): with self.assertRaises(AttributeError): import System - x = System.System + _ = System.System def test_module_get_attr(self): """Test module getattr behavior.""" import System int_type = System.Int32 - self.assertTrue(isCLRClass(int_type)) + self.assertTrue(is_clr_class(int_type)) module = System.Xml - self.assertTrue(isCLRModule(module)) + self.assertTrue(is_clr_module(module)) with self.assertRaises(AttributeError): - spam = System.Spam + _ = System.Spam with self.assertRaises(TypeError): - spam = getattr(System, 1) + _ = getattr(System, 1) def test_module_attr_abuse(self): """Test handling of attempts to set module attributes.""" @@ -322,26 +322,25 @@ def test_clr_add_reference(self): from System.IO import FileNotFoundException for name in ("System", "Python.Runtime"): assy = AddReference(name) - assyName = assy.GetName().Name - self.assertEqual(assyName, name) + assy_name = assy.GetName().Name + self.assertEqual(assy_name, name) with self.assertRaises(FileNotFoundException): AddReference("somethingtotallysilly") def test_assembly_load_thread_safety(self): - import time from Python.Test import ModuleTest # spin up .NET thread which loads assemblies and triggers AppDomain.AssemblyLoad event ModuleTest.RunThreads() time.sleep(1e-5) - for i in range(1, 100): + 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 - dict = Dictionary[Guid, DateTime]() + _ = Dictionary[Guid, DateTime]() ModuleTest.JoinThreads() diff --git a/src/tests/test_property.py b/src/tests/test_property.py index 8f1d5f9e1..8fb37768a 100644 --- a/src/tests/test_property.py +++ b/src/tests/test_property.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# + import unittest from Python.Test import PropertyTest @@ -70,25 +70,25 @@ def test_internal_property(self): """Test internal properties.""" with self.assertRaises(AttributeError): - PropertyTest().InternalProperty + _ = PropertyTest().InternalProperty with self.assertRaises(AttributeError): - PropertyTest().InternalStaticProperty + _ = PropertyTest().InternalStaticProperty with self.assertRaises(AttributeError): - PropertyTest.InternalStaticProperty + _ = PropertyTest.InternalStaticProperty def test_private_property(self): """Test private properties.""" with self.assertRaises(AttributeError): - PropertyTest().PrivateProperty + _ = PropertyTest().PrivateProperty with self.assertRaises(AttributeError): - PropertyTest().PrivateStaticProperty + _ = PropertyTest().PrivateStaticProperty with self.assertRaises(AttributeError): - PropertyTest.PrivateStaticProperty + _ = PropertyTest.PrivateStaticProperty def test_property_descriptor_get_set(self): """Test property descriptor get / set.""" diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index a1caa27a9..922e2651c 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -11,8 +11,8 @@ from _compat import range -# class that implements the test interface class InterfaceTestClass(IInterfaceTest): + """class that implements the test interface""" __namespace__ = "Python.Test" def foo(self): @@ -22,8 +22,8 @@ def bar(self, x, i): return "/".join([x] * i) -# class that derives from a class deriving from IInterfaceTest class DerivedClass(SubClassTest): + """class that derives from a class deriving from IInterfaceTest""" __namespace__ = "Python.Test" def foo(self): @@ -46,8 +46,8 @@ def return_list(self): return l -# class that implements IInterfaceTest.TestEvent class DerivedEventTest(IInterfaceTest): + """class that implements IInterfaceTest.TestEvent""" __namespace__ = "Python.Test" def __init__(self): @@ -67,7 +67,7 @@ def OnTestEvent(self, value): class SubClassTests(unittest.TestCase): - """Test subclassing managed types""" + """Test sub-classing managed types""" def test_base_class(self): """Test base class managed type""" diff --git a/src/tests/test_suite/test_callback.py b/src/tests/test_suite/test_callback.py index 412a27a66..2cb234442 100644 --- a/src/tests/test_suite/test_callback.py +++ b/src/tests/test_suite/test_callback.py @@ -15,18 +15,18 @@ def test_default_for_null(self): from Python.Test import CallbackTest test_instance = CallbackTest() - retVal = test_instance.Call_simpleDefaultArg_WithNull(__name__) - pythonRetVal = simpleDefaultArg(None) - self.assertEquals(retVal, pythonRetVal) + ret_val = test_instance.Call_simpleDefaultArg_WithNull(__name__) + python_ret_val = simpleDefaultArg(None) + self.assertEquals(ret_val, python_ret_val) def test_default_for_none(self): """Test that C# can use no argument for an optional python argument""" from Python.Test import CallbackTest test_instance = CallbackTest() - retVal = test_instance.Call_simpleDefaultArg_WithEmptyArgs(__name__) - pythonRetVal = simpleDefaultArg() - self.assertEquals(retVal, pythonRetVal) + ret_val = test_instance.Call_simpleDefaultArg_WithEmptyArgs(__name__) + python_ret_val = simpleDefaultArg() + self.assertEquals(ret_val, python_ret_val) def test_suite(): diff --git a/src/tests/test_thread.py b/src/tests/test_thread.py index 0f947933a..623be60a0 100644 --- a/src/tests/test_thread.py +++ b/src/tests/test_thread.py @@ -1,18 +1,11 @@ # -*- coding: utf-8 -*- -from __future__ import print_function - import threading import time import unittest from _compat import range, thread - - -def dprint(msg): - # Debugging helper to trace thread-related tests. - if 0: - print(msg) +from utils import dprint class ThreadTests(unittest.TestCase): diff --git a/src/tests/utils.py b/src/tests/utils.py index dd4d8767d..6729d7b30 100644 --- a/src/tests/utils.py +++ b/src/tests/utils.py @@ -5,14 +5,22 @@ Refactor utility functions and classes """ +from __future__ import print_function + from _compat import PY2, PY3 -def isCLRModule(ob): +def dprint(msg): + # Debugging helper to trace thread-related tests. + if 0: + print(msg) + + +def is_clr_module(ob): return type(ob).__name__ == 'ModuleObject' -def isCLRRootModule(ob): +def is_clr_root_module(ob): if PY3: # in Python 3 the clr module is a normal python module return ob.__name__ == "clr" @@ -20,7 +28,7 @@ def isCLRRootModule(ob): return type(ob).__name__ == 'CLRModule' -def isCLRClass(ob): +def is_clr_class(ob): return type(ob).__name__ == 'CLR Metatype' # for now From 5ca887e29db9cec8514f78c993c3dd34ffa0dc11 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 22 Jan 2017 02:38:47 -0700 Subject: [PATCH 043/245] Fix tests comparison to None, True, False, isinstance - Replace type(()) with tuple to clarify intent --- src/tests/test_array.py | 44 ++++++++++---------- src/tests/test_class.py | 2 +- src/tests/test_compat.py | 32 +++++++-------- src/tests/test_conversion.py | 38 +++++++++--------- src/tests/test_delegate.py | 4 +- src/tests/test_enum.py | 4 +- src/tests/test_event.py | 24 +++++------ src/tests/test_field.py | 20 ++++----- src/tests/test_generic.py | 20 ++++----- src/tests/test_indexer.py | 54 ++++++++++++------------- src/tests/test_interface.py | 2 +- src/tests/test_method.py | 78 ++++++++++++++++++------------------ src/tests/test_module.py | 32 +++++++-------- 13 files changed, 177 insertions(+), 177 deletions(-) diff --git a/src/tests/test_array.py b/src/tests/test_array.py index bcd50e386..36f225c82 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -127,17 +127,17 @@ def test_boolean_array(self): self.assertTrue(len(items) == 5) - self.assertTrue(items[0] == True) - self.assertTrue(items[1] == False) - self.assertTrue(items[2] == True) - self.assertTrue(items[3] == False) - self.assertTrue(items[4] == True) + self.assertTrue(items[0] is True) + self.assertTrue(items[1] is False) + self.assertTrue(items[2] is True) + self.assertTrue(items[3] is False) + self.assertTrue(items[4] is True) items[0] = False - self.assertTrue(items[0] == False) + self.assertTrue(items[0] is False) items[0] = True - self.assertTrue(items[0] == True) + self.assertTrue(items[0] is True) with self.assertRaises(TypeError): ob = Test.ByteArrayTest() @@ -700,7 +700,7 @@ def test_object_array(self): self.assertTrue(items[0] == 99) items[0] = None - self.assertTrue(items[0] == None) + self.assertTrue(items[0] is None) with self.assertRaises(TypeError): ob = Test.ObjectArrayTest() @@ -717,20 +717,20 @@ def test_null_array(self): self.assertTrue(len(items) == 5) - self.assertTrue(items[0] == None) - self.assertTrue(items[4] == None) + self.assertTrue(items[0] is None) + self.assertTrue(items[4] is None) items[0] = "spam" self.assertTrue(items[0] == "spam") items[0] = None - self.assertTrue(items[0] == None) + self.assertTrue(items[0] is None) items[-4] = "spam" self.assertTrue(items[-4] == "spam") items[-1] = None - self.assertTrue(items[-1] == None) + self.assertTrue(items[-1] is None) empty = ob.empty self.assertTrue(len(empty) == 0) @@ -763,7 +763,7 @@ def test_interface_array(self): self.assertTrue(items[-1].GetValue() == "0") items[0] = None - self.assertTrue(items[0] == None) + self.assertTrue(items[0] is None) with self.assertRaises(TypeError): ob = Test.InterfaceArrayTest() @@ -801,7 +801,7 @@ def test_typed_array(self): self.assertTrue(items[-1].GetValue() == "0") items[0] = None - self.assertTrue(items[0] == None) + self.assertTrue(items[0] is None) with self.assertRaises(TypeError): ob = Test.TypedArrayTest() @@ -889,7 +889,7 @@ def test_array_iteration(self): items = Test.NullArrayTest().items for i in items: - self.assertTrue(i == None) + self.assertTrue(i is None) empty = Test.NullArrayTest().empty @@ -1008,7 +1008,7 @@ def test_tuple_array_conversion_type_checking(self): result = ArrayConversionTest.EchoRange(items) self.assertTrue(result[0].__class__ == Spam) - self.assertTrue(result[1] == None) + self.assertTrue(result[1] is None) self.assertTrue(len(result) == 10) with self.assertRaises(TypeError): @@ -1037,7 +1037,7 @@ def test_list_array_conversion_type_checking(self): result = ArrayConversionTest.EchoRange(items) self.assertTrue(result[0].__class__ == Spam) - self.assertTrue(result[1] == None) + self.assertTrue(result[1] is None) self.assertTrue(len(result) == 10) with self.assertRaises(TypeError): @@ -1064,7 +1064,7 @@ def test_sequence_array_conversion_type_checking(self): result = ArrayConversionTest.EchoRange(items) self.assertTrue(result[0].__class__ == Spam) - self.assertTrue(result[1] == None) + self.assertTrue(result[1] is None) self.assertTrue(len(result) == 10) with self.assertRaises(TypeError): @@ -1143,13 +1143,13 @@ def test_special_array_creation(self): inst = InterfaceTest() value = Array[System.Boolean]([True, True]) - self.assertTrue(value[0] == True) - self.assertTrue(value[1] == True) + self.assertTrue(value[0] is True) + self.assertTrue(value[1] is True) self.assertTrue(value.Length == 2) value = Array[bool]([True, True]) - self.assertTrue(value[0] == True) - self.assertTrue(value[1] == True) + self.assertTrue(value[0] is True) + self.assertTrue(value[1] is True) self.assertTrue(value.Length == 2) value = Array[System.Byte]([0, 255]) diff --git a/src/tests/test_class.py b/src/tests/test_class.py index 80cee9009..bf3b6f143 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -26,7 +26,7 @@ def test_class_standard_attrs(self): self.assertTrue(ClassTest.__name__ == 'ClassTest') self.assertTrue(ClassTest.__module__ == 'Python.Test') - self.assertTrue(type(ClassTest.__dict__) == DictProxyType) + self.assertTrue(isinstance(ClassTest.__dict__, DictProxyType)) self.assertTrue(len(ClassTest.__doc__) > 0) def test_class_docstrings(self): diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index c26bb9e5d..cea51ca49 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -20,17 +20,17 @@ def test_simple_import(self): self.assertTrue(CLR.__name__ == 'clr') import sys - self.assertTrue(type(sys) == types.ModuleType) + self.assertTrue(isinstance(sys, types.ModuleType)) self.assertTrue(sys.__name__ == 'sys') if PY3: import http.client - self.assertTrue(type(http.client) == types.ModuleType) + self.assertTrue(isinstance(http.client, types.ModuleType)) self.assertTrue(http.client.__name__ == 'http.client') elif PY2: import httplib - self.assertTrue(type(httplib) == types.ModuleType) + self.assertTrue(isinstance(httplib, types.ModuleType)) self.assertTrue(httplib.__name__ == 'httplib') def test_simple_import_with_alias(self): @@ -40,17 +40,17 @@ def test_simple_import_with_alias(self): self.assertTrue(myCLR.__name__ == 'clr') import sys as mySys - self.assertTrue(type(mySys) == types.ModuleType) + self.assertTrue(isinstance(mySys, types.ModuleType)) self.assertTrue(mySys.__name__ == 'sys') if PY3: import http.client as myHttplib - self.assertTrue(type(myHttplib) == types.ModuleType) + self.assertTrue(isinstance(myHttplib, types.ModuleType)) self.assertTrue(myHttplib.__name__ == 'http.client') elif PY2: import httplib as myHttplib - self.assertTrue(type(myHttplib) == types.ModuleType) + self.assertTrue(isinstance(myHttplib, types.ModuleType)) self.assertTrue(myHttplib.__name__ == 'httplib') def test_dotted_name_import(self): @@ -66,7 +66,7 @@ def test_dotted_name_import(self): self.assertTrue(System is CLR.System) import xml.dom - self.assertTrue(type(xml.dom) == types.ModuleType) + self.assertTrue(isinstance(xml.dom, types.ModuleType)) self.assertTrue(xml.dom.__name__ == 'xml.dom') def test_dotted_name_import_with_alias(self): @@ -82,7 +82,7 @@ def test_dotted_name_import_with_alias(self): self.assertTrue(mySystem is myCLRSystem) import xml.dom as myDom - self.assertTrue(type(myDom) == types.ModuleType) + self.assertTrue(isinstance(myDom, types.ModuleType)) self.assertTrue(myDom.__name__ == 'xml.dom') def test_simple_import_from(self): @@ -92,7 +92,7 @@ def test_simple_import_from(self): self.assertTrue(System.__name__ == 'System') from xml import dom - self.assertTrue(type(dom) == types.ModuleType) + self.assertTrue(isinstance(dom, types.ModuleType)) self.assertTrue(dom.__name__ == 'xml.dom') def test_simple_import_from_with_alias(self): @@ -102,7 +102,7 @@ def test_simple_import_from_with_alias(self): self.assertTrue(mySystem.__name__ == 'System') from xml import dom as myDom - self.assertTrue(type(myDom) == types.ModuleType) + self.assertTrue(isinstance(myDom, types.ModuleType)) self.assertTrue(myDom.__name__ == 'xml.dom') def test_dotted_name_import_from(self): @@ -116,11 +116,11 @@ def test_dotted_name_import_from(self): self.assertTrue(XmlDocument.__name__ == 'XmlDocument') from xml.dom import pulldom - self.assertTrue(type(pulldom) == types.ModuleType) + self.assertTrue(isinstance(pulldom, types.ModuleType)) self.assertTrue(pulldom.__name__ == 'xml.dom.pulldom') from xml.dom.pulldom import PullDOM - self.assertTrue(type(PullDOM) == ClassType) + self.assertTrue(isinstance(PullDOM, ClassType)) self.assertTrue(PullDOM.__name__ == 'PullDOM') def test_dotted_name_import_from_with_alias(self): @@ -134,11 +134,11 @@ def test_dotted_name_import_from_with_alias(self): self.assertTrue(myXmlDocument.__name__ == 'XmlDocument') from xml.dom import pulldom as myPulldom - self.assertTrue(type(myPulldom) == types.ModuleType) + self.assertTrue(isinstance(myPulldom, types.ModuleType)) self.assertTrue(myPulldom.__name__ == 'xml.dom.pulldom') from xml.dom.pulldom import PullDOM as myPullDOM - self.assertTrue(type(myPullDOM) == ClassType) + self.assertTrue(isinstance(myPullDOM, ClassType)) self.assertTrue(myPullDOM.__name__ == 'PullDOM') def test_from_module_import_star(self): @@ -163,13 +163,13 @@ def test_explicit_assembly_load(self): import sys assembly = Assembly.LoadWithPartialName('System.Data') - self.assertTrue(assembly != None) + self.assertTrue(assembly is not None) import CLR.System.Data self.assertTrue('System.Data' in sys.modules) assembly = Assembly.LoadWithPartialName('SpamSpamSpamSpamEggsAndSpam') - self.assertTrue(assembly == None) + self.assertTrue(assembly is None) def test_implicit_load_already_valid_namespace(self): """Test implicit assembly load over an already valid namespace.""" diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index 8400292d5..0d0cd4008 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -14,52 +14,52 @@ class ConversionTests(unittest.TestCase): def test_bool_conversion(self): """Test bool conversion.""" ob = ConversionTest() - self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField == 0) ob.BooleanField = True - self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) self.assertTrue(ob.BooleanField is True) self.assertTrue(ob.BooleanField == 1) ob.BooleanField = False - self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField == 0) ob.BooleanField = 1 - self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) self.assertTrue(ob.BooleanField is True) self.assertTrue(ob.BooleanField == 1) ob.BooleanField = 0 - self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField == 0) ob.BooleanField = System.Boolean(None) - self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField == 0) ob.BooleanField = System.Boolean('') - self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField == 0) ob.BooleanField = System.Boolean(0) - self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField is False) self.assertTrue(ob.BooleanField == 0) ob.BooleanField = System.Boolean(1) - self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) self.assertTrue(ob.BooleanField is True) self.assertTrue(ob.BooleanField == 1) ob.BooleanField = System.Boolean('a') - self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) self.assertTrue(ob.BooleanField is True) self.assertTrue(ob.BooleanField == 1) @@ -531,7 +531,7 @@ def test_string_conversion(self): self.assertTrue(ob.StringField == u'\uffff\uffff') ob.StringField = None - self.assertTrue(ob.StringField == None) + self.assertTrue(ob.StringField is None) with self.assertRaises(TypeError): ConversionTest().StringField = 1 @@ -552,7 +552,7 @@ def test_interface_conversion(self): # need to test spam subclass here. ob.SpamField = None - self.assertTrue(ob.SpamField == None) + self.assertTrue(ob.SpamField is None) with self.assertRaises(TypeError): ob = ConversionTest() @@ -567,14 +567,14 @@ def test_object_conversion(self): from Python.Test import Spam ob = ConversionTest() - self.assertTrue(ob.ObjectField == None) + self.assertTrue(ob.ObjectField is None) ob.ObjectField = Spam("eggs") self.assertTrue(ob.ObjectField.__class__.__name__ == "Spam") self.assertTrue(ob.ObjectField.GetValue() == "eggs") ob.ObjectField = None - self.assertTrue(ob.ObjectField == None) + self.assertTrue(ob.ObjectField is None) ob.ObjectField = System.String("spam") self.assertTrue(ob.ObjectField == "spam") @@ -627,13 +627,13 @@ def test_null_conversion(self): ob = ConversionTest() ob.StringField = None - self.assertTrue(ob.StringField == None) + self.assertTrue(ob.StringField is None) ob.ObjectField = None - self.assertTrue(ob.ObjectField == None) + self.assertTrue(ob.ObjectField is None) ob.SpamField = None - self.assertTrue(ob.SpamField == None) + self.assertTrue(ob.SpamField is None) # Primitive types and enums should not be set to null. @@ -647,7 +647,7 @@ def test_byte_array_conversion(self): """Test byte array conversion.""" ob = ConversionTest() - self.assertTrue(ob.ByteArrayField == None) + self.assertTrue(ob.ByteArrayField is None) ob.ByteArrayField = [0, 1, 2, 3, 4] array = ob.ByteArrayField @@ -665,7 +665,7 @@ def test_sbyte_array_conversion(self): """Test sbyte array conversion.""" ob = ConversionTest() - self.assertTrue(ob.SByteArrayField == None) + self.assertTrue(ob.SByteArrayField is None) ob.SByteArrayField = [0, 1, 2, 3, 4] array = ob.SByteArrayField diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index 1d0c30533..4963a09b8 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -20,8 +20,8 @@ def test_delegate_standard_attrs(self): self.assertTrue(PublicDelegate.__name__ == 'PublicDelegate') self.assertTrue(PublicDelegate.__module__ == 'Python.Test') - self.assertTrue(type(PublicDelegate.__dict__) == DictProxyType) - self.assertTrue(PublicDelegate.__doc__ == None) + self.assertTrue(isinstance(PublicDelegate.__dict__, DictProxyType)) + self.assertTrue(PublicDelegate.__doc__ is None) def test_global_delegate_visibility(self): """Test visibility of module-level delegates.""" diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index c24f5aabd..e7147e69c 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -16,8 +16,8 @@ def test_enum_standard_attrs(self): self.assertTrue(DayOfWeek.__name__ == 'DayOfWeek') self.assertTrue(DayOfWeek.__module__ == 'System') - self.assertTrue(type(DayOfWeek.__dict__) == DictProxyType) - self.assertTrue(DayOfWeek.__doc__ == None) + self.assertTrue(isinstance(DayOfWeek.__dict__, DictProxyType)) + self.assertTrue(DayOfWeek.__doc__ is None) def test_enum_get_member(self): """Test access to enum members.""" diff --git a/src/tests/test_event.py b/src/tests/test_event.py index de337c00b..237d60777 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -18,7 +18,7 @@ def test_public_instance_event(self): ob = EventTest() handler = GenericHandler() - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) ob.PublicEvent += handler.handler @@ -30,7 +30,7 @@ def test_public_instance_event(self): def test_public_static_event(self): """Test public static events.""" handler = GenericHandler() - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) EventTest.PublicStaticEvent += handler.handler @@ -42,7 +42,7 @@ def test_protected_instance_event(self): ob = EventTest() handler = GenericHandler() - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) ob.ProtectedEvent += handler.handler @@ -54,7 +54,7 @@ def test_protected_instance_event(self): def test_protected_static_event(self): """Test protected static events.""" handler = GenericHandler() - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) EventTest.ProtectedStaticEvent += handler.handler @@ -121,7 +121,7 @@ def test_instance_method_handler(self): handler = GenericHandler() ob.PublicEvent += handler.handler - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) @@ -138,7 +138,7 @@ def test_var_args_instance_method_handler(self): handler = VariableArgsHandler() ob.PublicEvent += handler.handler - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) @@ -155,7 +155,7 @@ def test_callableob_handler(self): handler = CallableHandler() ob.PublicEvent += handler - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) @@ -172,7 +172,7 @@ def test_var_args_callable_handler(self): handler = VarCallableHandler() ob.PublicEvent += handler - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) @@ -190,7 +190,7 @@ def test_static_method_handler(self): StaticMethodHandler.value = None ob.PublicEvent += handler.handler - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) @@ -208,7 +208,7 @@ def test_class_method_handler(self): ClassMethodHandler.value = None ob.PublicEvent += handler.handler - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) @@ -271,7 +271,7 @@ def handler(sender, args, dict_=dict_): dict_['value'] = args.value ob.PublicEvent += handler - self.assertTrue(dict_['value'] == None) + self.assertTrue(dict_['value'] is None) ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(dict_['value'] == 10) @@ -515,7 +515,7 @@ def test_explicit_cls_event_registration(self): delegate = TestEventHandler(handler.handler) ob.add_PublicEvent(delegate) - self.assertTrue(handler.value == None) + self.assertTrue(handler.value is None) ob.OnPublicEvent(TestEventArgs(10)) self.assertTrue(handler.value == 10) diff --git a/src/tests/test_field.py b/src/tests/test_field.py index 6300309ce..b1d596fea 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -182,19 +182,19 @@ def test_boolean_field(self): """Test boolean fields.""" # change this to true / false later for Python 2.3? ob = FieldTest() - self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) ob.BooleanField = True - self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) ob.BooleanField = False - self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) ob.BooleanField = 1 - self.assertTrue(ob.BooleanField == True) + self.assertTrue(ob.BooleanField is True) ob.BooleanField = 0 - self.assertTrue(ob.BooleanField == False) + self.assertTrue(ob.BooleanField is False) def test_sbyte_field(self): """Test sbyte fields.""" @@ -322,7 +322,7 @@ def test_interface_field(self): def test_object_field(self): """Test ob fields.""" ob = FieldTest() - self.assertTrue(ob.ObjectField == None) + self.assertTrue(ob.ObjectField is None) ob.ObjectField = System.String("spam") self.assertTrue(ob.ObjectField == "spam") @@ -331,7 +331,7 @@ def test_object_field(self): self.assertTrue(ob.ObjectField == 1) ob.ObjectField = None - self.assertTrue(ob.ObjectField == None) + self.assertTrue(ob.ObjectField is None) def test_enum_field(self): """Test enum fields.""" @@ -348,13 +348,13 @@ def test_nullable_field(self): ob = FieldTest() ob.StringField = None - self.assertTrue(ob.StringField == None) + self.assertTrue(ob.StringField is None) ob.ObjectField = None - self.assertTrue(ob.ObjectField == None) + self.assertTrue(ob.ObjectField is None) ob.SpamField = None - self.assertTrue(ob.SpamField == None) + self.assertTrue(ob.SpamField is None) # Primitive types and enums should not be set to null. diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index fb5e0e5ea..8d5ea4c4c 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -159,12 +159,12 @@ def test_python_type_aliasing(self): dict_ = Dictionary[bool, bool]() self.assertEquals(dict_.Count, 0) dict_.Add(True, False) - self.assertTrue(dict_[True] == False) + self.assertTrue(dict_[True] is False) dict_ = Dictionary[System.Boolean, System.Boolean]() self.assertEquals(dict_.Count, 0) dict_.Add(True, False) - self.assertTrue(dict_[True] == False) + self.assertTrue(dict_[True] is False) def test_generic_reference_type(self): """Test usage of generic reference type definitions.""" @@ -398,11 +398,11 @@ def test_generic_method_overload_selection(self): # public static Q Overloaded(Q arg) value = type.Overloaded[bool](True) - self.assertTrue(value == True) + self.assertTrue(value is True) # public Q Overloaded(Q arg) value = inst.Overloaded[bool](True) - self.assertTrue(value == True) + self.assertTrue(value is True) # public static U Overloaded(Q arg1, U arg2) value = type.Overloaded[bool, str](True, "true") @@ -414,11 +414,11 @@ def test_generic_method_overload_selection(self): # public static U Overloaded(Q arg1, U arg2) value = type.Overloaded[str, bool]("true", True) - self.assertTrue(value == True) + self.assertTrue(value is True) # public U Overloaded(Q arg1, U arg2) value = inst.Overloaded[str, bool]("true", True) - self.assertTrue(value == True) + self.assertTrue(value is True) # public static string Overloaded(int arg1, int arg2, string arg3) value = type.Overloaded[str](123, 456, "success") @@ -444,12 +444,12 @@ def test_method_overload_selection_with_generic_types(self): vtype = GenericWrapper[System.Boolean] input_ = vtype(True) value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == True) + self.assertTrue(value.value is True) vtype = GenericWrapper[bool] input_ = vtype(True) value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == True) + self.assertTrue(value.value is True) vtype = GenericWrapper[System.Byte] input_ = vtype(255) @@ -580,14 +580,14 @@ def test_overload_selection_with_arrays_of_generic_types(self): vtype = System.Array[gtype] input_ = vtype([gtype(True), gtype(True)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == True) + self.assertTrue(value[0].value is True) self.assertTrue(value.Length == 2) gtype = GenericWrapper[bool] vtype = System.Array[gtype] input_ = vtype([gtype(True), gtype(True)]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == True) + self.assertTrue(value[0].value is True) self.assertTrue(value.Length == 2) gtype = GenericWrapper[System.Byte] diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index 62581aed4..422f7282e 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -20,7 +20,7 @@ def test_public_indexer(self): ob[1] = "one" self.assertTrue(ob[1] == "one") - self.assertTrue(ob[10] == None) + self.assertTrue(ob[10] is None) def test_protected_indexer(self): """Test protected indexers.""" @@ -32,7 +32,7 @@ def test_protected_indexer(self): ob[1] = "one" self.assertTrue(ob[1] == "one") - self.assertTrue(ob[10] == None) + self.assertTrue(ob[10] is None) def test_internal_indexer(self): """Test internal indexers.""" @@ -64,8 +64,8 @@ def test_boolean_indexer(self): """Test boolean indexers.""" ob = Test.BooleanIndexerTest() - self.assertTrue(ob[True] == None) - self.assertTrue(ob[1] == None) + self.assertTrue(ob[True] is None) + self.assertTrue(ob[1] is None) ob[0] = "false" self.assertTrue(ob[0] == "false") @@ -85,7 +85,7 @@ def test_byte_indexer(self): max_ = 255 min_ = 0 - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = str(max_) self.assertTrue(ob[max_] == str(max_)) @@ -107,7 +107,7 @@ def test_sbyte_indexer(self): max_ = 127 min_ = -128 - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = str(max_) self.assertTrue(ob[max_] == str(max_)) @@ -129,7 +129,7 @@ def test_char_indexer(self): max_ = unichr(65535) min_ = unichr(0) - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = "max_" self.assertTrue(ob[max_] == "max_") @@ -151,7 +151,7 @@ def test_int16_indexer(self): max_ = 32767 min_ = -32768 - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = str(max_) self.assertTrue(ob[max_] == str(max_)) @@ -173,7 +173,7 @@ def test_int32_indexer(self): max_ = 2147483647 min_ = -2147483648 - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = str(max_) self.assertTrue(ob[max_] == str(max_)) @@ -195,7 +195,7 @@ def test_int64_indexer(self): max_ = long(9223372036854775807) min_ = long(-9223372036854775808) - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = str(max_) self.assertTrue(ob[max_] == str(max_)) @@ -217,7 +217,7 @@ def test_uint16_indexer(self): max_ = 65535 min_ = 0 - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = str(max_) self.assertTrue(ob[max_] == str(max_)) @@ -239,7 +239,7 @@ def test_uint32_indexer(self): max_ = long(4294967295) min_ = 0 - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = str(max_) self.assertTrue(ob[max_] == str(max_)) @@ -261,7 +261,7 @@ def test_uint64_indexer(self): max_ = long(18446744073709551615) min_ = 0 - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = str(max_) self.assertTrue(ob[max_] == str(max_)) @@ -283,7 +283,7 @@ def test_single_indexer(self): max_ = 3.402823e38 min_ = -3.402823e38 - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = "max_" self.assertTrue(ob[max_] == "max_") @@ -305,7 +305,7 @@ def test_double_indexer(self): max_ = 1.7976931348623157e308 min_ = -1.7976931348623157e308 - self.assertTrue(ob[max_] == None) + self.assertTrue(ob[max_] is None) ob[max_] = "max_" self.assertTrue(ob[max_] == "max_") @@ -329,7 +329,7 @@ def test_decimal_indexer(self): max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") - self.assertTrue(ob[max_d] == None) + self.assertTrue(ob[max_d] is None) ob[max_d] = "max_" self.assertTrue(ob[max_d] == "max_") @@ -349,8 +349,8 @@ def test_string_indexer(self): """Test String indexers.""" ob = Test.StringIndexerTest() - self.assertTrue(ob["spam"] == None) - self.assertTrue(ob[u"spam"] == None) + self.assertTrue(ob["spam"] is None) + self.assertTrue(ob[u"spam"] is None) ob["spam"] = "spam" self.assertTrue(ob["spam"] == "spam") @@ -378,7 +378,7 @@ def test_enum_indexer(self): key = Test.ShortEnum.One - self.assertTrue(ob[key] == None) + self.assertTrue(ob[key] is None) ob[key] = "spam" self.assertTrue(ob[key] == "spam") @@ -404,10 +404,10 @@ def test_object_indexer(self): from Python.Test import Spam spam = Spam("spam") - self.assertTrue(ob[spam] == None) - self.assertTrue(ob["spam"] == None) - self.assertTrue(ob[1] == None) - self.assertTrue(ob[None] == None) + self.assertTrue(ob[spam] is None) + self.assertTrue(ob["spam"] is None) + self.assertTrue(ob[1] is None) + self.assertTrue(ob[None] is None) ob[spam] = "spam" self.assertTrue(ob[spam] == "spam") @@ -436,7 +436,7 @@ def test_interface_indexer(self): from Python.Test import Spam spam = Spam("spam") - self.assertTrue(ob[spam] == None) + self.assertTrue(ob[spam] is None) ob[spam] = "spam" self.assertTrue(ob[spam] == "spam") @@ -459,7 +459,7 @@ def test_typed_indexer(self): from Python.Test import Spam spam = Spam("spam") - self.assertTrue(ob[spam] == None) + self.assertTrue(ob[spam] is None) ob[spam] = "spam" self.assertTrue(ob[spam] == "spam") @@ -485,7 +485,7 @@ def test_multi_arg_indexer(self): ob[1, 9] = "one nine" self.assertTrue(ob[1, 9] == "one nine") - self.assertTrue(ob[10, 50] == None) + self.assertTrue(ob[10, 50] is None) with self.assertRaises(TypeError): ob = Test.MultiArgIndexerTest() @@ -553,7 +553,7 @@ def test_unbound_indexer(self): Test.PublicIndexerTest.__setitem__(ob, 1, "one") self.assertTrue(ob[1] == "one") - self.assertTrue(ob[10] == None) + self.assertTrue(ob[10] is None) def test_indexer_abuse(self): """Test indexer abuse.""" diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index d83a7a9f1..1fac36eb8 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -16,7 +16,7 @@ def test_interface_standard_attrs(self): self.assertTrue(IPublicInterface.__name__ == 'IPublicInterface') self.assertTrue(IPublicInterface.__module__ == 'Python.Test') - self.assertTrue(type(IPublicInterface.__dict__) == DictProxyType) + self.assertTrue(isinstance(IPublicInterface.__dict__, DictProxyType)) def test_global_interface_visibility(self): """Test visibility of module-level interfaces.""" diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 07b73a1e7..6c4454004 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -189,7 +189,7 @@ def test_null_array_conversion(self): """Test null array conversion in method call.""" ob = MethodTest() r = ob.TestNullArrayConversion(None) - self.assertTrue(r == None) + self.assertTrue(r is None) def test_string_params_args(self): """Test use of string params.""" @@ -243,37 +243,37 @@ def test_non_params_array_in_last_place(self): def test_string_out_params(self): """Test use of string out-parameters.""" result = MethodTest.TestStringOutParams("hi", "there") - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == "output string") result = MethodTest.TestStringOutParams("hi", None) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == "output string") def test_string_ref_params(self): """Test use of string byref parameters.""" result = MethodTest.TestStringRefParams("hi", "there") - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == "output string") result = MethodTest.TestStringRefParams("hi", None) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == "output string") def test_value_out_params(self): """Test use of value type out-parameters.""" result = MethodTest.TestValueOutParams("hi", 1) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == 42) # None cannot be converted to a value type like int, long, etc. @@ -283,9 +283,9 @@ def test_value_out_params(self): def test_value_ref_params(self): """Test use of value type byref parameters.""" result = MethodTest.TestValueRefParams("hi", 1) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == 42) # None cannot be converted to a value type like int, long, etc. @@ -295,37 +295,37 @@ def test_value_ref_params(self): def test_object_out_params(self): """Test use of object out-parameters.""" result = MethodTest.TestObjectOutParams("hi", MethodTest()) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertTrue(len(result) == 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(isinstance(result[1], System.Exception)) result = MethodTest.TestObjectOutParams("hi", None) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(isinstance(result[1], System.Exception)) def test_object_ref_params(self): """Test use of object byref parameters.""" result = MethodTest.TestObjectRefParams("hi", MethodTest()) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(isinstance(result[1], System.Exception)) result = MethodTest.TestObjectRefParams("hi", None) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(isinstance(result[1], System.Exception)) def test_struct_out_params(self): """Test use of struct out-parameters.""" result = MethodTest.TestStructOutParams("hi", System.Guid.NewGuid()) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(isinstance(result[1], System.Guid)) # None cannot be converted to a value type like a struct @@ -335,9 +335,9 @@ def test_struct_out_params(self): def test_struct_ref_params(self): """Test use of struct byref parameters.""" result = MethodTest.TestStructRefParams("hi", System.Guid.NewGuid()) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertTrue(len(result) == 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(isinstance(result[1], System.Guid)) # None cannot be converted to a value type like a struct @@ -388,16 +388,16 @@ def test_explicit_selection_with_out_modifier(self): refstr = System.String("").GetType().MakeByRefType() result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( "hi", "there") - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertTrue(len(result) == 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == "output string") result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( "hi", None) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertTrue(len(result) == 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == "output string") def test_explicit_selection_with_ref_modifier(self): @@ -405,16 +405,16 @@ def test_explicit_selection_with_ref_modifier(self): refstr = System.String("").GetType().MakeByRefType() result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( "hi", "there") - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertTrue(len(result) == 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == "output string") result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( "hi", None) - self.assertTrue(type(result) == type(())) + self.assertTrue(isinstance(result, tuple)) self.assertTrue(len(result) == 2) - self.assertTrue(result[0] == True) + self.assertTrue(result[0] is True) self.assertTrue(result[1] == "output string") def test_explicit_overload_selection(self): @@ -425,10 +425,10 @@ def test_explicit_overload_selection(self): inst = InterfaceTest() value = MethodTest.Overloaded.__overloads__[System.Boolean](True) - self.assertTrue(value == True) + self.assertTrue(value is True) value = MethodTest.Overloaded.__overloads__[bool](True) - self.assertTrue(value == True) + self.assertTrue(value is True) value = MethodTest.Overloaded.__overloads__[System.Byte](255) self.assertTrue(value == 255) @@ -526,14 +526,14 @@ def test_overload_selection_with_array_types(self): vtype = Array[System.Boolean] input_ = vtype([True, True]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == True) - self.assertTrue(value[1] == True) + self.assertTrue(value[0] is True) + self.assertTrue(value[1] is True) vtype = Array[bool] input_ = vtype([True, True]) value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == True) - self.assertTrue(value[1] == True) + self.assertTrue(value[0] is True) + self.assertTrue(value[1] is True) vtype = Array[System.Byte] input_ = vtype([0, 255]) diff --git a/src/tests/test_module.py b/src/tests/test_module.py index 45f20a911..5ee8e6fc2 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -71,16 +71,16 @@ def test_simple_import(self): self.assertTrue(System.__name__ == 'System') import sys - self.assertTrue(type(sys) == types.ModuleType) + self.assertTrue(isinstance(sys, types.ModuleType)) self.assertTrue(sys.__name__ == 'sys') if PY3: import http.client as httplib - self.assertTrue(type(httplib) == types.ModuleType) + self.assertTrue(isinstance(httplib, types.ModuleType)) self.assertTrue(httplib.__name__ == 'http.client') elif PY2: import httplib - self.assertTrue(type(httplib) == types.ModuleType) + self.assertTrue(isinstance(httplib, types.ModuleType)) self.assertTrue(httplib.__name__ == 'httplib') def test_simple_import_with_alias(self): @@ -90,16 +90,16 @@ def test_simple_import_with_alias(self): self.assertTrue(mySystem.__name__ == 'System') import sys as mySys - self.assertTrue(type(mySys) == types.ModuleType) + self.assertTrue(isinstance(mySys, types.ModuleType)) self.assertTrue(mySys.__name__ == 'sys') if PY3: import http.client as myHttplib - self.assertTrue(type(myHttplib) == types.ModuleType) + self.assertTrue(isinstance(myHttplib, types.ModuleType)) self.assertTrue(myHttplib.__name__ == 'http.client') elif PY2: import httplib as myHttplib - self.assertTrue(type(myHttplib) == types.ModuleType) + self.assertTrue(isinstance(myHttplib, types.ModuleType)) self.assertTrue(myHttplib.__name__ == 'httplib') def test_dotted_name_import(self): @@ -109,7 +109,7 @@ def test_dotted_name_import(self): self.assertTrue(System.Reflection.__name__ == 'System.Reflection') import xml.dom - self.assertTrue(type(xml.dom) == types.ModuleType) + self.assertTrue(isinstance(xml.dom, types.ModuleType)) self.assertTrue(xml.dom.__name__ == 'xml.dom') def test_multiple_dotted_name_import(self): @@ -128,7 +128,7 @@ def test_dotted_name_import_with_alias(self): self.assertTrue(SysRef.__name__ == 'System.Reflection') import xml.dom as myDom - self.assertTrue(type(myDom) == types.ModuleType) + self.assertTrue(isinstance(myDom, types.ModuleType)) self.assertTrue(myDom.__name__ == 'xml.dom') def test_simple_import_from(self): @@ -138,7 +138,7 @@ def test_simple_import_from(self): self.assertTrue(Reflection.__name__ == 'System.Reflection') from xml import dom - self.assertTrue(type(dom) == types.ModuleType) + self.assertTrue(isinstance(dom, types.ModuleType)) self.assertTrue(dom.__name__ == 'xml.dom') def test_simple_import_from_with_alias(self): @@ -148,7 +148,7 @@ def test_simple_import_from_with_alias(self): self.assertTrue(Coll.__name__ == 'System.Collections') from xml import dom as myDom - self.assertTrue(type(myDom) == types.ModuleType) + self.assertTrue(isinstance(myDom, types.ModuleType)) self.assertTrue(myDom.__name__ == 'xml.dom') def test_dotted_name_import_from(self): @@ -163,11 +163,11 @@ def test_dotted_name_import_from(self): self.assertTrue(StringCollection.__name__ == 'StringCollection') from xml.dom import pulldom - self.assertTrue(type(pulldom) == types.ModuleType) + self.assertTrue(isinstance(pulldom, types.ModuleType)) self.assertTrue(pulldom.__name__ == 'xml.dom.pulldom') from xml.dom.pulldom import PullDOM - self.assertTrue(type(PullDOM) == ClassType) + self.assertTrue(isinstance(PullDOM, ClassType)) self.assertTrue(PullDOM.__name__ == 'PullDOM') def test_dotted_name_import_from_with_alias(self): @@ -181,11 +181,11 @@ def test_dotted_name_import_from_with_alias(self): self.assertTrue(SC.__name__ == 'StringCollection') from xml.dom import pulldom as myPulldom - self.assertTrue(type(myPulldom) == types.ModuleType) + self.assertTrue(isinstance(myPulldom, types.ModuleType)) self.assertTrue(myPulldom.__name__ == 'xml.dom.pulldom') from xml.dom.pulldom import PullDOM as myPullDOM - self.assertTrue(type(myPullDOM) == ClassType) + self.assertTrue(isinstance(myPullDOM, ClassType)) self.assertTrue(myPullDOM.__name__ == 'PullDOM') def test_from_module_import_star(self): @@ -224,13 +224,13 @@ def test_explicit_assembly_load(self): import System, sys assembly = Assembly.LoadWithPartialName('System.Data') - self.assertTrue(assembly != None) + self.assertTrue(assembly is not None) import System.Data self.assertTrue('System.Data' in sys.modules) assembly = Assembly.LoadWithPartialName('SpamSpamSpamSpamEggsAndSpam') - self.assertTrue(assembly == None) + self.assertTrue(assembly is None) def test_implicit_load_already_valid_namespace(self): """Test implicit assembly load over an already valid namespace.""" From afb585ebe5cd2be838c75b95fc5b372a5e9a8c05 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 22 Jan 2017 03:30:27 -0700 Subject: [PATCH 044/245] Rename test fixtures Can mess with test discovery --- src/testing/eventtest.cs | 38 +++++++------- src/testing/subclasstest.cs | 8 +-- src/tests/leaktest.py | 20 ++++---- src/tests/test_event.py | 98 ++++++++++++++++++------------------- src/tests/test_subclass.py | 44 ++++++++--------- 5 files changed, 104 insertions(+), 104 deletions(-) diff --git a/src/testing/eventtest.cs b/src/testing/eventtest.cs index 544e0f259..d39557c4d 100644 --- a/src/testing/eventtest.cs +++ b/src/testing/eventtest.cs @@ -6,26 +6,26 @@ namespace Python.Test // Supports CLR event unit tests. //======================================================================== - public delegate void TestEventHandler(object sender, TestEventArgs e); + public delegate void EventHandlerTest(object sender, EventArgsTest e); public class EventTest { - public static event TestEventHandler PublicStaticEvent; + public static event EventHandlerTest PublicStaticEvent; - protected static event TestEventHandler ProtectedStaticEvent; + protected static event EventHandlerTest ProtectedStaticEvent; - internal static event TestEventHandler InternalStaticEvent; + internal static event EventHandlerTest InternalStaticEvent; - private static event TestEventHandler PrivateStaticEvent; + private static event EventHandlerTest PrivateStaticEvent; - public event TestEventHandler PublicEvent; + public event EventHandlerTest PublicEvent; - protected event TestEventHandler ProtectedEvent; + protected event EventHandlerTest ProtectedEvent; - internal event TestEventHandler InternalEvent; + internal event EventHandlerTest InternalEvent; - private event TestEventHandler PrivateEvent; + private event EventHandlerTest PrivateEvent; public static int s_value; @@ -42,7 +42,7 @@ static EventTest() } - public void OnPublicEvent(TestEventArgs e) + public void OnPublicEvent(EventArgsTest e) { if (PublicEvent != null) { @@ -51,7 +51,7 @@ public void OnPublicEvent(TestEventArgs e) } - public void OnProtectedEvent(TestEventArgs e) + public void OnProtectedEvent(EventArgsTest e) { if (ProtectedEvent != null) { @@ -60,7 +60,7 @@ public void OnProtectedEvent(TestEventArgs e) } - public static void OnPublicStaticEvent(TestEventArgs e) + public static void OnPublicStaticEvent(EventArgsTest e) { if (PublicStaticEvent != null) { @@ -69,7 +69,7 @@ public static void OnPublicStaticEvent(TestEventArgs e) } - protected static void OnProtectedStaticEvent(TestEventArgs e) + protected static void OnProtectedStaticEvent(EventArgsTest e) { if (ProtectedStaticEvent != null) { @@ -78,12 +78,12 @@ protected static void OnProtectedStaticEvent(TestEventArgs e) } - public void GenericHandler(object sender, TestEventArgs e) + public void GenericHandler(object sender, EventArgsTest e) { this.value = e.value; } - public static void StaticHandler(object sender, TestEventArgs e) + public static void StaticHandler(object sender, EventArgsTest e) { s_value = e.value; } @@ -92,7 +92,7 @@ public static void ShutUpCompiler() { // Quiet compiler warnings. EventTest e = new EventTest(); - TestEventHandler f = new TestEventHandler(e.GenericHandler); + EventHandlerTest f = new EventHandlerTest(e.GenericHandler); ProtectedStaticEvent += f; InternalStaticEvent += f; PrivateStaticEvent += f; @@ -103,13 +103,13 @@ public static void ShutUpCompiler() } - public class TestEventArgs : EventArgs + public class EventArgsTest : EventArgs { public int value; - public TestEventArgs(int v) + public EventArgsTest(int v) { this.value = v; } } -} \ No newline at end of file +} diff --git a/src/testing/subclasstest.cs b/src/testing/subclasstest.cs index 2b61be254..3229bdb94 100644 --- a/src/testing/subclasstest.cs +++ b/src/testing/subclasstest.cs @@ -14,14 +14,14 @@ public interface IInterfaceTest string bar(string s, int i); // test events on interfaces - event TestEventHandler TestEvent; + event EventHandlerTest TestEvent; void OnTestEvent(int value); } public class SubClassTest : IInterfaceTest { - public event TestEventHandler TestEvent; + public event EventHandlerTest TestEvent; public SubClassTest() { @@ -60,7 +60,7 @@ public static IList test_list(SubClassTest x) public virtual void OnTestEvent(int value) { if (null != TestEvent) - TestEvent(this, new TestEventArgs(value)); + TestEvent(this, new EventArgsTest(value)); } } @@ -75,7 +75,7 @@ public void SomeMethod() } } - public class TestFunctions + public class FunctionsTest { public static string test_foo(IInterfaceTest x) { diff --git a/src/tests/leaktest.py b/src/tests/leaktest.py index 2167060ad..646cb512e 100644 --- a/src/tests/leaktest.py +++ b/src/tests/leaktest.py @@ -138,7 +138,7 @@ def test_enumerations(self): self.end_test() def test_events(self): - from Python.Test import EventTest, TestEventArgs + from Python.Test import EventTest, EventArgsTest self.notify("Running event leak check...") @@ -151,28 +151,28 @@ def test_events(self): # Instance method event handler handler = GenericHandler() testob.PublicEvent += handler.handler - testob.PublicEvent(testob, TestEventArgs(10)) + testob.PublicEvent(testob, EventArgsTest(10)) testob.PublicEvent -= handler.handler del handler # Vararg method event handler handler = VariableArgsHandler() testob.PublicEvent += handler.handler - testob.PublicEvent(testob, TestEventArgs(10)) + testob.PublicEvent(testob, EventArgsTest(10)) testob.PublicEvent -= handler.handler del handler # Callable object event handler handler = CallableHandler() testob.PublicEvent += handler - testob.PublicEvent(testob, TestEventArgs(10)) + testob.PublicEvent(testob, EventArgsTest(10)) testob.PublicEvent -= handler del handler # Callable vararg event handler handler = VarCallableHandler() testob.PublicEvent += handler - testob.PublicEvent(testob, TestEventArgs(10)) + testob.PublicEvent(testob, EventArgsTest(10)) testob.PublicEvent -= handler del handler @@ -180,7 +180,7 @@ def test_events(self): handler = StaticMethodHandler() StaticMethodHandler.value = None testob.PublicEvent += handler.handler - testob.PublicEvent(testob, TestEventArgs(10)) + testob.PublicEvent(testob, EventArgsTest(10)) testob.PublicEvent -= handler.handler del handler @@ -188,18 +188,18 @@ def test_events(self): handler = ClassMethodHandler() ClassMethodHandler.value = None testob.PublicEvent += handler.handler - testob.PublicEvent(testob, TestEventArgs(10)) + testob.PublicEvent(testob, EventArgsTest(10)) testob.PublicEvent -= handler.handler del handler # Managed instance event handler testob.PublicEvent += testob.GenericHandler - testob.PublicEvent(testob, TestEventArgs(10)) + testob.PublicEvent(testob, EventArgsTest(10)) testob.PublicEvent -= testob.GenericHandler # Static managed event handler testob.PublicEvent += EventTest.StaticHandler - testob.PublicEvent(testob, TestEventArgs(10)) + testob.PublicEvent(testob, EventArgsTest(10)) testob.PublicEvent -= EventTest.StaticHandler # Function event handler @@ -209,7 +209,7 @@ def handler(sender, args, dict_=dict_): dict_['value'] = args.value testob.PublicEvent += handler - testob.PublicEvent(testob, TestEventArgs(10)) + testob.PublicEvent(testob, EventArgsTest(10)) testob.PublicEvent -= handler del handler diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 237d60777..047af47f3 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -2,7 +2,7 @@ import unittest -from Python.Test import EventTest, TestEventArgs +from Python.Test import EventTest, EventArgsTest from _compat import range from utils import (CallableHandler, ClassMethodHandler, GenericHandler, @@ -22,7 +22,7 @@ def test_public_instance_event(self): ob.PublicEvent += handler.handler - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) ob.PublicEvent -= handler.handler @@ -34,7 +34,7 @@ def test_public_static_event(self): EventTest.PublicStaticEvent += handler.handler - EventTest.OnPublicStaticEvent(TestEventArgs(10)) + EventTest.OnPublicStaticEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) def test_protected_instance_event(self): @@ -46,7 +46,7 @@ def test_protected_instance_event(self): ob.ProtectedEvent += handler.handler - ob.OnProtectedEvent(TestEventArgs(10)) + ob.OnProtectedEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) ob.ProtectedEvent -= handler.handler @@ -58,7 +58,7 @@ def test_protected_static_event(self): EventTest.ProtectedStaticEvent += handler.handler - EventTest.OnProtectedStaticEvent(TestEventArgs(10)) + EventTest.OnProtectedStaticEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) EventTest.ProtectedStaticEvent -= handler.handler @@ -99,13 +99,13 @@ def test_multicast_event(self): ob.PublicEvent += handler2.handler ob.PublicEvent += handler3.handler - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler1.value == 10) self.assertTrue(handler2.value == 10) self.assertTrue(handler3.value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(handler1.value == 20) self.assertTrue(handler2.value == 20) @@ -123,13 +123,13 @@ def test_instance_method_handler(self): ob.PublicEvent += handler.handler self.assertTrue(handler.value is None) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) ob.PublicEvent -= handler.handler self.assertTrue(handler.value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(handler.value == 10) def test_var_args_instance_method_handler(self): @@ -140,13 +140,13 @@ def test_var_args_instance_method_handler(self): ob.PublicEvent += handler.handler self.assertTrue(handler.value is None) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) ob.PublicEvent -= handler.handler self.assertTrue(handler.value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(handler.value == 10) def test_callableob_handler(self): @@ -157,13 +157,13 @@ def test_callableob_handler(self): ob.PublicEvent += handler self.assertTrue(handler.value is None) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) ob.PublicEvent -= handler self.assertTrue(handler.value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(handler.value == 10) def test_var_args_callable_handler(self): @@ -174,13 +174,13 @@ def test_var_args_callable_handler(self): ob.PublicEvent += handler self.assertTrue(handler.value is None) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) ob.PublicEvent -= handler self.assertTrue(handler.value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(handler.value == 10) def test_static_method_handler(self): @@ -192,13 +192,13 @@ def test_static_method_handler(self): ob.PublicEvent += handler.handler self.assertTrue(handler.value is None) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) ob.PublicEvent -= handler.handler self.assertTrue(handler.value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(handler.value == 10) def test_class_method_handler(self): @@ -210,13 +210,13 @@ def test_class_method_handler(self): ob.PublicEvent += handler.handler self.assertTrue(handler.value is None) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) ob.PublicEvent -= handler.handler self.assertTrue(handler.value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(handler.value == 10) def test_managed_instance_method_handler(self): @@ -226,13 +226,13 @@ def test_managed_instance_method_handler(self): ob.PublicEvent += ob.GenericHandler self.assertTrue(ob.value == 0) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(ob.value == 10) ob.PublicEvent -= ob.GenericHandler self.assertTrue(ob.value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(ob.value == 10) def test_managed_static_method_handler(self): @@ -243,13 +243,13 @@ def test_managed_static_method_handler(self): ob.PublicEvent += ob.StaticHandler self.assertTrue(EventTest.s_value == 0) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(EventTest.s_value == 10) ob.PublicEvent -= ob.StaticHandler self.assertTrue(EventTest.s_value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(EventTest.s_value == 10) def test_unbound_method_handler(self): @@ -258,7 +258,7 @@ def test_unbound_method_handler(self): ob.PublicEvent += GenericHandler.handler with self.assertRaises(TypeError): - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) ob.PublicEvent -= GenericHandler.handler @@ -273,13 +273,13 @@ def handler(sender, args, dict_=dict_): ob.PublicEvent += handler self.assertTrue(dict_['value'] is None) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(dict_['value'] == 10) ob.PublicEvent -= handler self.assertTrue(dict_['value'] == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(dict_['value'] == 10) def test_add_non_callable_handler(self): @@ -311,17 +311,17 @@ def test_remove_multiple_handlers(self): h2 = handler.handler ob.PublicEvent += h2 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 20) ob.PublicEvent -= h1 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 30) ob.PublicEvent -= h2 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 30) # try again, removing in a different order. @@ -335,17 +335,17 @@ def test_remove_multiple_handlers(self): h2 = handler.handler ob.PublicEvent += h2 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 20) ob.PublicEvent -= h2 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 30) ob.PublicEvent -= h1 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 30) def test_remove_multiple_static_handlers(self): @@ -359,17 +359,17 @@ def test_remove_multiple_static_handlers(self): h2 = handler.handler ob.PublicStaticEvent += h2 - ob.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(EventArgsTest(10)) self.assertTrue(handler.value == 20) ob.PublicStaticEvent -= h1 - ob.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(EventArgsTest(10)) self.assertTrue(handler.value == 30) ob.PublicStaticEvent -= h2 - ob.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(EventArgsTest(10)) self.assertTrue(handler.value == 30) # try again, removing in a different order. @@ -383,17 +383,17 @@ def test_remove_multiple_static_handlers(self): h2 = handler.handler ob.PublicStaticEvent += h2 - ob.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(EventArgsTest(10)) self.assertTrue(handler.value == 20) ob.PublicStaticEvent -= h2 - ob.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(EventArgsTest(10)) self.assertTrue(handler.value == 30) ob.PublicStaticEvent -= h1 - ob.OnPublicStaticEvent(TestEventArgs(10)) + ob.OnPublicStaticEvent(EventArgsTest(10)) self.assertTrue(handler.value == 30) def test_random_multiple_handlers(self): @@ -412,7 +412,7 @@ def test_random_multiple_handlers(self): ob.PublicEvent += method handlers.append(method) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 300) self.assertTrue(handler2.value == 20) handler.value = 0 @@ -423,24 +423,24 @@ def test_random_multiple_handlers(self): handlers.remove(item) ob.PublicEvent -= item handler.value = 0 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == (len(handlers) * 10)) self.assertTrue(handler2.value == ((i + 1) * 20)) handler2.value = 0 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler2.value == 20) ob.PublicEvent -= handler2.handler handler2.value = 0 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler2.value == 10) ob.PublicEvent -= handler2.handler handler2.value = 0 - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler2.value == 0) def test_remove_internal_call_handler(self): @@ -474,7 +474,7 @@ def handler(self, one): with self.assertRaises(TypeError): ob.PublicEvent += handler.handler - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) ob.PublicEvent -= handler.handler @@ -487,7 +487,7 @@ def handler(self, one, two, three, four, five): with self.assertRaises(TypeError): ob.PublicEvent += handler.handler - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) ob.PublicEvent -= handler.handler @@ -508,22 +508,22 @@ def test_incorrect_invokation(self): def test_explicit_cls_event_registration(self): """Test explicit CLS event registration.""" - from Python.Test import TestEventHandler + from Python.Test import EventHandlerTest ob = EventTest() handler = GenericHandler() - delegate = TestEventHandler(handler.handler) + delegate = EventHandlerTest(handler.handler) ob.add_PublicEvent(delegate) self.assertTrue(handler.value is None) - ob.OnPublicEvent(TestEventArgs(10)) + ob.OnPublicEvent(EventArgsTest(10)) self.assertTrue(handler.value == 10) ob.remove_PublicEvent(delegate) self.assertTrue(handler.value == 10) - ob.OnPublicEvent(TestEventArgs(20)) + ob.OnPublicEvent(EventArgsTest(20)) self.assertTrue(handler.value == 10) def test_implicit_cls_event_registration(self): diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index 922e2651c..28a634a18 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -4,8 +4,8 @@ import unittest import System -from Python.Test import (IInterfaceTest, SubClassTest, TestEventArgs, - TestFunctions) +from Python.Test import (IInterfaceTest, SubClassTest, EventArgsTest, + FunctionsTest) from System.Collections.Generic import List from _compat import range @@ -61,7 +61,7 @@ def remove_TestEvent(self, handler): self.event_handlers.remove(handler) def OnTestEvent(self, value): - args = TestEventArgs(value) + args = EventArgsTest(value) for handler in self.event_handlers: handler(self, args) @@ -73,9 +73,9 @@ def test_base_class(self): """Test base class managed type""" ob = SubClassTest() self.assertEqual(ob.foo(), "foo") - self.assertEqual(TestFunctions.test_foo(ob), "foo") + self.assertEqual(FunctionsTest.test_foo(ob), "foo") self.assertEqual(ob.bar("bar", 2), "bar") - self.assertEqual(TestFunctions.test_bar(ob, "bar", 2), "bar") + self.assertEqual(FunctionsTest.test_bar(ob, "bar", 2), "bar") self.assertEqual(ob.not_overriden(), "not_overriden") self.assertEqual(list(ob.return_list()), ["a", "b", "c"]) self.assertEqual(list(SubClassTest.test_list(ob)), ["a", "b", "c"]) @@ -84,11 +84,11 @@ def test_interface(self): """Test python classes can derive from C# interfaces""" ob = InterfaceTestClass() self.assertEqual(ob.foo(), "InterfaceTestClass") - self.assertEqual(TestFunctions.test_foo(ob), "InterfaceTestClass") + self.assertEqual(FunctionsTest.test_foo(ob), "InterfaceTestClass") self.assertEqual(ob.bar("bar", 2), "bar/bar") - self.assertEqual(TestFunctions.test_bar(ob, "bar", 2), "bar/bar") + self.assertEqual(FunctionsTest.test_bar(ob, "bar", 2), "bar/bar") - x = TestFunctions.pass_through(ob) + x = FunctionsTest.pass_through(ob) self.assertEqual(id(x), id(ob)) def test_derived_class(self): @@ -97,35 +97,35 @@ def test_derived_class(self): self.assertEqual(ob.foo(), "DerivedClass") self.assertEqual(ob.base_foo(), "foo") self.assertEqual(ob.super_foo(), "foo") - self.assertEqual(TestFunctions.test_foo(ob), "DerivedClass") + self.assertEqual(FunctionsTest.test_foo(ob), "DerivedClass") self.assertEqual(ob.bar("bar", 2), "bar_bar") - self.assertEqual(TestFunctions.test_bar(ob, "bar", 2), "bar_bar") + self.assertEqual(FunctionsTest.test_bar(ob, "bar", 2), "bar_bar") self.assertEqual(ob.not_overriden(), "not_overriden") self.assertEqual(list(ob.return_list()), ["A", "B", "C"]) self.assertEqual(list(SubClassTest.test_list(ob)), ["A", "B", "C"]) - x = TestFunctions.pass_through(ob) + x = FunctionsTest.pass_through(ob) self.assertEqual(id(x), id(ob)) def test_create_instance(self): """Test derived instances can be created from managed code""" - ob = TestFunctions.create_instance(DerivedClass) + ob = FunctionsTest.create_instance(DerivedClass) self.assertEqual(ob.foo(), "DerivedClass") - self.assertEqual(TestFunctions.test_foo(ob), "DerivedClass") + self.assertEqual(FunctionsTest.test_foo(ob), "DerivedClass") self.assertEqual(ob.bar("bar", 2), "bar_bar") - self.assertEqual(TestFunctions.test_bar(ob, "bar", 2), "bar_bar") + self.assertEqual(FunctionsTest.test_bar(ob, "bar", 2), "bar_bar") self.assertEqual(ob.not_overriden(), "not_overriden") - x = TestFunctions.pass_through(ob) + x = FunctionsTest.pass_through(ob) self.assertEqual(id(x), id(ob)) - ob2 = TestFunctions.create_instance(InterfaceTestClass) + ob2 = FunctionsTest.create_instance(InterfaceTestClass) self.assertEqual(ob2.foo(), "InterfaceTestClass") - self.assertEqual(TestFunctions.test_foo(ob2), "InterfaceTestClass") + self.assertEqual(FunctionsTest.test_foo(ob2), "InterfaceTestClass") self.assertEqual(ob2.bar("bar", 2), "bar/bar") - self.assertEqual(TestFunctions.test_bar(ob2, "bar", 2), "bar/bar") + self.assertEqual(FunctionsTest.test_bar(ob2, "bar", 2), "bar/bar") - y = TestFunctions.pass_through(ob2) + y = FunctionsTest.pass_through(ob2) self.assertEqual(id(y), id(ob2)) def test_events(self): @@ -137,16 +137,16 @@ def handler(self, x, args): x = SubClassTest() x.TestEvent += event_handler.handler - self.assertEqual(TestFunctions.test_event(x, 1), 1) + self.assertEqual(FunctionsTest.test_event(x, 1), 1) self.assertEqual(event_handler.value, 1) i = InterfaceTestClass() with self.assertRaises(System.NotImplementedException): - TestFunctions.test_event(i, 2) + FunctionsTest.test_event(i, 2) d = DerivedEventTest() d.add_TestEvent(event_handler.handler) - self.assertEqual(TestFunctions.test_event(d, 3), 3) + self.assertEqual(FunctionsTest.test_event(d, 3), 3) self.assertEqual(event_handler.value, 3) self.assertEqual(len(d.event_handlers), 1) From 1eeab58f3004e7265adcbb38a5611b203f10460d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 22 Jan 2017 03:38:27 -0700 Subject: [PATCH 045/245] Remove unused `using` from testing and format --- src/testing/arraytest.cs | 5 +---- src/testing/callbacktest.cs | 20 +++++++++----------- src/testing/classtest.cs | 3 +-- src/testing/constructortests.cs | 3 +-- src/testing/conversiontest.cs | 5 +---- src/testing/delegatetest.cs | 4 +--- src/testing/doctest.cs | 14 +++++++------- src/testing/enumtest.cs | 4 ++-- src/testing/exceptiontest.cs | 2 +- src/testing/fieldtest.cs | 5 +---- src/testing/generictest.cs | 5 +---- src/testing/globaltest.cs | 4 +--- src/testing/indexertest.cs | 3 +-- src/testing/interfacetest.cs | 4 +--- src/testing/methodtest.cs | 7 +++---- src/testing/moduletest.cs | 12 ++++++++---- src/testing/propertytest.cs | 4 +--- src/testing/subclasstest.cs | 3 --- src/testing/threadtest.cs | 3 +-- 19 files changed, 42 insertions(+), 68 deletions(-) diff --git a/src/testing/arraytest.cs b/src/testing/arraytest.cs index b9891cac8..591b5b1c4 100644 --- a/src/testing/arraytest.cs +++ b/src/testing/arraytest.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections; - namespace Python.Test { //======================================================================== @@ -318,4 +315,4 @@ public static Spam[][] EchoRangeAA(Spam[][] items) return items; } } -} \ No newline at end of file +} diff --git a/src/testing/callbacktest.cs b/src/testing/callbacktest.cs index f95cbc602..33e240531 100644 --- a/src/testing/callbacktest.cs +++ b/src/testing/callbacktest.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using Python.Runtime; namespace Python.Test { @@ -13,17 +10,18 @@ public class CallbackTest { public string Call_simpleDefaultArg_WithNull(string moduleName) { - using (Runtime.Py.GIL()) + using (Py.GIL()) { - dynamic module = Runtime.Py.Import(moduleName); + dynamic module = Py.Import(moduleName); return module.simpleDefaultArg(null); } } + public string Call_simpleDefaultArg_WithEmptyArgs(string moduleName) { - using (Runtime.Py.GIL()) + using (Py.GIL()) { - dynamic module = Runtime.Py.Import(moduleName); + dynamic module = Py.Import(moduleName); return module.simpleDefaultArg(); } } @@ -31,14 +29,14 @@ public string Call_simpleDefaultArg_WithEmptyArgs(string moduleName) //========================================================================== // Tests calling from Python into C# and back into Python using a PyObject. - // SelfCallbackTest should be inherited by a Python class. + // SelfCallbackTest should be inherited by a Python class. // Used in test_class.py / testCallback //========================================================================== public class SelfCallbackTest { - public void Callback(Runtime.PyObject self) + public void Callback(PyObject self) { - using (Runtime.Py.GIL()) + using (Py.GIL()) ((dynamic)self).PyCallback(self); } } diff --git a/src/testing/classtest.cs b/src/testing/classtest.cs index 5f3b0d7ed..ab0cad7ad 100644 --- a/src/testing/classtest.cs +++ b/src/testing/classtest.cs @@ -1,4 +1,3 @@ -using System; using System.Collections; namespace Python.Test @@ -61,4 +60,4 @@ public ClassCtorTest2(string v) internal class InternalClass { } -} \ No newline at end of file +} diff --git a/src/testing/constructortests.cs b/src/testing/constructortests.cs index cffcee888..4d3cc5710 100644 --- a/src/testing/constructortests.cs +++ b/src/testing/constructortests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.IO; namespace Python.Test @@ -50,4 +49,4 @@ public SubclassConstructorTest(Exception v) this.value = v; } } -} \ No newline at end of file +} diff --git a/src/testing/conversiontest.cs b/src/testing/conversiontest.cs index e4d4762e6..5686a1943 100644 --- a/src/testing/conversiontest.cs +++ b/src/testing/conversiontest.cs @@ -1,6 +1,3 @@ -using System; - - namespace Python.Test { //======================================================================== @@ -58,4 +55,4 @@ public string GetValue() return value; } } -} \ No newline at end of file +} diff --git a/src/testing/delegatetest.cs b/src/testing/delegatetest.cs index d13750c49..94169f650 100644 --- a/src/testing/delegatetest.cs +++ b/src/testing/delegatetest.cs @@ -1,5 +1,3 @@ -using System; - namespace Python.Test { //======================================================================== @@ -60,4 +58,4 @@ public bool CallBoolDelegate(BoolDelegate d) return d(); } } -} \ No newline at end of file +} diff --git a/src/testing/doctest.cs b/src/testing/doctest.cs index 156248029..a0f60b2e1 100644 --- a/src/testing/doctest.cs +++ b/src/testing/doctest.cs @@ -8,19 +8,19 @@ namespace Python.Test // Classes with a constructor have their docstring set to the ctor signature. // Test if a class has an explicit doc string it gets set correctly. - [DocStringAttribute("DocWithCtorTest Class")] + [DocString("DocWithCtorTest Class")] public class DocWithCtorTest { public DocWithCtorTest() { } - [DocStringAttribute("DocWithCtorTest TestMethod")] + [DocString("DocWithCtorTest TestMethod")] public void TestMethod() { } - [DocStringAttribute("DocWithCtorTest StaticTestMethod")] + [DocString("DocWithCtorTest StaticTestMethod")] public static void StaticTestMethod() { } @@ -41,17 +41,17 @@ public static void StaticTestMethod(double a, int b) } } - [DocStringAttribute("DocWithoutCtorTest Class")] + [DocString("DocWithoutCtorTest Class")] public class DocWithoutCtorTest { - [DocStringAttribute("DocWithoutCtorTest TestMethod")] + [DocString("DocWithoutCtorTest TestMethod")] public void TestMethod() { } - [DocStringAttribute("DocWithoutCtorTest StaticTestMethod")] + [DocString("DocWithoutCtorTest StaticTestMethod")] public static void StaticTestMethod() { } } -} \ No newline at end of file +} diff --git a/src/testing/enumtest.cs b/src/testing/enumtest.cs index 162771980..0d0d56190 100644 --- a/src/testing/enumtest.cs +++ b/src/testing/enumtest.cs @@ -86,7 +86,7 @@ public enum ULongEnum : ulong Five } - [FlagsAttribute] + [Flags] public enum FlagsEnum { Zero, @@ -96,4 +96,4 @@ public enum FlagsEnum Four, Five } -} \ No newline at end of file +} diff --git a/src/testing/exceptiontest.cs b/src/testing/exceptiontest.cs index 414c25d82..ae5fc86c0 100644 --- a/src/testing/exceptiontest.cs +++ b/src/testing/exceptiontest.cs @@ -99,4 +99,4 @@ public string GetExtraInfo() return extra; } } -} \ No newline at end of file +} diff --git a/src/testing/fieldtest.cs b/src/testing/fieldtest.cs index 5860bdafb..4d41cf084 100644 --- a/src/testing/fieldtest.cs +++ b/src/testing/fieldtest.cs @@ -1,6 +1,3 @@ -using System; - - namespace Python.Test { //======================================================================== @@ -54,4 +51,4 @@ public void Shutup() public object ObjectField; public ISpam SpamField; } -} \ No newline at end of file +} diff --git a/src/testing/generictest.cs b/src/testing/generictest.cs index 3019c1eb6..b38f5e8e5 100644 --- a/src/testing/generictest.cs +++ b/src/testing/generictest.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections; - namespace Python.Test { //======================================================================== @@ -131,4 +128,4 @@ public static string Overloaded(int arg1, int arg2, string arg3) return arg3; } } -} \ No newline at end of file +} diff --git a/src/testing/globaltest.cs b/src/testing/globaltest.cs index 887668d96..2d6d56cda 100644 --- a/src/testing/globaltest.cs +++ b/src/testing/globaltest.cs @@ -1,9 +1,7 @@ -using System; - //======================================================================== // Supports units tests for access to types without a namespace. //======================================================================== public class NoNamespaceType { -} \ No newline at end of file +} diff --git a/src/testing/indexertest.cs b/src/testing/indexertest.cs index eb0381777..f1dcbda0b 100644 --- a/src/testing/indexertest.cs +++ b/src/testing/indexertest.cs @@ -1,4 +1,3 @@ -using System; using System.Collections; namespace Python.Test @@ -415,4 +414,4 @@ public MultiDefaultKeyIndexerTest() : base() } } } -} \ No newline at end of file +} diff --git a/src/testing/interfacetest.cs b/src/testing/interfacetest.cs index b35ca81a8..4c4056d68 100644 --- a/src/testing/interfacetest.cs +++ b/src/testing/interfacetest.cs @@ -1,5 +1,3 @@ -using System; - namespace Python.Test { //======================================================================== @@ -62,4 +60,4 @@ private interface IPrivate { } } -} \ No newline at end of file +} diff --git a/src/testing/methodtest.cs b/src/testing/methodtest.cs index 675b1577c..65e39cf69 100644 --- a/src/testing/methodtest.cs +++ b/src/testing/methodtest.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using System.Collections.Generic; namespace Python.Test { @@ -156,13 +155,13 @@ public static bool TestValueRefParams(string s, ref int i1) public static bool TestObjectOutParams(object o, out object o1) { - o1 = new System.Exception("test"); + o1 = new Exception("test"); return true; } public static bool TestObjectRefParams(object o, ref object o1) { - o1 = new System.Exception("test"); + o1 = new Exception("test"); return true; } @@ -630,4 +629,4 @@ public string PublicMethod(string echo) return echo; } } -} \ No newline at end of file +} diff --git a/src/testing/moduletest.cs b/src/testing/moduletest.cs index ca75a1313..2d5734a11 100644 --- a/src/testing/moduletest.cs +++ b/src/testing/moduletest.cs @@ -1,16 +1,20 @@ using System; using System.Threading; -namespace Python.Test { - public class ModuleTest { +namespace Python.Test +{ + public class ModuleTest + { private static Thread _thread; public static void RunThreads() { - _thread = new Thread(() => { + _thread = new Thread(() => + { var appdomain = AppDomain.CurrentDomain; var assemblies = appdomain.GetAssemblies(); - foreach (var assembly in assemblies) { + foreach (var assembly in assemblies) + { assembly.GetTypes(); } }); diff --git a/src/testing/propertytest.cs b/src/testing/propertytest.cs index f01c02e0b..b70e9487a 100644 --- a/src/testing/propertytest.cs +++ b/src/testing/propertytest.cs @@ -1,5 +1,3 @@ -using System; - namespace Python.Test { //======================================================================== @@ -84,4 +82,4 @@ public ShortEnum EnumProperty set { _enum_property = value; } } } -} \ No newline at end of file +} diff --git a/src/testing/subclasstest.cs b/src/testing/subclasstest.cs index 3229bdb94..9ee105aef 100644 --- a/src/testing/subclasstest.cs +++ b/src/testing/subclasstest.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Python.Test { @@ -70,7 +68,6 @@ public class SubClass : RecursiveInheritance { public void SomeMethod() { - } } } diff --git a/src/testing/threadtest.cs b/src/testing/threadtest.cs index 0a4f46ccc..0cb2abe57 100644 --- a/src/testing/threadtest.cs +++ b/src/testing/threadtest.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using Python.Runtime; namespace Python.Test @@ -77,4 +76,4 @@ public static string CallEchoString2(string arg) } } } -} \ No newline at end of file +} From 400f688ed5f4a039bb0729a4194fa9d397a8cad3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 22 Jan 2017 13:14:32 -0700 Subject: [PATCH 046/245] Use unittest.skip(...) --- src/tests/runtests.py | 11 ++-- src/tests/test_engine.py | 3 +- src/tests/test_exceptions.py | 31 +++++----- src/tests/test_subclass.py | 107 ++++++++++++++++++++++------------- 4 files changed, 91 insertions(+), 61 deletions(-) diff --git a/src/tests/runtests.py b/src/tests/runtests.py index 919d4b7e5..9b77f99dd 100644 --- a/src/tests/runtests.py +++ b/src/tests/runtests.py @@ -16,13 +16,14 @@ except ImportError: print("Load clr import hook") import clr + clr.AddReference("Python.Test") clr.AddReference("System.Collections") clr.AddReference("System.Data") clr.AddReference("System.Management") test_modules = ( - # Passes on its own, but not here if + # test_module passes on its own, but not here if # other test modules that import System.Windows.Forms # run first. They must not do module level import/AddReference() # of the System.Windows.Forms namespace. @@ -47,11 +48,11 @@ 'test_thread', 'test_docstring', - # FIXME: Fails due to unhandled exception - # 'test_engine', + # FIXME: Has tests that are being skipped. + 'test_engine', - # FIXME: Fails in Linux - # 'test_subclass', + # FIXME: Has tests that are being skipped. + 'test_subclass', ) diff --git a/src/tests/test_engine.py b/src/tests/test_engine.py index a39cb4aa8..b605a3796 100644 --- a/src/tests/test_engine.py +++ b/src/tests/test_engine.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- -# FIXME: This test module fails due to unhandled exceptions import sys import unittest @@ -20,12 +19,14 @@ def test_multiple_calls_to_initialize(self): except BaseException: self.fail("Initialize() raise an exception.") + @unittest.skip(reason="FIXME: test crashes") def test_import_module(self): """Test module import.""" m = PythonEngine.ImportModule("sys") n = m.GetAttr("__name__") self.assertTrue(n.AsManagedObject(System.String) == "sys") + @unittest.skip(reason="FIXME: test freezes") def test_run_string(self): """Test the RunString method.""" PythonEngine.AcquireLock() diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index 7d60e0732..2fb55589c 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -306,23 +306,22 @@ def test_pickling_exceptions(self): self.assertEqual(exc.args, loaded.args) + @unittest.skipIf(PY2, "__cause__ isn't implemented in PY2") def test_chained_exceptions(self): - # __cause__ is py3 only - if PY3: - from Python.Test import ExceptionTest - - try: - ExceptionTest.ThrowChainedExceptions() - except Exception as exc: - msgs = ("Outer exception", - "Inner exception", - "Innermost exception",) - for msg in msgs: - self.assertEqual(exc.Message, msg) - self.assertEqual(exc.__cause__, exc.InnerException) - exc = exc.__cause__ - else: - self.fail("Test should raise an exception") + from Python.Test import ExceptionTest + + with self.assertRaises(Exception) as cm: + ExceptionTest.ThrowChainedExceptions() + + exc = cm.exception + + msgs = ("Outer exception", + "Inner exception", + "Innermost exception",) + for msg in msgs: + self.assertEqual(exc.Message, msg) + self.assertEqual(exc.__cause__, exc.InnerException) + exc = exc.__cause__ def test_suite(): diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index 28a634a18..34ec86d9a 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -1,5 +1,8 @@ # -*- coding: utf-8 -*- -# FIXME: This test module fails on Linux +# FIXME: This test module randomly passes/fails even if all tests are skipped. +# Something fishy is going on with the Test fixtures. Behavior seen on CI on +# both Linux and Windows +# TODO: Remove delay of class creations. Adding SetUp/TearDown may help import unittest @@ -11,64 +14,80 @@ from _compat import range -class InterfaceTestClass(IInterfaceTest): - """class that implements the test interface""" - __namespace__ = "Python.Test" +def interface_test_class_fixture(): + """Delay creation of class until test starts.""" - def foo(self): - return "InterfaceTestClass" + class InterfaceTestClass(IInterfaceTest): + """class that implements the test interface""" + __namespace__ = "Python.Test" - def bar(self, x, i): - return "/".join([x] * i) + def foo(self): + return "InterfaceTestClass" + def bar(self, x, i): + return "/".join([x] * i) -class DerivedClass(SubClassTest): - """class that derives from a class deriving from IInterfaceTest""" - __namespace__ = "Python.Test" + return InterfaceTestClass - def foo(self): - return "DerivedClass" - def base_foo(self): - return SubClassTest.foo(self) +def derived_class_fixture(): + """Delay creation of class until test starts.""" - def super_foo(self): - return super(DerivedClass, self).foo() + class DerivedClass(SubClassTest): + """class that derives from a class deriving from IInterfaceTest""" + __namespace__ = "Python.Test" - def bar(self, x, i): - return "_".join([x] * i) + def foo(self): + return "DerivedClass" - def return_list(self): - l = List[str]() - l.Add("A") - l.Add("B") - l.Add("C") - return l + def base_foo(self): + return SubClassTest.foo(self) + def super_foo(self): + return super(DerivedClass, self).foo() -class DerivedEventTest(IInterfaceTest): - """class that implements IInterfaceTest.TestEvent""" - __namespace__ = "Python.Test" + def bar(self, x, i): + return "_".join([x] * i) - def __init__(self): - self.event_handlers = [] + def return_list(self): + l = List[str]() + l.Add("A") + l.Add("B") + l.Add("C") + return l - # event handling - def add_TestEvent(self, handler): - self.event_handlers.append(handler) + return DerivedClass - def remove_TestEvent(self, handler): - self.event_handlers.remove(handler) - def OnTestEvent(self, value): - args = EventArgsTest(value) - for handler in self.event_handlers: - handler(self, args) +def derived_event_test_class_fixture(): + """Delay creation of class until test starts.""" + + class DerivedEventTest(IInterfaceTest): + """class that implements IInterfaceTest.TestEvent""" + __namespace__ = "Python.Test" + + def __init__(self): + self.event_handlers = [] + + # event handling + def add_TestEvent(self, handler): + self.event_handlers.append(handler) + + def remove_TestEvent(self, handler): + self.event_handlers.remove(handler) + + def OnTestEvent(self, value): + args = EventArgsTest(value) + for handler in self.event_handlers: + handler(self, args) + + return DerivedEventTest class SubClassTests(unittest.TestCase): """Test sub-classing managed types""" + @unittest.skip(reason="FIXME: test randomly pass/fails") def test_base_class(self): """Test base class managed type""" ob = SubClassTest() @@ -80,8 +99,10 @@ def test_base_class(self): self.assertEqual(list(ob.return_list()), ["a", "b", "c"]) self.assertEqual(list(SubClassTest.test_list(ob)), ["a", "b", "c"]) + @unittest.skip(reason="FIXME: test randomly pass/fails") def test_interface(self): """Test python classes can derive from C# interfaces""" + InterfaceTestClass = interface_test_class_fixture() ob = InterfaceTestClass() self.assertEqual(ob.foo(), "InterfaceTestClass") self.assertEqual(FunctionsTest.test_foo(ob), "InterfaceTestClass") @@ -91,8 +112,10 @@ def test_interface(self): x = FunctionsTest.pass_through(ob) self.assertEqual(id(x), id(ob)) + @unittest.skip(reason="FIXME: test randomly pass/fails") def test_derived_class(self): """Test python class derived from managed type""" + DerivedClass = derived_class_fixture() ob = DerivedClass() self.assertEqual(ob.foo(), "DerivedClass") self.assertEqual(ob.base_foo(), "foo") @@ -107,8 +130,10 @@ def test_derived_class(self): x = FunctionsTest.pass_through(ob) self.assertEqual(id(x), id(ob)) + @unittest.skip(reason="FIXME: test randomly pass/fails") def test_create_instance(self): """Test derived instances can be created from managed code""" + DerivedClass = derived_class_fixture() ob = FunctionsTest.create_instance(DerivedClass) self.assertEqual(ob.foo(), "DerivedClass") self.assertEqual(FunctionsTest.test_foo(ob), "DerivedClass") @@ -119,6 +144,7 @@ def test_create_instance(self): x = FunctionsTest.pass_through(ob) self.assertEqual(id(x), id(ob)) + InterfaceTestClass = interface_test_class_fixture() ob2 = FunctionsTest.create_instance(InterfaceTestClass) self.assertEqual(ob2.foo(), "InterfaceTestClass") self.assertEqual(FunctionsTest.test_foo(ob2), "InterfaceTestClass") @@ -128,6 +154,7 @@ def test_create_instance(self): y = FunctionsTest.pass_through(ob2) self.assertEqual(id(y), id(ob2)) + @unittest.skip(reason="FIXME: test randomly pass/fails") def test_events(self): class EventHandler(object): def handler(self, x, args): @@ -140,10 +167,12 @@ def handler(self, x, args): self.assertEqual(FunctionsTest.test_event(x, 1), 1) self.assertEqual(event_handler.value, 1) + InterfaceTestClass = interface_test_class_fixture() i = InterfaceTestClass() with self.assertRaises(System.NotImplementedException): FunctionsTest.test_event(i, 2) + DerivedEventTest = derived_event_test_class_fixture() d = DerivedEventTest() d.add_TestEvent(event_handler.handler) self.assertEqual(FunctionsTest.test_event(d, 3), 3) From 3058bf7919122659fc118b07888bcada9c9221a6 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 14:38:16 -0700 Subject: [PATCH 047/245] Cleanup testing format --- src/embed_tests/pyimport.cs | 23 ++++++++++------------- src/embed_tests/pyiter.cs | 4 ++-- src/embed_tests/pythonexception.cs | 4 ++-- src/testing/callbacktest.cs | 2 ++ src/testing/classtest.cs | 8 ++++---- src/testing/constructortests.cs | 8 ++++---- src/testing/eventtest.cs | 10 +++++----- src/testing/exceptiontest.cs | 2 +- src/testing/generictest.cs | 6 +++--- src/testing/moduletest.cs | 7 ++++--- src/testing/subclasstest.cs | 6 ++++-- src/testing/threadtest.cs | 8 ++++---- 12 files changed, 45 insertions(+), 43 deletions(-) diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index a6c12d49e..0e4cb3806 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -18,15 +18,13 @@ public void SetUp() PythonEngine.Initialize(); gs = PythonEngine.AcquireLock(); - /* - * Append the tests directory to sys.path - * using reflection to circumvent the private modifiers placed on most Runtime methods. + /* Append the tests directory to sys.path + * using reflection to circumvent the private + * modifiers placed on most Runtime methods. */ const string s = @"../../../../tests"; - var testPath = Path.Combine( - TestContext.CurrentContext.TestDirectory, s - ); + string testPath = Path.Combine(TestContext.CurrentContext.TestDirectory, s); IntPtr str = Runtime.Runtime.PyString_FromString(testPath); IntPtr path = Runtime.Runtime.PySys_GetObject("path"); @@ -44,13 +42,12 @@ public void TearDown() /// Test subdirectory import /// /// - /// The required directory structure was added to the \trunk\pythonnet\src\tests directory: - /// - /// PyImportTest/ - /// __init__.py - /// test/ - /// __init__.py - /// one.py + /// The required directory structure was added to .\pythonnet\src\tests\ directory: + /// + PyImportTest/ + /// | - __init__.py + /// | + test/ + /// | | - __init__.py + /// | | - one.py /// [Test] public void TestDottedName() diff --git a/src/embed_tests/pyiter.cs b/src/embed_tests/pyiter.cs index 1a4084474..1f0c651f8 100644 --- a/src/embed_tests/pyiter.cs +++ b/src/embed_tests/pyiter.cs @@ -27,11 +27,11 @@ public void TearDown() [Test] public void TestOnPyList() { - PyList list = new PyList(); + var list = new PyList(); list.Append(new PyString("foo")); list.Append(new PyString("bar")); list.Append(new PyString("baz")); - List result = new List(); + var result = new List(); foreach (PyObject item in list) { result.Add(item.ToString()); diff --git a/src/embed_tests/pythonexception.cs b/src/embed_tests/pythonexception.cs index f0bc39def..aaaf2c61c 100644 --- a/src/embed_tests/pythonexception.cs +++ b/src/embed_tests/pythonexception.cs @@ -26,7 +26,7 @@ public void TearDown() [Test] public void TestMessage() { - PyList list = new PyList(); + var list = new PyList(); try { PyObject junk = list[0]; @@ -40,7 +40,7 @@ public void TestMessage() [Test] public void TestNoError() { - PythonException e = new PythonException(); //There is no PyErr to fetch + var e = new PythonException(); //There is no PyErr to fetch Assert.AreEqual("", e.Message); } } diff --git a/src/testing/callbacktest.cs b/src/testing/callbacktest.cs index 33e240531..2838a12ca 100644 --- a/src/testing/callbacktest.cs +++ b/src/testing/callbacktest.cs @@ -37,7 +37,9 @@ public class SelfCallbackTest public void Callback(PyObject self) { using (Py.GIL()) + { ((dynamic)self).PyCallback(self); + } } } } diff --git a/src/testing/classtest.cs b/src/testing/classtest.cs index ab0cad7ad..333764610 100644 --- a/src/testing/classtest.cs +++ b/src/testing/classtest.cs @@ -10,8 +10,8 @@ public class ClassTest { public static ArrayList GetArrayList() { - ArrayList list = new ArrayList(); - for (int i = 0; i < 10; i++) + var list = new ArrayList(); + for (var i = 0; i < 10; i++) { list.Add(i); } @@ -20,7 +20,7 @@ public static ArrayList GetArrayList() public static Hashtable GetHashtable() { - Hashtable dict = new Hashtable(); + var dict = new Hashtable(); dict.Add("one", 1); dict.Add("two", 2); dict.Add("three", 3); @@ -31,7 +31,7 @@ public static Hashtable GetHashtable() public static IEnumerator GetEnumerator() { - string temp = "test string"; + var temp = "test string"; return temp.GetEnumerator(); } } diff --git a/src/testing/constructortests.cs b/src/testing/constructortests.cs index 4d3cc5710..71e50cae9 100644 --- a/src/testing/constructortests.cs +++ b/src/testing/constructortests.cs @@ -13,7 +13,7 @@ public class EnumConstructorTest public EnumConstructorTest(TypeCode v) { - this.value = v; + value = v; } } @@ -24,7 +24,7 @@ public class FlagsConstructorTest public FlagsConstructorTest(FileAccess v) { - this.value = v; + value = v; } } @@ -35,7 +35,7 @@ public class StructConstructorTest public StructConstructorTest(Guid v) { - this.value = v; + value = v; } } @@ -46,7 +46,7 @@ public class SubclassConstructorTest public SubclassConstructorTest(Exception v) { - this.value = v; + value = v; } } } diff --git a/src/testing/eventtest.cs b/src/testing/eventtest.cs index d39557c4d..b5a27a244 100644 --- a/src/testing/eventtest.cs +++ b/src/testing/eventtest.cs @@ -33,7 +33,7 @@ public class EventTest public EventTest() { - this.value = 0; + value = 0; } static EventTest() @@ -80,7 +80,7 @@ protected static void OnProtectedStaticEvent(EventArgsTest e) public void GenericHandler(object sender, EventArgsTest e) { - this.value = e.value; + value = e.value; } public static void StaticHandler(object sender, EventArgsTest e) @@ -91,8 +91,8 @@ public static void StaticHandler(object sender, EventArgsTest e) public static void ShutUpCompiler() { // Quiet compiler warnings. - EventTest e = new EventTest(); - EventHandlerTest f = new EventHandlerTest(e.GenericHandler); + var e = new EventTest(); + EventHandlerTest f = e.GenericHandler; ProtectedStaticEvent += f; InternalStaticEvent += f; PrivateStaticEvent += f; @@ -109,7 +109,7 @@ public class EventArgsTest : EventArgs public EventArgsTest(int v) { - this.value = v; + value = v; } } } diff --git a/src/testing/exceptiontest.cs b/src/testing/exceptiontest.cs index ae5fc86c0..9c45227ea 100644 --- a/src/testing/exceptiontest.cs +++ b/src/testing/exceptiontest.cs @@ -78,7 +78,7 @@ public static void ThrowChainedExceptions() public class ExtendedException : OverflowException { - public ExtendedException() : base() + public ExtendedException() { } diff --git a/src/testing/generictest.cs b/src/testing/generictest.cs index b38f5e8e5..f6aaed181 100644 --- a/src/testing/generictest.cs +++ b/src/testing/generictest.cs @@ -21,8 +21,8 @@ public class GenericTypeDefinition public GenericTypeDefinition(T arg1, U arg2) { - this.value1 = arg1; - this.value2 = arg2; + value1 = arg1; + value2 = arg2; } } @@ -34,7 +34,7 @@ public class DerivedFromOpenGeneric : public DerivedFromOpenGeneric(int arg1, V arg2, W arg3) : base(arg1, arg2) { - this.value3 = arg3; + value3 = arg3; } } diff --git a/src/testing/moduletest.cs b/src/testing/moduletest.cs index 2d5734a11..2df5269f3 100644 --- a/src/testing/moduletest.cs +++ b/src/testing/moduletest.cs @@ -1,4 +1,5 @@ using System; +using System.Reflection; using System.Threading; namespace Python.Test @@ -11,9 +12,9 @@ public static void RunThreads() { _thread = new Thread(() => { - var appdomain = AppDomain.CurrentDomain; - var assemblies = appdomain.GetAssemblies(); - foreach (var assembly in assemblies) + AppDomain appdomain = AppDomain.CurrentDomain; + Assembly[] assemblies = appdomain.GetAssemblies(); + foreach (Assembly assembly in assemblies) { assembly.GetTypes(); } diff --git a/src/testing/subclasstest.cs b/src/testing/subclasstest.cs index 9ee105aef..9817d865e 100644 --- a/src/testing/subclasstest.cs +++ b/src/testing/subclasstest.cs @@ -58,7 +58,9 @@ public static IList test_list(SubClassTest x) public virtual void OnTestEvent(int value) { if (null != TestEvent) + { TestEvent(this, new EventArgsTest(value)); + } } } @@ -89,7 +91,7 @@ public static string test_bar(IInterfaceTest x, string s, int i) // test instances can be constructed in managed code public static IInterfaceTest create_instance(Type t) { - return (IInterfaceTest)t.GetConstructor(new Type[] { }).Invoke(new Object[] { }); + return (IInterfaceTest)t.GetConstructor(new Type[] { }).Invoke(new object[] { }); } // test instances pass through managed code unchanged @@ -101,7 +103,7 @@ public static IInterfaceTest pass_through(IInterfaceTest s) public static int test_event(IInterfaceTest x, int value) { // reuse the event handler from eventtest.cs - EventTest et = new EventTest(); + var et = new EventTest(); x.TestEvent += et.GenericHandler; // raise the event (should trigger both python and managed handlers) diff --git a/src/testing/threadtest.cs b/src/testing/threadtest.cs index 0cb2abe57..d47d494a1 100644 --- a/src/testing/threadtest.cs +++ b/src/testing/threadtest.cs @@ -37,9 +37,9 @@ public static string CallEchoString(string arg) module = PythonEngine.ModuleFromString("tt", testmod); } PyObject func = module.GetAttr("echostring"); - PyString parg = new PyString(arg); + var parg = new PyString(arg); PyObject temp = func.Invoke(parg); - string result = (string)temp.AsManagedObject(typeof(String)); + var result = (string)temp.AsManagedObject(typeof(string)); func.Dispose(); parg.Dispose(); temp.Dispose(); @@ -62,9 +62,9 @@ public static string CallEchoString2(string arg) } PyObject func = module.GetAttr("echostring2"); - PyString parg = new PyString(arg); + var parg = new PyString(arg); PyObject temp = func.Invoke(parg); - string result = (string)temp.AsManagedObject(typeof(String)); + var result = (string)temp.AsManagedObject(typeof(string)); func.Dispose(); parg.Dispose(); temp.Dispose(); From bd73d5ae887a70a50d1c4254d0dc675b883162ae Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 14:48:47 -0700 Subject: [PATCH 048/245] XML Docs on test fixtures --- src/testing/arraytest.cs | 7 +++---- src/testing/callbacktest.cs | 17 ++++++++--------- src/testing/classtest.cs | 7 +++---- src/testing/constructortests.cs | 7 +++---- src/testing/conversiontest.cs | 7 +++---- src/testing/delegatetest.cs | 7 +++---- src/testing/doctest.cs | 13 +++++++------ src/testing/enumtest.cs | 7 +++---- src/testing/eventtest.cs | 7 +++---- src/testing/exceptiontest.cs | 7 +++---- src/testing/fieldtest.cs | 7 +++---- src/testing/generictest.cs | 7 +++---- src/testing/globaltest.cs | 6 +++--- src/testing/indexertest.cs | 7 +++---- src/testing/interfacetest.cs | 7 +++---- src/testing/methodtest.cs | 14 ++++++-------- src/testing/propertytest.cs | 7 +++---- src/testing/threadtest.cs | 16 ++++++++-------- 18 files changed, 71 insertions(+), 86 deletions(-) diff --git a/src/testing/arraytest.cs b/src/testing/arraytest.cs index 591b5b1c4..946684962 100644 --- a/src/testing/arraytest.cs +++ b/src/testing/arraytest.cs @@ -1,9 +1,8 @@ namespace Python.Test { - //======================================================================== - // Supports units tests for indexer access. - //======================================================================== - + /// + /// Supports units tests for indexer access. + /// public class PublicArrayTest { public int[] items; diff --git a/src/testing/callbacktest.cs b/src/testing/callbacktest.cs index 2838a12ca..321ecc86f 100644 --- a/src/testing/callbacktest.cs +++ b/src/testing/callbacktest.cs @@ -2,10 +2,9 @@ namespace Python.Test { - //======================================================================== - // Tests callbacks into python code. - //======================================================================== - + /// + /// Tests callbacks into python code. + /// public class CallbackTest { public string Call_simpleDefaultArg_WithNull(string moduleName) @@ -27,11 +26,11 @@ public string Call_simpleDefaultArg_WithEmptyArgs(string moduleName) } } - //========================================================================== - // Tests calling from Python into C# and back into Python using a PyObject. - // SelfCallbackTest should be inherited by a Python class. - // Used in test_class.py / testCallback - //========================================================================== + /// + /// Tests calling from Python into C# and back into Python using a PyObject. + /// SelfCallbackTest should be inherited by a Python class. + /// Used in test_class.py / testCallback + /// public class SelfCallbackTest { public void Callback(PyObject self) diff --git a/src/testing/classtest.cs b/src/testing/classtest.cs index 333764610..68c0d8c55 100644 --- a/src/testing/classtest.cs +++ b/src/testing/classtest.cs @@ -2,10 +2,9 @@ namespace Python.Test { - //======================================================================== - // Supports CLR class unit tests. - //======================================================================== - + /// + /// Supports CLR class unit tests. + /// public class ClassTest { public static ArrayList GetArrayList() diff --git a/src/testing/constructortests.cs b/src/testing/constructortests.cs index 71e50cae9..8800c94a1 100644 --- a/src/testing/constructortests.cs +++ b/src/testing/constructortests.cs @@ -3,10 +3,9 @@ namespace Python.Test { - //======================================================================== - // These classes support the CLR constructor unit tests. - //======================================================================== - + /// + /// These classes support the CLR constructor unit tests. + /// public class EnumConstructorTest { public TypeCode value; diff --git a/src/testing/conversiontest.cs b/src/testing/conversiontest.cs index 5686a1943..f204a9f85 100644 --- a/src/testing/conversiontest.cs +++ b/src/testing/conversiontest.cs @@ -1,9 +1,8 @@ namespace Python.Test { - //======================================================================== - // Supports units tests for field access. - //======================================================================== - + /// + /// Supports units tests for field access. + /// public class ConversionTest { public ConversionTest() diff --git a/src/testing/delegatetest.cs b/src/testing/delegatetest.cs index 94169f650..e2df9475f 100644 --- a/src/testing/delegatetest.cs +++ b/src/testing/delegatetest.cs @@ -1,9 +1,8 @@ namespace Python.Test { - //======================================================================== - // Supports CLR class unit tests. - //======================================================================== - + /// + /// Supports CLR class unit tests. + /// public delegate void PublicDelegate(); internal delegate void InternalDelegate(); diff --git a/src/testing/doctest.cs b/src/testing/doctest.cs index a0f60b2e1..98ca05de4 100644 --- a/src/testing/doctest.cs +++ b/src/testing/doctest.cs @@ -2,12 +2,13 @@ namespace Python.Test { - //======================================================================== - // Supports units tests for exposing docstrings from C# to Python - //======================================================================== - - // Classes with a constructor have their docstring set to the ctor signature. - // Test if a class has an explicit doc string it gets set correctly. + /// + /// Supports units tests for exposing docstrings from C# to Python + /// + /// + /// Classes with a constructor have their docstring set to the ctor signature. + /// Test if a class has an explicit doc string it gets set correctly. + /// [DocString("DocWithCtorTest Class")] public class DocWithCtorTest { diff --git a/src/testing/enumtest.cs b/src/testing/enumtest.cs index 0d0d56190..de5d8f5ee 100644 --- a/src/testing/enumtest.cs +++ b/src/testing/enumtest.cs @@ -2,10 +2,9 @@ namespace Python.Test { - //======================================================================== - // Supports CLR enum unit tests. - //======================================================================== - + /// + /// Supports CLR enum unit tests. + /// public enum ByteEnum : byte { Zero, diff --git a/src/testing/eventtest.cs b/src/testing/eventtest.cs index b5a27a244..4c701d488 100644 --- a/src/testing/eventtest.cs +++ b/src/testing/eventtest.cs @@ -2,10 +2,9 @@ namespace Python.Test { - //======================================================================== - // Supports CLR event unit tests. - //======================================================================== - + /// + /// Supports CLR event unit tests. + /// public delegate void EventHandlerTest(object sender, EventArgsTest e); diff --git a/src/testing/exceptiontest.cs b/src/testing/exceptiontest.cs index 9c45227ea..e4f683721 100644 --- a/src/testing/exceptiontest.cs +++ b/src/testing/exceptiontest.cs @@ -2,10 +2,9 @@ namespace Python.Test { - //======================================================================== - // Supports CLR Exception unit tests. - //======================================================================== - + /// + /// Supports CLR Exception unit tests. + /// public class ExceptionTest { public int ThrowProperty diff --git a/src/testing/fieldtest.cs b/src/testing/fieldtest.cs index 4d41cf084..d1bf6e983 100644 --- a/src/testing/fieldtest.cs +++ b/src/testing/fieldtest.cs @@ -1,9 +1,8 @@ namespace Python.Test { - //======================================================================== - // Supports units tests for field access. - //======================================================================== - + /// + /// Supports units tests for field access. + /// public class FieldTest { public FieldTest() diff --git a/src/testing/generictest.cs b/src/testing/generictest.cs index f6aaed181..848ee5cea 100644 --- a/src/testing/generictest.cs +++ b/src/testing/generictest.cs @@ -1,9 +1,8 @@ namespace Python.Test { - //======================================================================== - // Supports CLR generics unit tests. - //======================================================================== - + /// + /// Supports CLR generics unit tests. + /// public class GenericWrapper { public T value; diff --git a/src/testing/globaltest.cs b/src/testing/globaltest.cs index 2d6d56cda..83a2bc439 100644 --- a/src/testing/globaltest.cs +++ b/src/testing/globaltest.cs @@ -1,7 +1,7 @@ -//======================================================================== -// Supports units tests for access to types without a namespace. -//======================================================================== +/// +/// Supports units tests for access to types without a namespace. +/// public class NoNamespaceType { } diff --git a/src/testing/indexertest.cs b/src/testing/indexertest.cs index f1dcbda0b..74ba69755 100644 --- a/src/testing/indexertest.cs +++ b/src/testing/indexertest.cs @@ -2,10 +2,9 @@ namespace Python.Test { - //======================================================================== - // Supports units tests for indexer access. - //======================================================================== - + /// + /// Supports units tests for indexer access. + /// public class IndexerBase { protected Hashtable t; diff --git a/src/testing/interfacetest.cs b/src/testing/interfacetest.cs index 4c4056d68..2c24596bc 100644 --- a/src/testing/interfacetest.cs +++ b/src/testing/interfacetest.cs @@ -1,9 +1,8 @@ namespace Python.Test { - //======================================================================== - // Supports CLR class unit tests. - //======================================================================== - + /// + /// Supports CLR class unit tests. + /// public interface IPublicInterface { } diff --git a/src/testing/methodtest.cs b/src/testing/methodtest.cs index 65e39cf69..567dd9227 100644 --- a/src/testing/methodtest.cs +++ b/src/testing/methodtest.cs @@ -3,10 +3,9 @@ namespace Python.Test { - //======================================================================== - // Supports units tests for method access. - //======================================================================== - + /// + /// Supports units tests for method access. + /// public class MethodTest { public MethodTest() @@ -54,10 +53,9 @@ private static string PrivateStaticMethod() } - //=================================================================== - // Methods to support specific argument conversion unit tests - //=================================================================== - + /// + /// Methods to support specific argument conversion unit tests + /// public TypeCode TestEnumConversion(TypeCode v) { return v; diff --git a/src/testing/propertytest.cs b/src/testing/propertytest.cs index b70e9487a..999865ef6 100644 --- a/src/testing/propertytest.cs +++ b/src/testing/propertytest.cs @@ -1,9 +1,8 @@ namespace Python.Test { - //======================================================================== - // Supports units tests for property access. - //======================================================================== - + /// + /// Supports units tests for property access. + /// public class PropertyTest { public PropertyTest() diff --git a/src/testing/threadtest.cs b/src/testing/threadtest.cs index d47d494a1..2825c3fef 100644 --- a/src/testing/threadtest.cs +++ b/src/testing/threadtest.cs @@ -3,10 +3,9 @@ namespace Python.Test { - //======================================================================== - // Supports CLR threading / reentrancy unit tests. - //======================================================================== - + /// + /// Supports CLR threading / reentrant unit tests. + /// public class ThreadTest { private static PyObject module; @@ -23,10 +22,11 @@ public class ThreadTest "\n"; - // This method calls back into the CPython runtime - tests - // call this from Python to check that we don't hang on - // nested transitions from managed to Python code and back. - + /// + /// This method calls back into the CPython runtime - tests + /// call this from Python to check that we don't hang on + /// nested transitions from managed to Python code and back. + /// public static string CallEchoString(string arg) { IntPtr gs = PythonEngine.AcquireLock(); From f7f2fc0d2c1786399c8b1ef8e090d8ddf5bfeb03 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 15:04:28 -0700 Subject: [PATCH 049/245] Update CHANGELOG --- CHANGELOG.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 53f75e6af..dbf9f4c9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,17 +9,19 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. ### Added -- New `Foo` feature +- Code Coverage (#345) ### Changed - Refactored `setup.py` (#337) - Upgraded NUnit framework to 3.5 (#341) - Completed refactor of Build Directives on `Runtime.cs` (#339) +- Refactor tests and removed dependency on `six` (#329) +- Unfroze Mono version on Travis (#345) ### Fixed -- Fixed `FooBar` bug +- Fixed crash during Shutdown (#343) ## [2.2.2][] - 2017-01-29 From eca5ac904a4568fa06c356dfa8f628873e0192ae Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Tue, 24 Jan 2017 15:52:14 +0100 Subject: [PATCH 050/245] Implement Py.SetArgv. --- src/runtime/pythonengine.cs | 30 +++++++++++++++++++++++++++++- src/runtime/runtime.cs | 19 +++++++++++++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index c296f1b87..626a8ffca 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -500,7 +500,7 @@ public class KeywordArguments : PyDict public static KeywordArguments kw(params object[] kv) { var dict = new KeywordArguments(); - if (kv.Length%2 != 0) + if (kv.Length % 2 != 0) throw new ArgumentException("Must have an equal number of keys and values"); for (int i = 0; i < kv.Length; i += 2) { @@ -521,5 +521,33 @@ public static PyObject Import(string name) { return PythonEngine.ImportModule(name); } + + public static void SetArgv() + { + IEnumerable args; + try + { + args = Environment.GetCommandLineArgs(); + } + catch (NotSupportedException) + { + args = Enumerable.Empty(); + } + + SetArgv( + new[] { "" }.Concat( + Environment.GetCommandLineArgs().Skip(1) + ) + ); + } + + public static void SetArgv(IEnumerable argv) + { + using (GIL()) + { + var arr = argv.ToArray(); + Runtime.PySys_SetArgvEx(arr.Length, arr, 0); + } + } } } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 5f0ecfbd2..9b5c4ffb5 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -2027,11 +2027,26 @@ internal unsafe static extern IntPtr internal unsafe static extern IntPtr PyImport_GetModuleDict(); - +#if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern void - PySys_SetArgv(int argc, IntPtr argv); + PySys_SetArgvEx( + int argc, + [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] + string[] argv, + int updatepath + ); +#elif PYTHON2 + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern void + PySys_SetArgvEx( + int argc, + string[] argv, + int updatepath + ); +#endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] From 331524f16a0a60afd7f845a9b73222e386747cf7 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Thu, 26 Jan 2017 17:32:16 +0100 Subject: [PATCH 051/245] Add a `Py.Throw` function. Checks whether an error occurred and in case it has throws a PythonException. --- src/runtime/pythonengine.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 626a8ffca..93df4c778 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -549,5 +549,13 @@ public static void SetArgv(IEnumerable argv) Runtime.PySys_SetArgvEx(arr.Length, arr, 0); } } + + internal static void Throw() + { + if (Runtime.PyErr_Occurred() != 0) + { + throw new PythonException(); + } + } } } From a0849a9d490bc199752e498946153911bf0e7761 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Mon, 30 Jan 2017 14:03:18 +0100 Subject: [PATCH 052/245] Add overload for Initialize to pass specific args. --- src/embed_tests/InitializeTest.cs | 36 +++++++++++++++++++++++++++++++ src/runtime/pythonengine.cs | 19 +++++++++++++--- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/src/embed_tests/InitializeTest.cs b/src/embed_tests/InitializeTest.cs index a9667343c..212fbcff1 100644 --- a/src/embed_tests/InitializeTest.cs +++ b/src/embed_tests/InitializeTest.cs @@ -9,6 +9,42 @@ namespace Python.EmbeddingTest { public class InitializeTest { + [Test] + public static void LoadSpecificArgs() + { + var args = new[] { "test1", "test2" }; + PythonEngine.Initialize(args); + try + { + using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) + { + Assert.That(argv[0].ToString() == args[0]); + Assert.That(argv[1].ToString() == args[1]); + } + } + finally + { + PythonEngine.Shutdown(); + } + } + + [Test] + public static void LoadDefaultArgs() + { + PythonEngine.Initialize(); + try + { + using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) + { + Assert.That(argv.Length() != 0); + } + } + finally + { + PythonEngine.Shutdown(); + } + } + [Test] public static void Test() { diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 93df4c778..06510d955 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -2,6 +2,8 @@ using System.IO; using System.Threading; using System.Reflection; +using System.Collections.Generic; +using System.Linq; namespace Python.Runtime { @@ -102,6 +104,11 @@ public static int RunSimpleString(string code) #endregion + public static void Initialize() + { + Initialize(Enumerable.Empty()); + } + /// /// Initialize Method /// @@ -112,7 +119,7 @@ public static int RunSimpleString(string code) /// first call. It is *not* necessary to hold the Python global /// interpreter lock (GIL) to call this method. /// - public static void Initialize() + public static void Initialize(IEnumerable args) { if (!initialized) { @@ -126,6 +133,9 @@ public static void Initialize() initialized = true; Exceptions.Clear(); + Py.SetArgv(args); + Py.Throw(); + // register the atexit callback (this doesn't use Py_AtExit as the C atexit // callbacks are called after python is fully finalized but the python ones // are called while the python engine is still running). @@ -552,9 +562,12 @@ public static void SetArgv(IEnumerable argv) internal static void Throw() { - if (Runtime.PyErr_Occurred() != 0) + using (GIL()) { - throw new PythonException(); + if (Runtime.PyErr_Occurred() != 0) + { + throw new PythonException(); + } } } } From 4f67c5da5d592d11fb90b287c5e4b70ab68e30e8 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Tue, 31 Jan 2017 13:47:17 +0100 Subject: [PATCH 053/245] Allow the engine to be initialized as a Disposable. --- src/embed_tests/InitializeTest.cs | 30 ++++++++---------------------- src/runtime/pythonengine.cs | 30 ++++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 24 deletions(-) diff --git a/src/embed_tests/InitializeTest.cs b/src/embed_tests/InitializeTest.cs index 212fbcff1..6c6f0f1f1 100644 --- a/src/embed_tests/InitializeTest.cs +++ b/src/embed_tests/InitializeTest.cs @@ -13,40 +13,26 @@ public class InitializeTest public static void LoadSpecificArgs() { var args = new[] { "test1", "test2" }; - PythonEngine.Initialize(args); - try + using (new PythonEngine(args)) + using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) { - using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) - { - Assert.That(argv[0].ToString() == args[0]); - Assert.That(argv[1].ToString() == args[1]); - } - } - finally - { - PythonEngine.Shutdown(); + Assert.That(argv[0].ToString() == args[0]); + Assert.That(argv[1].ToString() == args[1]); } } [Test] public static void LoadDefaultArgs() { - PythonEngine.Initialize(); - try - { - using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) - { - Assert.That(argv.Length() != 0); - } - } - finally + using (new PythonEngine()) + using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) { - PythonEngine.Shutdown(); + Assert.That(argv.Length() != 0); } } [Test] - public static void Test() + public static void StartAndStopTwice() { PythonEngine.Initialize(); PythonEngine.Shutdown(); diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 06510d955..0449d3c31 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -10,11 +10,31 @@ namespace Python.Runtime /// /// This class provides the public interface of the Python runtime. /// - public class PythonEngine + public class PythonEngine : IDisposable { private static DelegateManager delegateManager; private static bool initialized; + public PythonEngine() + { + Initialize(); + } + + public PythonEngine(params string[] args) + { + Initialize(args); + } + + public PythonEngine(IEnumerable args) + { + Initialize(args); + } + + public void Dispose() + { + Shutdown(); + } + #region Properties public static bool IsInitialized @@ -197,7 +217,8 @@ public static void Initialize(IEnumerable args) // when it is imported by the CLR extension module. //==================================================================== #if PYTHON3 - public static IntPtr InitExt() { + public static IntPtr InitExt() + { #elif PYTHON2 public static void InitExt() { @@ -551,6 +572,11 @@ public static void SetArgv() ); } + public static void SetArgv(params string[] argv) + { + SetArgv(argv as IEnumerable); + } + public static void SetArgv(IEnumerable argv) { using (GIL()) From 3785c40a10d4754803374112212fc87a8da7e31d Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Tue, 31 Jan 2017 14:32:09 +0100 Subject: [PATCH 054/245] Use Py.Throw in a few more places. In particular in Py.Import. --- src/runtime/pythonengine.cs | 27 ++++++--------------------- 1 file changed, 6 insertions(+), 21 deletions(-) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 0449d3c31..754aaf2cd 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -154,7 +154,6 @@ public static void Initialize(IEnumerable args) Exceptions.Clear(); Py.SetArgv(args); - Py.Throw(); // register the atexit callback (this doesn't use Py_AtExit as the C atexit // callbacks are called after python is fully finalized but the python ones @@ -382,10 +381,7 @@ public static void EndAllowThreads(IntPtr ts) public static PyObject ImportModule(string name) { IntPtr op = Runtime.PyImport_ImportModule(name); - if (op == IntPtr.Zero) - { - return null; - } + Py.Throw(); return new PyObject(op); } @@ -401,10 +397,7 @@ public static PyObject ImportModule(string name) public static PyObject ReloadModule(PyObject module) { IntPtr op = Runtime.PyImport_ReloadModule(module.Handle); - if (op == IntPtr.Zero) - { - throw new PythonException(); - } + Py.Throw(); return new PyObject(op); } @@ -420,15 +413,9 @@ public static PyObject ReloadModule(PyObject module) public static PyObject ModuleFromString(string name, string code) { IntPtr c = Runtime.Py_CompileString(code, "none", (IntPtr)257); - if (c == IntPtr.Zero) - { - throw new PythonException(); - } + Py.Throw(); IntPtr m = Runtime.PyImport_ExecCodeModule(name, c); - if (m == IntPtr.Zero) - { - throw new PythonException(); - } + Py.Throw(); return new PyObject(m); } @@ -476,10 +463,7 @@ public static PyObject RunString( code, flag, globals.Value, locals.Value ); - if (Runtime.PyErr_Occurred() != 0) - { - throw new PythonException(); - } + Py.Throw(); return new PyObject(result); } @@ -583,6 +567,7 @@ public static void SetArgv(IEnumerable argv) { var arr = argv.ToArray(); Runtime.PySys_SetArgvEx(arr.Length, arr, 0); + Py.Throw(); } } From 78fb457c804ca3f9cec62b83fb6dbe696abccbb4 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 19:18:13 -0700 Subject: [PATCH 055/245] Add PY3.7 to travis with allow_failure --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.travis.yml b/.travis.yml index 1b5806d59..f23a4ee6c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,6 +7,11 @@ python: - 3.4 - 3.5 - 3.6 + - 3.7-dev + +matrix: + allow_failures: + - python: 3.7-dev env: global: From cb6ec6d1967dc851fb2616a81f72130f511917eb Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 20:50:37 -0700 Subject: [PATCH 056/245] Format & Whitespace *.cs linelength 120 Allman --- src/console/assemblyinfo.cs | 3 +- src/runtime/arrayobject.cs | 22 +- src/runtime/assemblymanager.cs | 37 +- src/runtime/classbase.cs | 13 +- src/runtime/classderived.cs | 3 +- src/runtime/classmanager.cs | 2 +- src/runtime/classobject.cs | 25 +- src/runtime/codegenerator.cs | 2 +- src/runtime/constructorbinder.cs | 9 +- src/runtime/constructorbinding.cs | 3 +- src/runtime/converter.cs | 154 ++++---- src/runtime/debughelper.cs | 4 +- src/runtime/delegatemanager.cs | 12 +- src/runtime/delegateobject.cs | 3 +- src/runtime/eventbinding.cs | 10 +- src/runtime/eventobject.cs | 14 +- src/runtime/extensiontype.cs | 13 +- src/runtime/fieldobject.cs | 21 +- src/runtime/generictype.cs | 9 +- src/runtime/genericutil.cs | 5 +- src/runtime/importhook.cs | 39 +- src/runtime/indexer.cs | 2 +- src/runtime/interfaceobject.cs | 13 +- src/runtime/interfaces.cs | 2 +- src/runtime/interop.cs | 41 +- src/runtime/iterator.cs | 2 +- src/runtime/managedtype.cs | 6 +- src/runtime/metatype.cs | 18 +- src/runtime/methodbinder.cs | 82 ++-- src/runtime/methodbinding.cs | 5 +- src/runtime/methodobject.cs | 5 +- src/runtime/methodwrapper.cs | 4 +- src/runtime/modulefunctionobject.cs | 2 +- src/runtime/moduleobject.cs | 5 +- src/runtime/modulepropertyobject.cs | 2 +- src/runtime/monosupport.cs | 15 +- src/runtime/nativecall.cs | 8 +- src/runtime/overload.cs | 2 +- src/runtime/propertyobject.cs | 13 +- src/runtime/pyansistring.cs | 8 +- src/runtime/pydict.cs | 2 +- src/runtime/pyfloat.cs | 2 +- src/runtime/pyint.cs | 2 +- src/runtime/pyiter.cs | 2 +- src/runtime/pylist.cs | 2 +- src/runtime/pylong.cs | 2 +- src/runtime/pynumber.cs | 2 +- src/runtime/pyobject.cs | 4 +- src/runtime/pysequence.cs | 2 +- src/runtime/pystring.cs | 2 +- src/runtime/pythonengine.cs | 3 +- src/runtime/pythonexception.cs | 2 +- src/runtime/pytuple.cs | 2 +- src/runtime/runtime.cs | 589 ++++++++++++++-------------- src/runtime/typemanager.cs | 29 +- src/runtime/typemethod.cs | 5 +- src/testing/generictest.cs | 6 +- src/testing/indexertest.cs | 6 +- src/testing/methodtest.cs | 111 ++---- 59 files changed, 647 insertions(+), 766 deletions(-) diff --git a/src/console/assemblyinfo.cs b/src/console/assemblyinfo.cs index c7d957326..fcdc2b693 100644 --- a/src/console/assemblyinfo.cs +++ b/src/console/assemblyinfo.cs @@ -10,8 +10,7 @@ [assembly: AssemblyDefaultAlias("python.exe")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] -[assembly: PermissionSet(SecurityAction.RequestMinimum, - Name = "FullTrust")] +[assembly: PermissionSet(SecurityAction.RequestMinimum, Name = "FullTrust")] [assembly: AssemblyDescription("")] [assembly: AssemblyCopyright("MIT License")] [assembly: AssemblyFileVersion("2.0.0.4")] diff --git a/src/runtime/arrayobject.cs b/src/runtime/arrayobject.cs index 2fe433e57..eaff49214 100644 --- a/src/runtime/arrayobject.cs +++ b/src/runtime/arrayobject.cs @@ -80,9 +80,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) } catch (IndexOutOfRangeException) { - Exceptions.SetError(Exceptions.IndexError, - "array index out of range" - ); + Exceptions.SetError(Exceptions.IndexError, "array index out of range"); return IntPtr.Zero; } @@ -93,9 +91,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) if (!Runtime.PyTuple_Check(idx)) { - Exceptions.SetError(Exceptions.TypeError, - "invalid index value" - ); + Exceptions.SetError(Exceptions.TypeError, "invalid index value"); return IntPtr.Zero; } @@ -127,9 +123,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) } catch (IndexOutOfRangeException) { - Exceptions.SetError(Exceptions.IndexError, - "array index out of range" - ); + Exceptions.SetError(Exceptions.IndexError, "array index out of range"); return IntPtr.Zero; } @@ -182,9 +176,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) } catch (IndexOutOfRangeException) { - Exceptions.SetError(Exceptions.IndexError, - "array index out of range" - ); + Exceptions.SetError(Exceptions.IndexError, "array index out of range"); return -1; } @@ -226,9 +218,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) } catch (IndexOutOfRangeException) { - Exceptions.SetError(Exceptions.IndexError, - "array index out of range" - ); + Exceptions.SetError(Exceptions.IndexError, "array index out of range"); return -1; } @@ -272,4 +262,4 @@ public static int mp_length(IntPtr ob) return items.Length; } } -} \ No newline at end of file +} diff --git a/src/runtime/assemblymanager.cs b/src/runtime/assemblymanager.cs index 5d9759375..f263728bb 100644 --- a/src/runtime/assemblymanager.cs +++ b/src/runtime/assemblymanager.cs @@ -39,8 +39,7 @@ private AssemblyManager() internal static void Initialize() { - namespaces = new - ConcurrentDictionary>(); + namespaces = new ConcurrentDictionary>(); probed = new Dictionary(32); //generics = new Dictionary>(); assemblies = new AssemblyList(16); @@ -206,9 +205,10 @@ public static Assembly LoadAssembly(string name) { assembly = Assembly.Load(name); } - catch (System.Exception e) + catch (System.Exception) { - //if (!(e is System.IO.FileNotFoundException)) { + //if (!(e is System.IO.FileNotFoundException)) + //{ // throw; //} } @@ -480,13 +480,15 @@ public static Type LookupType(string qname) } /// - /// Wrapper around List for thread safe access + /// Wrapper around List<Assembly> for thread safe access /// - private class AssemblyList : IEnumerable{ + private class AssemblyList : IEnumerable + { private readonly List _list; private readonly ReaderWriterLockSlim _lock; - public AssemblyList(int capacity) { + public AssemblyList(int capacity) + { _list = new List(capacity); _lock = new ReaderWriterLockSlim(); } @@ -496,16 +498,19 @@ public int Count get { _lock.EnterReadLock(); - try { + try + { return _list.Count; } - finally { + finally + { _lock.ExitReadLock(); } } } - public void Add(Assembly assembly) { + public void Add(Assembly assembly) + { _lock.EnterWriteLock(); try { @@ -519,7 +524,7 @@ public void Add(Assembly assembly) { public IEnumerator GetEnumerator() { - return ((IEnumerable) this).GetEnumerator(); + return ((IEnumerable)this).GetEnumerator(); } /// @@ -555,9 +560,15 @@ public void Reset() _listEnumerator.Reset(); } - public Assembly Current { get { return _listEnumerator.Current; } } + public Assembly Current + { + get { return _listEnumerator.Current; } + } - object IEnumerator.Current { get { return Current; } } + object IEnumerator.Current + { + get { return Current; } + } } IEnumerator IEnumerable.GetEnumerator() diff --git a/src/runtime/classbase.cs b/src/runtime/classbase.cs index 3089465e3..7c7bb0509 100644 --- a/src/runtime/classbase.cs +++ b/src/runtime/classbase.cs @@ -68,7 +68,8 @@ public virtual IntPtr type_subscript(IntPtr idx) // Standard comparison implementation for instances of reflected types. //==================================================================== - public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) { + public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) + { CLRObject co1; CLRObject co2; switch (op) @@ -116,7 +117,7 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) { case Runtime.Py_GE: co1 = GetManagedObject(ob) as CLRObject; co2 = GetManagedObject(other) as CLRObject; - if(co1 == null || co2 == null) + if (co1 == null || co2 == null) return Exceptions.RaiseTypeError("Cannot get managed object"); var co1Comp = co1.inst as IComparable; if (co1Comp == null) @@ -150,10 +151,12 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) { } else { - if (op == Runtime.Py_GE || op == Runtime.Py_GT) { + if (op == Runtime.Py_GE || op == Runtime.Py_GT) + { pyCmp = Runtime.PyTrue; } - else { + else + { pyCmp = Runtime.PyFalse; } } @@ -285,4 +288,4 @@ public static void tp_dealloc(IntPtr ob) self.gcHandle.Free(); } } -} \ No newline at end of file +} diff --git a/src/runtime/classderived.cs b/src/runtime/classderived.cs index 02d734c26..ea0cbb7e9 100644 --- a/src/runtime/classderived.cs +++ b/src/runtime/classderived.cs @@ -33,8 +33,7 @@ static ClassDerivedObject() moduleBuilders = new Dictionary, ModuleBuilder>(); } - internal ClassDerivedObject(Type tp) - : base(tp) + internal ClassDerivedObject(Type tp): base(tp) { } diff --git a/src/runtime/classmanager.cs b/src/runtime/classmanager.cs index 52fecf39c..2588adf7e 100644 --- a/src/runtime/classmanager.cs +++ b/src/runtime/classmanager.cs @@ -397,4 +397,4 @@ internal ClassInfo(Type t) public Hashtable members; public Indexer indexer; } -} \ No newline at end of file +} diff --git a/src/runtime/classobject.cs b/src/runtime/classobject.cs index bd4702c20..671f0c8e6 100644 --- a/src/runtime/classobject.cs +++ b/src/runtime/classobject.cs @@ -71,9 +71,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { if (Runtime.PyTuple_Size(args) != 1) { - Exceptions.SetError(Exceptions.TypeError, - "no constructors match given arguments" - ); + Exceptions.SetError(Exceptions.TypeError, "no constructors match given arguments"); return IntPtr.Zero; } @@ -90,17 +88,13 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) if (type.IsAbstract) { - Exceptions.SetError(Exceptions.TypeError, - "cannot instantiate abstract class" - ); + Exceptions.SetError(Exceptions.TypeError, "cannot instantiate abstract class"); return IntPtr.Zero; } if (type.IsEnum) { - Exceptions.SetError(Exceptions.TypeError, - "cannot instantiate enumeration" - ); + Exceptions.SetError(Exceptions.TypeError, "cannot instantiate enumeration"); return IntPtr.Zero; } @@ -178,9 +172,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) if (cls.indexer == null || !cls.indexer.CanGet) { - Exceptions.SetError(Exceptions.TypeError, - "unindexable object" - ); + Exceptions.SetError(Exceptions.TypeError, "unindexable object"); return IntPtr.Zero; } @@ -228,9 +220,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) if (cls.indexer == null || !cls.indexer.CanSet) { - Exceptions.SetError(Exceptions.TypeError, - "object doesn't support item assignment" - ); + Exceptions.SetError(Exceptions.TypeError, "object doesn't support item assignment"); return -1; } @@ -314,8 +304,7 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) if (cb.type != typeof(System.Delegate)) { - Exceptions.SetError(Exceptions.TypeError, - "object is not callable"); + Exceptions.SetError(Exceptions.TypeError, "object is not callable"); return IntPtr.Zero; } @@ -331,4 +320,4 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) return binder.Invoke(ob, args, kw); } } -} \ No newline at end of file +} diff --git a/src/runtime/codegenerator.cs b/src/runtime/codegenerator.cs index 01edd79ba..527ef418a 100644 --- a/src/runtime/codegenerator.cs +++ b/src/runtime/codegenerator.cs @@ -49,4 +49,4 @@ internal TypeBuilder DefineType(string name, Type basetype) return mBuilder.DefineType(name, attrs, basetype); } } -} \ No newline at end of file +} diff --git a/src/runtime/constructorbinder.cs b/src/runtime/constructorbinder.cs index 7ea7602b8..837c7ff2e 100644 --- a/src/runtime/constructorbinder.cs +++ b/src/runtime/constructorbinder.cs @@ -49,8 +49,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw) /// Binding binding = this.Bind(inst, args, kw, info); /// to take advantage of Bind()'s ability to use a single MethodBase (CI or MI). /// - internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, - MethodBase info) + internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) { Object result; @@ -96,9 +95,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, if (binding == null) { - Exceptions.SetError(Exceptions.TypeError, - "no constructor matches given arguments" - ); + Exceptions.SetError(Exceptions.TypeError, "no constructor matches given arguments"); return null; } } @@ -123,4 +120,4 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, return result; } } -} \ No newline at end of file +} diff --git a/src/runtime/constructorbinding.cs b/src/runtime/constructorbinding.cs index 8710f53bf..940650186 100644 --- a/src/runtime/constructorbinding.cs +++ b/src/runtime/constructorbinding.cs @@ -169,8 +169,7 @@ internal class BoundContructor : ExtensionType ConstructorInfo ctorInfo; IntPtr repr; - public BoundContructor(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder, ConstructorInfo ci) - : base() + public BoundContructor(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder, ConstructorInfo ci) : base() { this.type = type; Runtime.XIncref(pyTypeHndl); diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index ac1085c18..320d6eb58 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -126,7 +126,7 @@ internal static IntPtr ToPython(T value) internal static IntPtr ToPython(Object value, Type type) { - if(value is PyObject) + if (value is PyObject) { IntPtr handle = ((PyObject)value).Handle; Runtime.XIncref(handle); @@ -144,7 +144,7 @@ internal static IntPtr ToPython(Object value, Type type) } // it the type is a python subclass of a managed type then return the - // underying python object rather than construct a new wrapper object. + // underlying python object rather than construct a new wrapper object. IPythonDerivedType pyderived = value as IPythonDerivedType; if (null != pyderived) { @@ -303,7 +303,7 @@ internal static bool ToManagedValue(IntPtr value, Type obType, result = ((ClassBase)mt).type; return true; } - // shouldnt happen + // shouldn't happen return false; } @@ -323,16 +323,13 @@ internal static bool ToManagedValue(IntPtr value, Type obType, return ToEnum(value, obType, out result, setError); } - // Conversion to 'Object' is done based on some reasonable - // default conversions (Python string -> managed string, - // Python int -> Int32 etc.). - + // Conversion to 'Object' is done based on some reasonable default + // conversions (Python string -> managed string, Python int -> Int32 etc.). if (obType == objectType) { if (Runtime.IsStringType(value)) { - return ToPrimitive(value, stringType, out result, - setError); + return ToPrimitive(value, stringType, out result, setError); } else if (Runtime.PyBool_Check(value)) @@ -357,23 +354,18 @@ internal static bool ToManagedValue(IntPtr value, Type obType, else if (Runtime.PySequence_Check(value)) { - return ToArray(value, typeof(object[]), out result, - setError); + return ToArray(value, typeof(object[]), out result, setError); } if (setError) { - Exceptions.SetError(Exceptions.TypeError, - "value cannot be converted to Object" - ); + Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Object"); } return false; } - // Conversion to 'Type' is done using the same mappings as above - // for objects. - + // Conversion to 'Type' is done using the same mappings as above for objects. if (obType == typeType) { if (value == Runtime.PyStringType) @@ -414,9 +406,7 @@ internal static bool ToManagedValue(IntPtr value, Type obType, if (setError) { - Exceptions.SetError(Exceptions.TypeError, - "value cannot be converted to Type" - ); + Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Type"); } return false; @@ -429,8 +419,7 @@ internal static bool ToManagedValue(IntPtr value, Type obType, // Convert a Python value to an instance of a primitive managed type. //==================================================================== - static bool ToPrimitive(IntPtr value, Type obType, out Object result, - bool setError) + static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setError) { IntPtr overflow = Exceptions.OverflowError; TypeCode tc = Type.GetTypeCode(obType); @@ -450,8 +439,8 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, return true; case TypeCode.Int32: -#if PYTHON2 - // Trickery to support 64-bit platforms. +#if PYTHON2 // Trickery to support 64-bit platforms. + if (IntPtr.Size == 4) { op = Runtime.PyNumber_Int(value); @@ -478,33 +467,32 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, } else { -#elif PYTHON3 - // When using Python3 always use the PyLong API +#elif PYTHON3 // When using Python3 always use the PyLong API { #endif - op = Runtime.PyNumber_Long(value); - if (op == IntPtr.Zero) - { - Exceptions.Clear(); - if (Exceptions.ExceptionMatches(overflow)) - { - goto overflow; - } - goto type_error; - } - long ll = (long)Runtime.PyLong_AsLongLong(op); - Runtime.XDecref(op); - if ((ll == -1) && Exceptions.ErrorOccurred()) - { - goto overflow; - } - if (ll > Int32.MaxValue || ll < Int32.MinValue) + op = Runtime.PyNumber_Long(value); + if (op == IntPtr.Zero) + { + Exceptions.Clear(); + if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } - result = (int)ll; - return true; + goto type_error; + } + long ll = (long)Runtime.PyLong_AsLongLong(op); + Runtime.XDecref(op); + if ((ll == -1) && Exceptions.ErrorOccurred()) + { + goto overflow; + } + if (ll > Int32.MaxValue || ll < Int32.MinValue) + { + goto overflow; } + result = (int)ll; + return true; + } case TypeCode.Boolean: result = (Runtime.PyObject_IsTrue(value) != 0); @@ -512,16 +500,16 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, case TypeCode.Byte: #if PYTHON3 - if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) - { - if (Runtime.PyBytes_Size(value) == 1) + if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { - op = Runtime.PyBytes_AS_STRING(value); - result = (byte)Marshal.ReadByte(op); - return true; + if (Runtime.PyBytes_Size(value) == 1) + { + op = Runtime.PyBytes_AS_STRING(value); + result = (byte)Marshal.ReadByte(op); + return true; + } + goto type_error; } - goto type_error; - } #elif PYTHON2 if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType)) { @@ -557,14 +545,16 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, case TypeCode.SByte: #if PYTHON3 - if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { - if (Runtime.PyBytes_Size(value) == 1) { - op = Runtime.PyBytes_AS_STRING(value); - result = (byte)Marshal.ReadByte(op); - return true; + if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) + { + if (Runtime.PyBytes_Size(value) == 1) + { + op = Runtime.PyBytes_AS_STRING(value); + result = (byte)Marshal.ReadByte(op); + return true; + } + goto type_error; } - goto type_error; - } #elif PYTHON2 if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType)) { @@ -600,14 +590,16 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, case TypeCode.Char: #if PYTHON3 - if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { - if (Runtime.PyBytes_Size(value) == 1) { - op = Runtime.PyBytes_AS_STRING(value); - result = (byte)Marshal.ReadByte(op); - return true; + if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) + { + if (Runtime.PyBytes_Size(value) == 1) + { + op = Runtime.PyBytes_AS_STRING(value); + result = (byte)Marshal.ReadByte(op); + return true; + } + goto type_error; } - goto type_error; - } #elif PYTHON2 if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType)) { @@ -620,19 +612,18 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, goto type_error; } #endif - else if (Runtime.PyObject_TypeCheck(value, - Runtime.PyUnicodeType)) + else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType)) { if (Runtime.PyUnicode_GetSize(value) == 1) { op = Runtime.PyUnicode_AS_UNICODE(value); #if !UCS4 - // 2011-01-02: Marshal as character array because the cast - // result = (char)Marshal.ReadInt16(op); throws an OverflowException - // on negative numbers with Check Overflow option set on the project - Char[] buff = new Char[1]; - Marshal.Copy(op, buff, 0, 1); - result = buff[0]; + // 2011-01-02: Marshal as character array because the cast + // result = (char)Marshal.ReadInt16(op); throws an OverflowException + // on negative numbers with Check Overflow option set on the project + Char[] buff = new Char[1]; + Marshal.Copy(op, buff, 0, 1); + result = buff[0]; #else // XXX this is probably NOT correct? result = (char)Marshal.ReadInt32(op); @@ -830,9 +821,7 @@ static void SetConversionError(IntPtr value, Type target) IntPtr ob = Runtime.PyObject_Repr(value); string src = Runtime.GetManagedString(ob); Runtime.XDecref(ob); - string error = String.Format( - "Cannot convert {0} to {1}", src, target - ); + string error = String.Format("Cannot convert {0} to {1}", src, target); Exceptions.SetError(Exceptions.TypeError, error); } @@ -843,8 +832,7 @@ static void SetConversionError(IntPtr value, Type target) // items in the sequence must be convertible to the target array type. //==================================================================== - static bool ToArray(IntPtr value, Type obType, out Object result, - bool setError) + static bool ToArray(IntPtr value, Type obType, out Object result, bool setError) { Type elementType = obType.GetElementType(); int size = Runtime.PySequence_Size(value); @@ -861,8 +849,7 @@ static bool ToArray(IntPtr value, Type obType, out Object result, Array items = Array.CreateInstance(elementType, size); - // XXX - is there a better way to unwrap this if it is a real - // array? + // XXX - is there a better way to unwrap this if it is a real array? for (int i = 0; i < size; i++) { Object obj = null; @@ -895,8 +882,7 @@ static bool ToArray(IntPtr value, Type obType, out Object result, // Convert a Python value to a correctly typed managed enum instance. //==================================================================== - static bool ToEnum(IntPtr value, Type obType, out Object result, - bool setError) + static bool ToEnum(IntPtr value, Type obType, out Object result, bool setError) { Type etype = Enum.GetUnderlyingType(obType); result = null; diff --git a/src/runtime/debughelper.cs b/src/runtime/debughelper.cs index d65300e39..94dd026f6 100644 --- a/src/runtime/debughelper.cs +++ b/src/runtime/debughelper.cs @@ -67,7 +67,7 @@ internal static void DumpType(IntPtr type) for (int i = 0; i < slots.Length; i++) { - int offset = i*size; + int offset = i * size; name = slots[i].Name; op = Marshal.ReadIntPtr(type, offset); Console.WriteLine(" {0}: {1}", name, op); @@ -119,4 +119,4 @@ internal static void debug(string msg) return; } } -} \ No newline at end of file +} diff --git a/src/runtime/delegatemanager.cs b/src/runtime/delegatemanager.cs index 1e652214b..a9e26fb01 100644 --- a/src/runtime/delegatemanager.cs +++ b/src/runtime/delegatemanager.cs @@ -108,12 +108,7 @@ private Type GetDispatcher(Type dtype) signature[i] = pi[i].ParameterType; } - MethodBuilder mb = tb.DefineMethod( - "Invoke", - MethodAttributes.Public, - method.ReturnType, - signature - ); + MethodBuilder mb = tb.DefineMethod("Invoke", MethodAttributes.Public, method.ReturnType, signature); ConstructorInfo ctor = listtype.GetConstructor(Type.EmptyTypes); MethodInfo dispatch = basetype.GetMethod("Dispatch"); @@ -271,8 +266,7 @@ public object TrueDispatch(ArrayList args) Object result = null; if (!Converter.ToManaged(op, rtype, out result, false)) { - string s = "could not convert Python result to " + - rtype.ToString(); + string s = "could not convert Python result to " + rtype.ToString(); Runtime.XDecref(op); throw new ConversionException(s); } @@ -293,4 +287,4 @@ public ConversionException(string msg) : base(msg) { } } -} \ No newline at end of file +} diff --git a/src/runtime/delegateobject.cs b/src/runtime/delegateobject.cs index 61e91942b..2186e98ad 100644 --- a/src/runtime/delegateobject.cs +++ b/src/runtime/delegateobject.cs @@ -103,7 +103,8 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) // Implements __cmp__ for reflected delegate types. //==================================================================== #if PYTHON3 - public static new IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) { + public static new IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) + { if (op != Runtime.Py_EQ && op != Runtime.Py_NE) { Runtime.XIncref(Runtime.PyNotImplemented); diff --git a/src/runtime/eventbinding.cs b/src/runtime/eventbinding.cs index 6035c8e0b..090d812ca 100644 --- a/src/runtime/eventbinding.cs +++ b/src/runtime/eventbinding.cs @@ -29,9 +29,7 @@ public static IntPtr nb_inplace_add(IntPtr ob, IntPtr arg) if (Runtime.PyCallable_Check(arg) < 1) { - Exceptions.SetError(Exceptions.TypeError, - "event handlers must be callable" - ); + Exceptions.SetError(Exceptions.TypeError, "event handlers must be callable"); return IntPtr.Zero; } @@ -55,9 +53,7 @@ public static IntPtr nb_inplace_subtract(IntPtr ob, IntPtr arg) if (Runtime.PyCallable_Check(arg) < 1) { - Exceptions.SetError(Exceptions.TypeError, - "invalid event handler" - ); + Exceptions.SetError(Exceptions.TypeError, "invalid event handler"); return IntPtr.Zero; } @@ -131,4 +127,4 @@ public static IntPtr tp_repr(IntPtr ob) ExtensionType.FinalizeObject(self); } } -} \ No newline at end of file +} diff --git a/src/runtime/eventobject.cs b/src/runtime/eventobject.cs index 6523f7e20..191a95546 100644 --- a/src/runtime/eventobject.cs +++ b/src/runtime/eventobject.cs @@ -87,9 +87,7 @@ internal bool RemoveEventHandler(IntPtr target, IntPtr handler) IntPtr hash = Runtime.PyObject_Hash(handler); if (Exceptions.ErrorOccurred() || (reg == null)) { - Exceptions.SetError(Exceptions.ValueError, - "unknown event handler" - ); + Exceptions.SetError(Exceptions.ValueError, "unknown event handler"); return false; } @@ -98,9 +96,7 @@ internal bool RemoveEventHandler(IntPtr target, IntPtr handler) if (list == null) { - Exceptions.SetError(Exceptions.ValueError, - "unknown event handler" - ); + Exceptions.SetError(Exceptions.ValueError, "unknown event handler"); return false; } @@ -127,9 +123,7 @@ internal bool RemoveEventHandler(IntPtr target, IntPtr handler) return true; } - Exceptions.SetError(Exceptions.ValueError, - "unknown event handler" - ); + Exceptions.SetError(Exceptions.ValueError, "unknown event handler"); return false; } @@ -236,4 +230,4 @@ public Handler(IntPtr hash, Delegate d) this.del = d; } } -} \ No newline at end of file +} diff --git a/src/runtime/extensiontype.cs b/src/runtime/extensiontype.cs index 91ff5be2e..769904444 100644 --- a/src/runtime/extensiontype.cs +++ b/src/runtime/extensiontype.cs @@ -21,11 +21,12 @@ public ExtensionType() : base() IntPtr tp = TypeManager.GetTypeHandle(this.GetType()); -// int rc = (int)Marshal.ReadIntPtr(tp, TypeOffset.ob_refcnt); -// if (rc > 1050) { -// DebugUtil.Print("tp is: ", tp); -// DebugUtil.DumpType(tp); -// } + //int rc = (int)Marshal.ReadIntPtr(tp, TypeOffset.ob_refcnt); + //if (rc > 1050) + //{ + // DebugUtil.Print("tp is: ", tp); + // DebugUtil.DumpType(tp); + //} IntPtr py = Runtime.PyType_GenericAlloc(tp, 0); @@ -120,4 +121,4 @@ public static void tp_dealloc(IntPtr ob) FinalizeObject(self); } } -} \ No newline at end of file +} diff --git a/src/runtime/fieldobject.cs b/src/runtime/fieldobject.cs index d9740d9b1..53597aee7 100644 --- a/src/runtime/fieldobject.cs +++ b/src/runtime/fieldobject.cs @@ -41,9 +41,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) if (!info.IsStatic) { Exceptions.SetError(Exceptions.TypeError, - "instance attribute must be accessed " + - "through a class instance" - ); + "instance attribute must be accessed " + "through a class instance"); return IntPtr.Zero; } try @@ -89,9 +87,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) if (val == IntPtr.Zero) { - Exceptions.SetError(Exceptions.TypeError, - "cannot delete field" - ); + Exceptions.SetError(Exceptions.TypeError, "cannot delete field"); return -1; } @@ -99,9 +95,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) if (info.IsLiteral || info.IsInitOnly) { - Exceptions.SetError(Exceptions.TypeError, - "field is read-only" - ); + Exceptions.SetError(Exceptions.TypeError, "field is read-only"); return -1; } @@ -112,15 +106,12 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) if (!is_static) { Exceptions.SetError(Exceptions.TypeError, - "instance attribute must be set " + - "through a class instance" - ); + "instance attribute must be set " + "through a class instance"); return -1; } } - if (!Converter.ToManaged(val, info.FieldType, out newval, - true)) + if (!Converter.ToManaged(val, info.FieldType, out newval, true)) { return -1; } @@ -156,4 +147,4 @@ public static IntPtr tp_repr(IntPtr ob) return Runtime.PyString_FromStringAndSize(s, s.Length); } } -} \ No newline at end of file +} diff --git a/src/runtime/generictype.cs b/src/runtime/generictype.cs index d5caec38e..19cde37bf 100644 --- a/src/runtime/generictype.cs +++ b/src/runtime/generictype.cs @@ -21,9 +21,7 @@ internal GenericType(Type tp) : base(tp) public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { - Exceptions.SetError(Exceptions.TypeError, - "cannot instantiate an open generic type" - ); + Exceptions.SetError(Exceptions.TypeError, "cannot instantiate an open generic type"); return IntPtr.Zero; } @@ -34,9 +32,8 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { - Exceptions.SetError(Exceptions.TypeError, - "object is not callable"); + Exceptions.SetError(Exceptions.TypeError, "object is not callable"); return IntPtr.Zero; } } -} \ No newline at end of file +} diff --git a/src/runtime/genericutil.cs b/src/runtime/genericutil.cs index 18d59602a..9870b2a5b 100644 --- a/src/runtime/genericutil.cs +++ b/src/runtime/genericutil.cs @@ -21,8 +21,7 @@ private GenericUtil() static GenericUtil() { - mapping = new - Dictionary>>(); + mapping = new Dictionary>>(); } //==================================================================== @@ -162,4 +161,4 @@ public static string GenericNameForBaseName(string ns, string name) return null; } } -} \ No newline at end of file +} diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index dca5a53b4..851bf49d7 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -76,7 +76,8 @@ internal static void Initialize() internal static void Shutdown() { - if (0 != Runtime.Py_IsInitialized()) { + if (0 != Runtime.Py_IsInitialized()) + { #if PYTHON3 Runtime.XDecref(py_clr_module); #elif PYTHON2 @@ -94,23 +95,27 @@ public static IntPtr GetCLRModule(IntPtr? fromList = null) { root.InitializePreload(); #if PYTHON3 - // update the module dictionary with the contents of the root dictionary + // update the module dictionary with the contents of the root dictionary root.LoadNames(); IntPtr py_mod_dict = Runtime.PyModule_GetDict(py_clr_module); IntPtr clr_dict = Runtime._PyObject_GetDictPtr(root.pyHandle); // PyObject** clr_dict = (IntPtr)Marshal.PtrToStructure(clr_dict, typeof(IntPtr)); Runtime.PyDict_Update(py_mod_dict, clr_dict); - // find any items from the fromlist and get them from the root if they're not - // aleady in the module dictionary - if (fromList != null && fromList != IntPtr.Zero) { + // find any items from the from list and get them from the root if they're not + // already in the module dictionary + if (fromList != null && fromList != IntPtr.Zero) + { if (Runtime.PyTuple_Check(fromList.GetValueOrDefault())) { Runtime.XIncref(py_mod_dict); - using(PyDict mod_dict = new PyDict(py_mod_dict)) { + using (PyDict mod_dict = new PyDict(py_mod_dict)) + { Runtime.XIncref(fromList.GetValueOrDefault()); - using (PyTuple from = new PyTuple(fromList.GetValueOrDefault())) { - foreach (PyObject item in from) { + using (PyTuple from = new PyTuple(fromList.GetValueOrDefault())) + { + foreach (PyObject item in from) + { if (mod_dict.HasKey(item)) continue; @@ -123,7 +128,8 @@ public static IntPtr GetCLRModule(IntPtr? fromList = null) continue; Runtime.XIncref(attr.pyHandle); - using (PyObject obj = new PyObject(attr.pyHandle)) { + using (PyObject obj = new PyObject(attr.pyHandle)) + { mod_dict.SetItem(s, obj); } } @@ -153,9 +159,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) int num_args = Runtime.PyTuple_Size(args); if (num_args < 1) { - return Exceptions.RaiseTypeError( - "__import__() takes at least 1 argument (0 given)" - ); + return Exceptions.RaiseTypeError("__import__() takes at least 1 argument (0 given)"); } // borrowed reference @@ -200,8 +204,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) } if (mod_name == "CLR") { - Exceptions.deprecation("The CLR module is deprecated. " + - "Please use 'clr'."); + Exceptions.deprecation("The CLR module is deprecated. " + "Please use 'clr'."); IntPtr clr_module = GetCLRModule(fromList); if (clr_module != IntPtr.Zero) { @@ -337,16 +340,12 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) } // Add the module to sys.modules - Runtime.PyDict_SetItemString(modules, - tail.moduleName, - tail.pyHandle); + Runtime.PyDict_SetItemString(modules, tail.moduleName, tail.pyHandle); // If imported from CLR add CLR. to sys.modules as well if (clr_prefix != null) { - Runtime.PyDict_SetItemString(modules, - clr_prefix + tail.moduleName, - tail.pyHandle); + Runtime.PyDict_SetItemString(modules, clr_prefix + tail.moduleName, tail.pyHandle); } } diff --git a/src/runtime/indexer.cs b/src/runtime/indexer.cs index 86e290d5b..06355c9f7 100644 --- a/src/runtime/indexer.cs +++ b/src/runtime/indexer.cs @@ -111,4 +111,4 @@ internal IntPtr GetDefaultArgs(IntPtr args) return defaultArgs; } } -} \ No newline at end of file +} diff --git a/src/runtime/interfaceobject.cs b/src/runtime/interfaceobject.cs index f550a95a8..076ecc727 100644 --- a/src/runtime/interfaceobject.cs +++ b/src/runtime/interfaceobject.cs @@ -16,8 +16,7 @@ internal class InterfaceObject : ClassBase internal InterfaceObject(Type tp) : base(tp) { - CoClassAttribute coclass = (CoClassAttribute) - Attribute.GetCustomAttribute(tp, cc_attr); + CoClassAttribute coclass = (CoClassAttribute)Attribute.GetCustomAttribute(tp, cc_attr); if (coclass != null) { ctor = coclass.CoClass.GetConstructor(Type.EmptyTypes); @@ -63,22 +62,18 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) if (obj == null || !type.IsInstanceOfType(obj)) { - Exceptions.SetError(Exceptions.TypeError, - "CoClass default constructor failed" - ); + Exceptions.SetError(Exceptions.TypeError, "CoClass default constructor failed"); return IntPtr.Zero; } } else { - Exceptions.SetError(Exceptions.TypeError, - "interface takes exactly one argument" - ); + Exceptions.SetError(Exceptions.TypeError, "interface takes exactly one argument"); return IntPtr.Zero; } return CLRObject.GetInstHandle(obj, self.pyHandle); } } -} \ No newline at end of file +} diff --git a/src/runtime/interfaces.cs b/src/runtime/interfaces.cs index 28f343529..d0edfbf9c 100644 --- a/src/runtime/interfaces.cs +++ b/src/runtime/interfaces.cs @@ -29,4 +29,4 @@ internal interface IReflectedArray : IReflectedType internal interface IReflectedGenericClass : IReflectedClass { } -} \ No newline at end of file +} diff --git a/src/runtime/interop.cs b/src/runtime/interop.cs index 3dc5ad827..9be8169d2 100644 --- a/src/runtime/interop.cs +++ b/src/runtime/interop.cs @@ -81,16 +81,16 @@ static ObjectOffset() _ob_prev = 1 * size; n = 2; #endif - ob_refcnt = (n + 0)*size; - ob_type = (n + 1)*size; - ob_dict = (n + 2)*size; - ob_data = (n + 3)*size; + ob_refcnt = (n + 0) * size; + ob_type = (n + 1) * size; + ob_dict = (n + 2) * size; + ob_data = (n + 3) * size; } public static int magic(IntPtr ob) { if ((Runtime.PyObject_TypeCheck(ob, Exceptions.BaseException) || - (Runtime.PyType_Check(ob) && Runtime.PyType_IsSubtype(ob, Exceptions.BaseException)))) + (Runtime.PyType_Check(ob) && Runtime.PyType_IsSubtype(ob, Exceptions.BaseException)))) { return ExceptionOffset.ob_data; } @@ -100,7 +100,7 @@ public static int magic(IntPtr ob) public static int DictOffset(IntPtr ob) { if ((Runtime.PyObject_TypeCheck(ob, Exceptions.BaseException) || - (Runtime.PyType_Check(ob) && Runtime.PyType_IsSubtype(ob, Exceptions.BaseException)))) + (Runtime.PyType_Check(ob) && Runtime.PyType_IsSubtype(ob, Exceptions.BaseException)))) { return ExceptionOffset.ob_dict; } @@ -110,7 +110,7 @@ public static int DictOffset(IntPtr ob) public static int Size(IntPtr ob) { if ((Runtime.PyObject_TypeCheck(ob, Exceptions.BaseException) || - (Runtime.PyType_Check(ob) && Runtime.PyType_IsSubtype(ob, Exceptions.BaseException)))) + (Runtime.PyType_Check(ob) && Runtime.PyType_IsSubtype(ob, Exceptions.BaseException)))) { return ExceptionOffset.Size(); } @@ -186,7 +186,7 @@ static BytesOffset() /* The *real* layout of a type object when allocated on the heap */ //typedef struct _heaptypeobject { -#if Py_DEBUG // #ifdef Py_TRACE_REFS +#if Py_DEBUG // #ifdef Py_TRACE_REFS /* _PyObject_HEAD_EXTRA defines pointers to support a doubly-linked list of all live heap objects. */ public static int _ob_next = 0; public static int _ob_prev = 0; @@ -196,7 +196,7 @@ static BytesOffset() public static int ob_refcnt = 0; public static int ob_type = 0; // } - public static int ob_size = 0; /* Number of items in _VAR_iable part */ + public static int ob_size = 0; /* Number of items in _VAR_iable part */ // } public static int ob_shash = 0; public static int ob_sval = 0; /* start of data */ @@ -223,7 +223,8 @@ static ModuleDefOffset() } } - public static IntPtr AllocModuleDef(string modulename) { + public static IntPtr AllocModuleDef(string modulename) + { byte[] ascii = Encoding.ASCII.GetBytes(modulename); int size = name + ascii.Length + 1; IntPtr ptr = Marshal.AllocHGlobal(size); @@ -235,7 +236,8 @@ public static IntPtr AllocModuleDef(string modulename) { return ptr; } - public static void FreeModuleDef(IntPtr ptr) { + public static void FreeModuleDef(IntPtr ptr) + { Marshal.FreeHGlobal(ptr); } @@ -268,8 +270,7 @@ public static void FreeModuleDef(IntPtr ptr) { /// internal class TypeFlags { -#if PYTHON2 - // these flags were removed in Python 3 +#if PYTHON2 // these flags were removed in Python 3 public static int HaveGetCharBuffer = (1 << 0); public static int HaveSequenceIn = (1 << 1); public static int GC = 0; @@ -307,8 +308,7 @@ internal class TypeFlags public static int BaseExceptionSubclass = (1 << 30); public static int TypeSubclass = (1 << 31); -#if PYTHON2 - // Default flags for Python 2 +#if PYTHON2 // Default flags for Python 2 public static int Default = ( HaveGetCharBuffer | HaveSequenceIn | @@ -318,13 +318,12 @@ internal class TypeFlags HaveIter | HaveClass | HaveStacklessExtension | - HaveIndex | - 0); -#elif PYTHON3 - // Default flags for Python 3 + HaveIndex | + 0); +#elif PYTHON3 // Default flags for Python 3 public static int Default = ( - HaveStacklessExtension | - HaveVersionTag); + HaveStacklessExtension | + HaveVersionTag); #endif } diff --git a/src/runtime/iterator.cs b/src/runtime/iterator.cs index c9b232e5e..dcab722f1 100644 --- a/src/runtime/iterator.cs +++ b/src/runtime/iterator.cs @@ -41,4 +41,4 @@ public static IntPtr tp_iter(IntPtr ob) return ob; } } -} \ No newline at end of file +} diff --git a/src/runtime/managedtype.cs b/src/runtime/managedtype.cs index 782865f93..ebb2057b9 100644 --- a/src/runtime/managedtype.cs +++ b/src/runtime/managedtype.cs @@ -51,9 +51,7 @@ internal static ManagedType GetManagedObjectErr(IntPtr ob) ManagedType result = GetManagedObject(ob); if (result == null) { - Exceptions.SetError(Exceptions.TypeError, - "invalid argument, expected CLR type" - ); + Exceptions.SetError(Exceptions.TypeError, "invalid argument, expected CLR type"); } return result; } @@ -78,4 +76,4 @@ internal static bool IsManagedType(IntPtr ob) return false; } } -} \ No newline at end of file +} diff --git a/src/runtime/metatype.cs b/src/runtime/metatype.cs index b2ad78078..b1761c2d7 100644 --- a/src/runtime/metatype.cs +++ b/src/runtime/metatype.cs @@ -51,9 +51,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) if (Runtime.PyTuple_Size(bases) != 1) { - return Exceptions.RaiseTypeError( - "cannot use multiple inheritance with managed classes" - ); + return Exceptions.RaiseTypeError("cannot use multiple inheritance with managed classes"); } IntPtr base_type = Runtime.PyTuple_GetItem(bases, 0); @@ -72,18 +70,14 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { if (!cb.CanSubclass()) { - return Exceptions.RaiseTypeError( - "delegates, enums and array types cannot be subclassed" - ); + return Exceptions.RaiseTypeError("delegates, enums and array types cannot be subclassed"); } } IntPtr slots = Runtime.PyDict_GetItemString(dict, "__slots__"); if (slots != IntPtr.Zero) { - return Exceptions.RaiseTypeError( - "subclasses of managed classes do not support __slots__" - ); + return Exceptions.RaiseTypeError("subclasses of managed classes do not support __slots__"); } // If __assembly__ or __namespace__ are in the class dictionary then create @@ -101,8 +95,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) } // otherwise just create a basic type without reflecting back into the managed side. - IntPtr func = Marshal.ReadIntPtr(Runtime.PyTypeType, - TypeOffset.tp_new); + IntPtr func = Marshal.ReadIntPtr(Runtime.PyTypeType, TypeOffset.tp_new); IntPtr type = NativeCall.Call_3(func, tp, args, kw); if (type == IntPtr.Zero) { @@ -227,8 +220,7 @@ public static int tp_setattro(IntPtr tp, IntPtr name, IntPtr value) } else { - Exceptions.SetError(Exceptions.AttributeError, - "attribute is read-only"); + Exceptions.SetError(Exceptions.AttributeError, "attribute is read-only"); return -1; } } diff --git a/src/runtime/methodbinder.cs b/src/runtime/methodbinder.cs index c3b3e4a70..c4d41d156 100644 --- a/src/runtime/methodbinder.cs +++ b/src/runtime/methodbinder.cs @@ -198,23 +198,38 @@ internal static int GetPrecedence(MethodBase mi) internal static int ArgPrecedence(Type t) { Type objectType = typeof(Object); - if (t == objectType) return 3000; + if (t == objectType) + return 3000; TypeCode tc = Type.GetTypeCode(t); - if (tc == TypeCode.Object) return 1; - if (tc == TypeCode.UInt64) return 10; - if (tc == TypeCode.UInt32) return 11; - if (tc == TypeCode.UInt16) return 12; - if (tc == TypeCode.Int64) return 13; - if (tc == TypeCode.Int32) return 14; - if (tc == TypeCode.Int16) return 15; - if (tc == TypeCode.Char) return 16; - if (tc == TypeCode.SByte) return 17; - if (tc == TypeCode.Byte) return 18; - if (tc == TypeCode.Single) return 20; - if (tc == TypeCode.Double) return 21; - if (tc == TypeCode.String) return 30; - if (tc == TypeCode.Boolean) return 40; + if (tc == TypeCode.Object) + return 1; + if (tc == TypeCode.UInt64) + return 10; + if (tc == TypeCode.UInt32) + return 11; + if (tc == TypeCode.UInt16) + return 12; + if (tc == TypeCode.Int64) + return 13; + if (tc == TypeCode.Int32) + return 14; + if (tc == TypeCode.Int16) + return 15; + if (tc == TypeCode.Char) + return 16; + if (tc == TypeCode.SByte) + return 17; + if (tc == TypeCode.Byte) + return 18; + if (tc == TypeCode.Single) + return 20; + if (tc == TypeCode.Double) + return 21; + if (tc == TypeCode.String) + return 30; + if (tc == TypeCode.Boolean) + return 40; if (t.IsArray) { @@ -238,14 +253,12 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw) return this.Bind(inst, args, kw, null, null); } - internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, - MethodBase info) + internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) { return this.Bind(inst, args, kw, info, null); } - internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, - MethodBase info, MethodInfo[] methodinfo) + internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo) { // loop to find match, return invoker w/ or /wo error MethodBase[] _methods = null; @@ -255,9 +268,7 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, ArrayList defaultArgList = null; if (info != null) { - _methods = (MethodBase[])Array.CreateInstance( - typeof(MethodBase), 1 - ); + _methods = (MethodBase[])Array.CreateInstance(typeof(MethodBase), 1); _methods.SetValue(info, 0); } else @@ -461,14 +472,12 @@ internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw) return this.Invoke(inst, args, kw, null, null); } - internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, - MethodBase info) + internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) { return this.Invoke(inst, args, kw, info, null); } - internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, - MethodBase info, MethodInfo[] methodinfo) + internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo) { Binding binding = this.Bind(inst, args, kw, info, methodinfo); Object result; @@ -476,9 +485,7 @@ internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, if (binding == null) { - Exceptions.SetError(Exceptions.TypeError, - "No method matches given arguments" - ); + Exceptions.SetError(Exceptions.TypeError, "No method matches given arguments"); return IntPtr.Zero; } @@ -489,11 +496,7 @@ internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, try { - result = binding.info.Invoke(binding.inst, - BindingFlags.Default, - null, - binding.args, - null); + result = binding.info.Invoke(binding.inst, BindingFlags.Default, null, binding.args, null); } catch (Exception e) { @@ -574,8 +577,10 @@ int IComparer.Compare(Object m1, Object m2) { int p1 = MethodBinder.GetPrecedence((MethodBase)m1); int p2 = MethodBinder.GetPrecedence((MethodBase)m2); - if (p1 < p2) return -1; - if (p1 > p2) return 1; + if (p1 < p2) + return -1; + if (p1 > p2) + return 1; return 0; } } @@ -594,8 +599,7 @@ internal class Binding public Object inst; public int outs; - internal Binding(MethodBase info, Object inst, Object[] args, - int outs) + internal Binding(MethodBase info, Object inst, Object[] args, int outs) { this.info = info; this.inst = inst; @@ -603,4 +607,4 @@ internal Binding(MethodBase info, Object inst, Object[] args, this.outs = outs; } } -} \ No newline at end of file +} diff --git a/src/runtime/methodbinding.cs b/src/runtime/methodbinding.cs index d8fec069c..9d328381f 100644 --- a/src/runtime/methodbinding.cs +++ b/src/runtime/methodbinding.cs @@ -117,7 +117,8 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { Type[] genericTp = self.info.GetGenericArguments(); MethodInfo betterMatch = MethodBinder.MatchSignatureAndParameters(self.m.info, genericTp, sigTp); - if (betterMatch != null) self.info = betterMatch; + if (betterMatch != null) + self.info = betterMatch; } } } @@ -245,4 +246,4 @@ public static IntPtr tp_repr(IntPtr ob) ExtensionType.FinalizeObject(self); } } -} \ No newline at end of file +} diff --git a/src/runtime/methodobject.cs b/src/runtime/methodobject.cs index 20f757d58..b3e1a66c5 100644 --- a/src/runtime/methodobject.cs +++ b/src/runtime/methodobject.cs @@ -53,8 +53,7 @@ public virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw) return this.Invoke(inst, args, kw, null); } - public virtual IntPtr Invoke(IntPtr target, IntPtr args, IntPtr kw, - MethodBase info) + public virtual IntPtr Invoke(IntPtr target, IntPtr args, IntPtr kw, MethodBase info) { return binder.Invoke(target, args, kw, info, this.info); } @@ -210,4 +209,4 @@ public static IntPtr tp_repr(IntPtr ob) ExtensionType.FinalizeObject(self); } } -} \ No newline at end of file +} diff --git a/src/runtime/methodwrapper.cs b/src/runtime/methodwrapper.cs index 53c0a3cc9..71932ddd0 100644 --- a/src/runtime/methodwrapper.cs +++ b/src/runtime/methodwrapper.cs @@ -24,7 +24,7 @@ public MethodWrapper(Type type, string name, string funcType = null) // Allocate and initialize a PyMethodDef structure to represent // the managed method, then create a PyCFunction. - mdef = Runtime.PyMem_Malloc(4*IntPtr.Size); + mdef = Runtime.PyMem_Malloc(4 * IntPtr.Size); TypeManager.WriteMethodDef(mdef, name, fp, 0x0003); ptr = Runtime.PyCFunction_NewEx(mdef, IntPtr.Zero, IntPtr.Zero); } @@ -34,4 +34,4 @@ public IntPtr Call(IntPtr args, IntPtr kw) return Runtime.PyCFunction_Call(ptr, args, kw); } } -} \ No newline at end of file +} diff --git a/src/runtime/modulefunctionobject.cs b/src/runtime/modulefunctionobject.cs index efd0384c4..667b37fe9 100644 --- a/src/runtime/modulefunctionobject.cs +++ b/src/runtime/modulefunctionobject.cs @@ -43,4 +43,4 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) return Runtime.PyString_FromStringAndSize(s, s.Length); } } -} \ No newline at end of file +} diff --git a/src/runtime/moduleobject.cs b/src/runtime/moduleobject.cs index 87e3ed2f1..c4fec976b 100644 --- a/src/runtime/moduleobject.cs +++ b/src/runtime/moduleobject.cs @@ -159,8 +159,7 @@ public ManagedType GetAttribute(string name, bool guess) if (guess) { - string gname = GenericUtil.GenericNameForBaseName( - _namespace, name); + string gname = GenericUtil.GenericNameForBaseName(_namespace, name); if (gname != null) { ManagedType o = GetAttribute(gname, false); @@ -447,4 +446,4 @@ public static int _AtExit() return Runtime.AtExit(); } } -} \ No newline at end of file +} diff --git a/src/runtime/modulepropertyobject.cs b/src/runtime/modulepropertyobject.cs index 1f67f89ec..7f7841890 100644 --- a/src/runtime/modulepropertyobject.cs +++ b/src/runtime/modulepropertyobject.cs @@ -15,4 +15,4 @@ public ModulePropertyObject(PropertyInfo md) : base() throw new NotImplementedException("ModulePropertyObject"); } } -} \ No newline at end of file +} diff --git a/src/runtime/monosupport.cs b/src/runtime/monosupport.cs index 52c2921da..7ddf9aa1a 100644 --- a/src/runtime/monosupport.cs +++ b/src/runtime/monosupport.cs @@ -6,12 +6,9 @@ namespace Python.Runtime { - // The Utf32Marshaler was written Jonathan Pryor and has been placed - // in the PUBLIC DOMAIN. public class Utf32Marshaler : ICustomMarshaler { - private static Utf32Marshaler instance = new - Utf32Marshaler(); + private static Utf32Marshaler instance = new Utf32Marshaler(); public static ICustomMarshaler GetInstance(string s) { @@ -37,17 +34,13 @@ public IntPtr MarshalManagedToNative(object obj) string s = obj as string; if (s == null) return IntPtr.Zero; - return UnixMarshal.StringToHeap(s, - Encoding.UTF32); + return UnixMarshal.StringToHeap(s, Encoding.UTF32); } - public object MarshalNativeToManaged(IntPtr - pNativeData) + public object MarshalNativeToManaged(IntPtr pNativeData) { - return UnixMarshal.PtrToString(pNativeData, - Encoding.UTF32); + return UnixMarshal.PtrToString(pNativeData, Encoding.UTF32); } } } - #endif diff --git a/src/runtime/nativecall.cs b/src/runtime/nativecall.cs index a37729ab2..7eb8b87c8 100644 --- a/src/runtime/nativecall.cs +++ b/src/runtime/nativecall.cs @@ -128,14 +128,12 @@ public static void Void_Call_1(IntPtr fp, IntPtr a1) Impl.Void_Call_1(fp, a1); } - public static IntPtr Call_3(IntPtr fp, IntPtr a1, IntPtr a2, - IntPtr a3) + public static IntPtr Call_3(IntPtr fp, IntPtr a1, IntPtr a2, IntPtr a3) { return Impl.Call_3(fp, a1, a2, a3); } - public static int Int_Call_3(IntPtr fp, IntPtr a1, IntPtr a2, - IntPtr a3) + public static int Int_Call_3(IntPtr fp, IntPtr a1, IntPtr a2, IntPtr a3) { return Impl.Int_Call_3(fp, a1, a2, a3); } @@ -155,4 +153,4 @@ public interface INativeCall IntPtr Call_3(IntPtr funcPtr, IntPtr a1, IntPtr a2, IntPtr a3); } -} \ No newline at end of file +} diff --git a/src/runtime/overload.cs b/src/runtime/overload.cs index 2a339df66..e7d548a23 100644 --- a/src/runtime/overload.cs +++ b/src/runtime/overload.cs @@ -74,4 +74,4 @@ public static IntPtr tp_repr(IntPtr op) ExtensionType.FinalizeObject(self); } } -} \ No newline at end of file +} diff --git a/src/runtime/propertyobject.cs b/src/runtime/propertyobject.cs index 5bbf94d1a..bfb70899f 100644 --- a/src/runtime/propertyobject.cs +++ b/src/runtime/propertyobject.cs @@ -47,9 +47,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) if (!(getter.IsStatic)) { Exceptions.SetError(Exceptions.TypeError, - "instance property must be accessed through " + - "a class instance" - ); + "instance property must be accessed through " + "a class instance"); return IntPtr.Zero; } @@ -112,8 +110,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) } - if (!Converter.ToManaged(val, self.info.PropertyType, out newval, - true)) + if (!Converter.ToManaged(val, self.info.PropertyType, out newval, true)) { return -1; } @@ -124,9 +121,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { if (!(is_static)) { - Exceptions.RaiseTypeError( - "instance property must be set on an instance" - ); + Exceptions.RaiseTypeError("instance property must be set on an instance"); return -1; } } @@ -172,4 +167,4 @@ public static IntPtr tp_repr(IntPtr ob) return Runtime.PyString_FromStringAndSize(s, s.Length); } } -} \ No newline at end of file +} diff --git a/src/runtime/pyansistring.cs b/src/runtime/pyansistring.cs index 1a2cb7955..71dec3362 100644 --- a/src/runtime/pyansistring.cs +++ b/src/runtime/pyansistring.cs @@ -27,8 +27,7 @@ public PyAnsiString(IntPtr ptr) : base(ptr) /// An ArgumentException will be thrown if the given object is not /// a Python string object. /// - public PyAnsiString(PyObject o) - : base() + public PyAnsiString(PyObject o) : base() { if (!IsStringType(o)) { @@ -46,8 +45,7 @@ public PyAnsiString(PyObject o) /// /// Creates a Python string from a managed string. /// - public PyAnsiString(string s) - : base() + public PyAnsiString(string s) : base() { obj = Runtime.PyString_FromStringAndSize(s, s.Length); if (obj == IntPtr.Zero) @@ -69,4 +67,4 @@ public static bool IsStringType(PyObject value) return Runtime.PyString_Check(value.obj); } } -} \ No newline at end of file +} diff --git a/src/runtime/pydict.cs b/src/runtime/pydict.cs index fc8b98377..0d1449862 100644 --- a/src/runtime/pydict.cs +++ b/src/runtime/pydict.cs @@ -201,4 +201,4 @@ public void Clear() Runtime.PyDict_Clear(obj); } } -} \ No newline at end of file +} diff --git a/src/runtime/pyfloat.cs b/src/runtime/pyfloat.cs index 27a13f184..c8a363ea8 100644 --- a/src/runtime/pyfloat.cs +++ b/src/runtime/pyfloat.cs @@ -113,4 +113,4 @@ public static PyFloat AsFloat(PyObject value) return new PyFloat(op); } } -} \ No newline at end of file +} diff --git a/src/runtime/pyint.cs b/src/runtime/pyint.cs index 935f54a8b..847ad2ebf 100644 --- a/src/runtime/pyint.cs +++ b/src/runtime/pyint.cs @@ -252,4 +252,4 @@ public long ToInt64() return System.Convert.ToInt64(this.ToInt32()); } } -} \ No newline at end of file +} diff --git a/src/runtime/pyiter.cs b/src/runtime/pyiter.cs index 5d11fb4d4..5310c4d8b 100644 --- a/src/runtime/pyiter.cs +++ b/src/runtime/pyiter.cs @@ -79,4 +79,4 @@ public object Current #endregion } -} \ No newline at end of file +} diff --git a/src/runtime/pylist.cs b/src/runtime/pylist.cs index bdbc806fd..681e864a4 100644 --- a/src/runtime/pylist.cs +++ b/src/runtime/pylist.cs @@ -182,4 +182,4 @@ public void Sort() } } } -} \ No newline at end of file +} diff --git a/src/runtime/pylong.cs b/src/runtime/pylong.cs index 63c613402..8e17d2a59 100644 --- a/src/runtime/pylong.cs +++ b/src/runtime/pylong.cs @@ -287,4 +287,4 @@ public long ToInt64() return Runtime.PyLong_AsLongLong(obj); } } -} \ No newline at end of file +} diff --git a/src/runtime/pynumber.cs b/src/runtime/pynumber.cs index c8da3e7a6..e6805d708 100644 --- a/src/runtime/pynumber.cs +++ b/src/runtime/pynumber.cs @@ -33,4 +33,4 @@ public static bool IsNumberType(PyObject value) // TODO: add all of the PyNumber_XXX methods. } -} \ No newline at end of file +} diff --git a/src/runtime/pyobject.cs b/src/runtime/pyobject.cs index 781f6313d..19a2f178b 100644 --- a/src/runtime/pyobject.cs +++ b/src/runtime/pyobject.cs @@ -126,7 +126,7 @@ protected virtual void Dispose(bool disposing) disposed = true; } } - + public void Dispose() { Dispose(true); @@ -1189,4 +1189,4 @@ public override bool TryUnaryOperation(UnaryOperationBinder binder, out Object r return true; } } -} \ No newline at end of file +} diff --git a/src/runtime/pysequence.cs b/src/runtime/pysequence.cs index d32921901..a5f6f3dad 100644 --- a/src/runtime/pysequence.cs +++ b/src/runtime/pysequence.cs @@ -160,4 +160,4 @@ public PyObject Repeat(int count) return new PyObject(op); } } -} \ No newline at end of file +} diff --git a/src/runtime/pystring.cs b/src/runtime/pystring.cs index 46b8fd657..a3d198a2c 100644 --- a/src/runtime/pystring.cs +++ b/src/runtime/pystring.cs @@ -72,4 +72,4 @@ public static bool IsStringType(PyObject value) return Runtime.PyString_Check(value.obj); } } -} \ No newline at end of file +} diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 754aaf2cd..3f0022467 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -217,11 +217,10 @@ public static void Initialize(IEnumerable args) //==================================================================== #if PYTHON3 public static IntPtr InitExt() - { #elif PYTHON2 public static void InitExt() - { #endif + { try { Initialize(); diff --git a/src/runtime/pythonexception.cs b/src/runtime/pythonexception.cs index 2999432c1..124636457 100644 --- a/src/runtime/pythonexception.cs +++ b/src/runtime/pythonexception.cs @@ -176,4 +176,4 @@ public static bool Matches(IntPtr ob) return Runtime.PyErr_ExceptionMatches(ob) != 0; } } -} \ No newline at end of file +} diff --git a/src/runtime/pytuple.cs b/src/runtime/pytuple.cs index 123ad4359..97f4c5bbc 100644 --- a/src/runtime/pytuple.cs +++ b/src/runtime/pytuple.cs @@ -115,4 +115,4 @@ public static PyTuple AsTuple(PyObject value) return new PyTuple(op); } } -} \ No newline at end of file +} diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 9b5c4ffb5..f79daa970 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -14,15 +14,18 @@ namespace Python.Runtime static class NativeMethods { #if MONO_LINUX || MONO_OSX - static public IntPtr LoadLibrary(string fileName) { + static public IntPtr LoadLibrary(string fileName) + { return dlopen(fileName, RTLD_NOW | RTLD_SHARED); } - static public void FreeLibrary(IntPtr handle) { + static public void FreeLibrary(IntPtr handle) + { dlclose(handle); } - static public IntPtr GetProcAddress(IntPtr dllHandle, string name) { + static public IntPtr GetProcAddress(IntPtr dllHandle, string name) + { // look in the exe if dllHandle is NULL if (IntPtr.Zero == dllHandle) dllHandle = RTLD_DEFAULT; @@ -31,7 +34,8 @@ static public IntPtr GetProcAddress(IntPtr dllHandle, string name) { dlerror(); var res = dlsym(dllHandle, name); var errPtr = dlerror(); - if (errPtr != IntPtr.Zero) { + if (errPtr != IntPtr.Zero) + { throw new Exception("dlsym: " + Marshal.PtrToStringAnsi(errPtr)); } return res; @@ -72,6 +76,7 @@ static public IntPtr GetProcAddress(IntPtr dllHandle, string name) { #endif #else // Windows + [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); @@ -113,8 +118,7 @@ public class Runtime #elif PYTHON36 public const string pyversion = "3.6"; public const int pyversionnumber = 36; -#elif PYTHON37 - // TODO: Add interop37 after Python3.7 is released +#elif PYTHON37 // TODO: Add interop37 after Python3.7 is released public const string pyversion = "3.7"; public const int pyversionnumber = 37; #else @@ -270,8 +274,8 @@ internal static void Initialize() Runtime.XDecref(op); #if PYTHON3 - PyClassType = IntPtr.Zero; - PyInstanceType = IntPtr.Zero; + PyClassType = IntPtr.Zero; + PyInstanceType = IntPtr.Zero; #elif PYTHON2 IntPtr s = Runtime.PyString_FromString("_temp"); IntPtr d = Runtime.PyDict_New(); @@ -291,15 +295,17 @@ internal static void Initialize() Error = new IntPtr(-1); #if PYTHON3 - IntPtr dll = IntPtr.Zero; - if ("__Internal" != Runtime.dll) { - NativeMethods.LoadLibrary(Runtime.dll); - } - _PyObject_NextNotImplemented = NativeMethods.GetProcAddress(dll, "_PyObject_NextNotImplemented"); + IntPtr dll = IntPtr.Zero; + if ("__Internal" != Runtime.dll) + { + NativeMethods.LoadLibrary(Runtime.dll); + } + _PyObject_NextNotImplemented = NativeMethods.GetProcAddress(dll, "_PyObject_NextNotImplemented"); #if !(MONO_LINUX || MONO_OSX) - if (IntPtr.Zero != dll) { - NativeMethods.FreeLibrary(dll); - } + if (IntPtr.Zero != dll) + { + NativeMethods.FreeLibrary(dll); + } #endif #endif @@ -500,9 +506,9 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) internal unsafe static void XIncref(IntPtr op) { #if Py_DEBUG - // according to Python doc, Py_IncRef() is Py_XINCREF() - Py_IncRef(op); - return; + // according to Python doc, Py_IncRef() is Py_XINCREF() + Py_IncRef(op); + return; #else void* p = (void*)op; if ((void*)0 != p) @@ -522,10 +528,10 @@ internal unsafe static void XIncref(IntPtr op) internal static unsafe void XDecref(IntPtr op) { #if Py_DEBUG - // Py_DecRef calls Python's Py_DECREF - // according to Python doc, Py_DecRef() is Py_XDECREF() - Py_DecRef(op); - return; + // Py_DecRef calls Python's Py_DECREF + // according to Python doc, Py_DecRef() is Py_XDECREF() + Py_DecRef(op); + return; #else void* p = (void*)op; if ((void*)0 != p) @@ -577,17 +583,17 @@ internal unsafe static long Refcount(IntPtr op) } #if Py_DEBUG - // Py_IncRef and Py_DecRef are taking care of the extra payload - // in Py_DEBUG builds of Python like _Py_RefTotal - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - private unsafe static extern void - Py_IncRef(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - private unsafe static extern void - Py_DecRef(IntPtr ob); + // Py_IncRef and Py_DecRef are taking care of the extra payload + // in Py_DEBUG builds of Python like _Py_RefTotal + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + private unsafe static extern void + Py_IncRef(IntPtr ob); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + private unsafe static extern void + Py_DecRef(IntPtr ob); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, @@ -663,10 +669,10 @@ internal unsafe static extern IntPtr PyGILState_GetThisThreadState(); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - public unsafe static extern int - Py_Main(int argc, [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)] string[] argv); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + public unsafe static extern int + Py_Main(int argc, [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] argv); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -731,38 +737,38 @@ internal unsafe static extern IntPtr #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - [return: MarshalAs(UnmanagedType.LPWStr)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string - Py_GetProgramName(); + Py_GetProgramName(); - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern void - Py_SetProgramName([MarshalAsAttribute(UnmanagedType.LPWStr)]string name); + Py_SetProgramName([MarshalAsAttribute(UnmanagedType.LPWStr)] string name); - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - [return: MarshalAs(UnmanagedType.LPWStr)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string - Py_GetPythonHome(); + Py_GetPythonHome(); - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern void - Py_SetPythonHome([MarshalAsAttribute(UnmanagedType.LPWStr)]string home); + Py_SetPythonHome([MarshalAsAttribute(UnmanagedType.LPWStr)] string home); - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - [return: MarshalAs(UnmanagedType.LPWStr)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string - Py_GetPath(); + Py_GetPath(); - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern void - Py_SetPath([MarshalAsAttribute(UnmanagedType.LPWStr)]string home); + Py_SetPath([MarshalAsAttribute(UnmanagedType.LPWStr)] string home); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -888,7 +894,7 @@ internal unsafe static IntPtr return IntPtr.Zero; } #if Py_DEBUG - int n = 3; + int n = 3; #else int n = 1; #endif @@ -982,34 +988,35 @@ internal unsafe static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - internal unsafe static extern int - PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); - - internal static int PyObject_Compare(IntPtr value1, IntPtr value2) { - int res; - res = PyObject_RichCompareBool(value1, value2, Py_LT); - if (-1 == res) - return -1; - else if (1 == res) - return -1; - - res = PyObject_RichCompareBool(value1, value2, Py_EQ); - if (-1 == res) - return -1; - else if (1 == res) - return 0; + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern int + PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); - res = PyObject_RichCompareBool(value1, value2, Py_GT); - if (-1 == res) + internal static int PyObject_Compare(IntPtr value1, IntPtr value2) + { + int res; + res = PyObject_RichCompareBool(value1, value2, Py_LT); + if (-1 == res) + return -1; + else if (1 == res) + return -1; + + res = PyObject_RichCompareBool(value1, value2, Py_EQ); + if (-1 == res) + return -1; + else if (1 == res) + return 0; + + res = PyObject_RichCompareBool(value1, value2, Py_GT); + if (-1 == res) + return -1; + else if (1 == res) + return 1; + + Exceptions.SetError(Exceptions.SystemError, "Error comparing objects"); return -1; - else if (1 == res) - return 1; - - Exceptions.SetError(Exceptions.SystemError, "Error comparing objects"); - return -1; - } + } #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -1064,11 +1071,11 @@ internal unsafe static extern IntPtr PyObject_Str(IntPtr pointer); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint="PyObject_Str", - ExactSpelling = true, CharSet = CharSet.Ansi)] - internal unsafe static extern IntPtr - PyObject_Unicode(IntPtr pointer); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyObject_Str", + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern IntPtr + PyObject_Unicode(IntPtr pointer); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -1087,11 +1094,11 @@ internal unsafe static extern IntPtr //==================================================================== #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint = "PyNumber_Long", - ExactSpelling=true, CharSet=CharSet.Ansi)] - internal unsafe static extern IntPtr - PyNumber_Int(IntPtr ob); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyNumber_Long", + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern IntPtr + PyNumber_Int(IntPtr ob); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, @@ -1140,29 +1147,29 @@ internal static IntPtr PyInt_FromInt64(long value) } #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyLong_FromLong", - ExactSpelling = true, CharSet = CharSet.Ansi)] - private unsafe static extern IntPtr - PyInt_FromLong(IntPtr value); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint = "PyLong_AsLong", - ExactSpelling=true, CharSet=CharSet.Ansi)] - internal unsafe static extern int - PyInt_AsLong(IntPtr value); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint = "PyLong_FromString", - ExactSpelling=true, CharSet=CharSet.Ansi)] - internal unsafe static extern IntPtr - PyInt_FromString(string value, IntPtr end, int radix); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint = "PyLong_GetMax", - ExactSpelling=true, CharSet=CharSet.Ansi)] - internal unsafe static extern int - PyInt_GetMax(); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyLong_FromLong", + ExactSpelling = true, CharSet = CharSet.Ansi)] + private unsafe static extern IntPtr + PyInt_FromLong(IntPtr value); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyLong_AsLong", + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern int + PyInt_AsLong(IntPtr value); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyLong_FromString", + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern IntPtr + PyInt_FromString(string value, IntPtr end, int radix); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyLong_GetMax", + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern int + PyInt_GetMax(); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, @@ -1488,40 +1495,43 @@ internal static IntPtr PyString_FromString(string value) } #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - internal unsafe static extern IntPtr - PyBytes_FromString(string op); - - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] - internal unsafe static extern int - PyBytes_Size(IntPtr op); - - internal static IntPtr PyBytes_AS_STRING(IntPtr ob) { - return ob + BytesOffset.ob_sval; - } + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern IntPtr + PyBytes_FromString(string op); - internal static IntPtr PyString_FromStringAndSize(string value, int length) - { - // copy the string into an unmanaged UTF-8 buffer - int len = Encoding.UTF8.GetByteCount(value); - byte[] buffer = new byte[len + 1]; - Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, 0); - IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length); - try { - Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length); - return PyUnicode_FromStringAndSize(nativeUtf8, length); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern int + PyBytes_Size(IntPtr op); + + internal static IntPtr PyBytes_AS_STRING(IntPtr ob) + { + return ob + BytesOffset.ob_sval; } - finally { - Marshal.FreeHGlobal(nativeUtf8); + + internal static IntPtr PyString_FromStringAndSize(string value, int length) + { + // copy the string into an unmanaged UTF-8 buffer + int len = Encoding.UTF8.GetByteCount(value); + byte[] buffer = new byte[len + 1]; + Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, 0); + IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length); + try + { + Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length); + return PyUnicode_FromStringAndSize(nativeUtf8, length); + } + finally + { + Marshal.FreeHGlobal(nativeUtf8); + } } - } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromStringAndSize(IntPtr value, int size); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromStringAndSize(IntPtr value, int size); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -1546,133 +1556,135 @@ internal static bool PyUnicode_Check(IntPtr ob) } #if UCS2 && PYTHON3 - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromObject(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint="PyUnicode_FromKindAndData", - ExactSpelling=true, - CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromKindAndString(int kind, string s, int size); - - internal static IntPtr PyUnicode_FromUnicode(string s, int size) { - return PyUnicode_FromKindAndString(2, s, size); - } + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromObject(IntPtr ob); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern int - PyUnicode_GetSize(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern char * - PyUnicode_AsUnicode(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicode_AsUnicode", - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_AS_UNICODE(IntPtr op); - - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromOrdinal(int c); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicode_FromKindAndData", + ExactSpelling = true, + CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromKindAndString(int kind, string s, int size); + + internal static IntPtr PyUnicode_FromUnicode(string s, int size) + { + return PyUnicode_FromKindAndString(2, s, size); + } + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern int + PyUnicode_GetSize(IntPtr ob); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern char* + PyUnicode_AsUnicode(IntPtr ob); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicode_AsUnicode", + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_AS_UNICODE(IntPtr op); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromOrdinal(int c); #elif UCS2 && PYTHON2 - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint="PyUnicodeUCS2_FromObject", - ExactSpelling=true, CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromObject(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint="PyUnicodeUCS2_FromEncodedObject", - ExactSpelling=true, CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint="PyUnicodeUCS2_FromUnicode", - ExactSpelling=true, CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromUnicode(string s, int size); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint="PyUnicodeUCS2_GetSize", - ExactSpelling=true, CharSet=CharSet.Ansi)] - internal unsafe static extern int - PyUnicode_GetSize(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint="PyUnicodeUCS2_AsUnicode", - ExactSpelling=true)] - internal unsafe static extern char * - PyUnicode_AsUnicode(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint="PyUnicodeUCS2_AsUnicode", - ExactSpelling=true, CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_AS_UNICODE(IntPtr op); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - EntryPoint="PyUnicodeUCS2_FromOrdinal", - ExactSpelling=true, CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromOrdinal(int c); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicodeUCS2_FromObject", + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromObject(IntPtr ob); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicodeUCS2_FromEncodedObject", + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicodeUCS2_FromUnicode", + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromUnicode(string s, int size); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicodeUCS2_GetSize", + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern int + PyUnicode_GetSize(IntPtr ob); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicodeUCS2_AsUnicode", + ExactSpelling = true)] + internal unsafe static extern char* + PyUnicode_AsUnicode(IntPtr ob); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicodeUCS2_AsUnicode", + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_AS_UNICODE(IntPtr op); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicodeUCS2_FromOrdinal", + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromObject(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicode_FromKindAndData", - ExactSpelling = true)] - internal unsafe static extern IntPtr - PyUnicode_FromKindAndString(int kind, - [MarshalAs (UnmanagedType.CustomMarshaler, - MarshalTypeRef=typeof(Utf32Marshaler))] string s, - int size); - - internal static IntPtr PyUnicode_FromUnicode(string s, int size) { - return PyUnicode_FromKindAndString(4, s, size); - } + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromObject(IntPtr ob); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicode_FromKindAndData", + ExactSpelling = true)] + internal unsafe static extern IntPtr + PyUnicode_FromKindAndString(int kind, + [MarshalAs(UnmanagedType.CustomMarshaler, + MarshalTypeRef = typeof(Utf32Marshaler))] string s, + int size); + + internal static IntPtr PyUnicode_FromUnicode(string s, int size) + { + return PyUnicode_FromKindAndString(4, s, size); + } + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern int + PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] - internal unsafe static extern int - PyUnicode_GetSize(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true)] - internal unsafe static extern IntPtr - PyUnicode_AsUnicode(IntPtr ob); - - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicode_AsUnicode", - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_AS_UNICODE(IntPtr op); - - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_FromOrdinal(int c); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true)] + internal unsafe static extern IntPtr + PyUnicode_AsUnicode(IntPtr ob); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + EntryPoint = "PyUnicode_AsUnicode", + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_AS_UNICODE(IntPtr op); + + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Unicode)] + internal unsafe static extern IntPtr + PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS4_FromObject", @@ -1734,7 +1746,7 @@ internal unsafe static string GetManagedString(IntPtr op) return Marshal.PtrToStringAnsi( PyString_AS_STRING(op), Runtime.PyString_Size(op) - ); + ); } #endif @@ -1743,7 +1755,7 @@ internal unsafe static string GetManagedString(IntPtr op) #if UCS4 IntPtr p = Runtime.PyUnicode_AsUnicode(op); int length = Runtime.PyUnicode_GetSize(op); - int size = length*4; + int size = length * 4; byte[] buffer = new byte[size]; Marshal.Copy(p, buffer, 0, size); return Encoding.UTF32.GetString(buffer, 0, size); @@ -1957,13 +1969,13 @@ internal unsafe static extern int internal unsafe static extern bool PyIter_Check(IntPtr pointer); #elif PYTHON3 - internal static bool - PyIter_Check(IntPtr pointer) - { - IntPtr ob_type = (IntPtr)Marshal.PtrToStructure(pointer + ObjectOffset.ob_type, typeof(IntPtr)); - IntPtr tp_iternext = ob_type + TypeOffset.tp_iternext; - return tp_iternext != null && tp_iternext != _PyObject_NextNotImplemented; - } + internal static bool + PyIter_Check(IntPtr pointer) + { + IntPtr ob_type = (IntPtr)Marshal.PtrToStructure(pointer + ObjectOffset.ob_type, typeof(IntPtr)); + IntPtr tp_iternext = ob_type + TypeOffset.tp_iternext; + return tp_iternext != null && tp_iternext != _PyObject_NextNotImplemented; + } #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, @@ -1996,10 +2008,10 @@ internal unsafe static extern string PyModule_GetFilename(IntPtr module); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl, - ExactSpelling=true, CharSet=CharSet.Ansi)] - internal unsafe static extern IntPtr - PyModule_Create2(IntPtr module, int apiver); + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, + ExactSpelling = true, CharSet = CharSet.Ansi)] + internal unsafe static extern IntPtr + PyModule_Create2(IntPtr module, int apiver); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, @@ -2033,10 +2045,9 @@ internal unsafe static extern IntPtr internal unsafe static extern void PySys_SetArgvEx( int argc, - [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] - string[] argv, + [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] argv, int updatepath - ); + ); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -2045,7 +2056,7 @@ internal unsafe static extern void int argc, string[] argv, int updatepath - ); + ); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, diff --git a/src/runtime/typemanager.cs b/src/runtime/typemanager.cs index 40e60336d..d6c474f8d 100644 --- a/src/runtime/typemanager.cs +++ b/src/runtime/typemanager.cs @@ -268,10 +268,10 @@ internal static IntPtr CreateSubType(IntPtr py_name, IntPtr py_base_type, IntPtr internal static IntPtr WriteMethodDef(IntPtr mdef, IntPtr name, IntPtr func, int flags, IntPtr doc) { Marshal.WriteIntPtr(mdef, name); - Marshal.WriteIntPtr(mdef, (1*IntPtr.Size), func); - Marshal.WriteInt32(mdef, (2*IntPtr.Size), flags); - Marshal.WriteIntPtr(mdef, (3*IntPtr.Size), doc); - return mdef + 4*IntPtr.Size; + Marshal.WriteIntPtr(mdef, (1 * IntPtr.Size), func); + Marshal.WriteInt32(mdef, (2 * IntPtr.Size), flags); + Marshal.WriteIntPtr(mdef, (3 * IntPtr.Size), doc); + return mdef + 4 * IntPtr.Size; } internal static IntPtr WriteMethodDef(IntPtr mdef, string name, IntPtr func, int flags = 0x0001, @@ -325,19 +325,19 @@ internal static IntPtr CreateMetaType(Type impl) // We need space for 3 PyMethodDef structs, each of them // 4 int-ptrs in size. - IntPtr mdef = Runtime.PyMem_Malloc(3*(4*IntPtr.Size)); + IntPtr mdef = Runtime.PyMem_Malloc(3 * (4 * IntPtr.Size)); IntPtr mdefStart = mdef; mdef = WriteMethodDef( mdef, "__instancecheck__", Interop.GetThunk(typeof(MetaType).GetMethod("__instancecheck__"), "BinaryFunc") - ); + ); mdef = WriteMethodDef( mdef, "__subclasscheck__", Interop.GetThunk(typeof(MetaType).GetMethod("__subclasscheck__"), "BinaryFunc") - ); + ); mdef = WriteMethodDefSentinel(mdef); @@ -355,8 +355,7 @@ internal static IntPtr CreateMetaType(Type impl) } - internal static IntPtr BasicSubType(string name, IntPtr base_, - Type impl) + internal static IntPtr BasicSubType(string name, IntPtr base_, Type impl) { // Utility to create a subtype of a std Python type, but with // a managed type able to override implementation @@ -408,9 +407,9 @@ internal static IntPtr AllocateTypeObject(string name) // the Python version of the type name - otherwise we'd have to // allocate the tp_name and would have no way to free it. #if PYTHON3 - // For python3 we leak two objects. One for the ascii representation - // required for tp_name, and another for the unicode representation - // for ht_name. + // For python3 we leak two objects. One for the ASCII representation + // required for tp_name, and another for the Unicode representation + // for ht_name. IntPtr temp = Runtime.PyBytes_FromString(name); IntPtr raw = Runtime.PyBytes_AS_STRING(temp); temp = Runtime.PyUnicode_FromString(name); @@ -438,12 +437,10 @@ internal static IntPtr AllocateTypeObject(string name) #if PYTHON3 temp = new IntPtr(ptr + TypeOffset.bf_getbuffer); - Marshal.WriteIntPtr(type, TypeOffset.tp_as_buffer, temp); #elif PYTHON2 temp = new IntPtr(ptr + TypeOffset.bf_getreadbuffer); - Marshal.WriteIntPtr(type, TypeOffset.tp_as_buffer, temp); #endif - + Marshal.WriteIntPtr(type, TypeOffset.tp_as_buffer, temp); return type; } @@ -471,7 +468,7 @@ internal static void InitializeSlots(IntPtr type, Type impl) name.StartsWith("sq_") || name.StartsWith("mp_") || name.StartsWith("bf_") - )) + )) { continue; } diff --git a/src/runtime/typemethod.cs b/src/runtime/typemethod.cs index 4e46da2da..0c60301a0 100644 --- a/src/runtime/typemethod.cs +++ b/src/runtime/typemethod.cs @@ -35,8 +35,7 @@ public override IntPtr Invoke(IntPtr ob, IntPtr args, IntPtr kw) { inst = GetManagedObject(ob); } - return (IntPtr)mi.Invoke(inst, BindingFlags.Default, null, arglist, - null); + return (IntPtr)mi.Invoke(inst, BindingFlags.Default, null, arglist, null); } catch (Exception e) { @@ -45,4 +44,4 @@ public override IntPtr Invoke(IntPtr ob, IntPtr args, IntPtr kw) } } } -} \ No newline at end of file +} diff --git a/src/testing/generictest.cs b/src/testing/generictest.cs index 848ee5cea..1e9c71ac6 100644 --- a/src/testing/generictest.cs +++ b/src/testing/generictest.cs @@ -25,13 +25,11 @@ public GenericTypeDefinition(T arg1, U arg2) } } - public class DerivedFromOpenGeneric : - GenericTypeDefinition + public class DerivedFromOpenGeneric : GenericTypeDefinition { public W value3; - public DerivedFromOpenGeneric(int arg1, V arg2, W arg3) : - base(arg1, arg2) + public DerivedFromOpenGeneric(int arg1, V arg2, W arg3) : base(arg1, arg2) { value3 = arg3; } diff --git a/src/testing/indexertest.cs b/src/testing/indexertest.cs index 74ba69755..ae39eb2b1 100644 --- a/src/testing/indexertest.cs +++ b/src/testing/indexertest.cs @@ -375,8 +375,7 @@ public MultiTypeIndexerTest() : base() { get { - string key = i1.ToString() + i2.ToString() + - i3.GetHashCode().ToString(); + string key = i1.ToString() + i2.ToString() + i3.GetHashCode().ToString(); object value = t[key]; if (value != null) { @@ -386,8 +385,7 @@ public MultiTypeIndexerTest() : base() } set { - string key = i1.ToString() + i2.ToString() + - i3.GetHashCode().ToString(); + string key = i1.ToString() + i2.ToString() + i3.GetHashCode().ToString(); t[key] = value; } } diff --git a/src/testing/methodtest.cs b/src/testing/methodtest.cs index 567dd9227..7634c4839 100644 --- a/src/testing/methodtest.cs +++ b/src/testing/methodtest.cs @@ -101,8 +101,7 @@ public static int[] TestOneArgWithParams(string s, params int[] args) return args; } - public static int[] TestTwoArgWithParams(string s, string x, - params int[] args) + public static int[] TestTwoArgWithParams(string s, string x, params int[] args) { return args; } @@ -383,218 +382,182 @@ public static ISayHello1[] Overloaded(ISayHello1[] v) return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper Overloaded( - GenericWrapper v) + public static GenericWrapper Overloaded(GenericWrapper v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } - public static GenericWrapper[] Overloaded( - GenericWrapper[] v) + public static GenericWrapper[] Overloaded(GenericWrapper[] v) { return v; } From 8a50e135ddfdf4eb5d726b0af406baa5551dc062 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 22:03:51 -0700 Subject: [PATCH 057/245] Update CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbf9f4c9a..b547712fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. ### Added - Code Coverage (#345) +- Add `pysetargv` (#347) ### Changed From a12b2b2701462964090ecc4fe9ef1ba0f931e50b Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 12:10:01 -0700 Subject: [PATCH 058/245] Change applicable comments to xml-docs --- src/runtime/arrayobject.cs | 28 ++--- src/runtime/assemblymanager.cs | 188 +++++++++++++--------------- src/runtime/classbase.cs | 60 ++++----- src/runtime/classderived.cs | 15 ++- src/runtime/classmanager.cs | 20 ++- src/runtime/classobject.cs | 52 ++++---- src/runtime/codegenerator.cs | 14 +-- src/runtime/constructorbinder.cs | 32 +++-- src/runtime/constructorbinding.cs | 34 +++-- src/runtime/converter.cs | 69 +++++----- src/runtime/delegatemanager.cs | 31 +++-- src/runtime/delegateobject.cs | 37 +++--- src/runtime/eventbinding.cs | 42 +++---- src/runtime/eventobject.cs | 59 ++++----- src/runtime/exceptions.cs | 21 ++-- src/runtime/extensiontype.cs | 37 +++--- src/runtime/fieldobject.cs | 36 +++--- src/runtime/generictype.cs | 14 +-- src/runtime/genericutil.cs | 28 ++--- src/runtime/importhook.cs | 34 +++-- src/runtime/indexer.cs | 9 +- src/runtime/interfaceobject.cs | 7 +- src/runtime/interop.cs | 11 +- src/runtime/iterator.cs | 16 ++- src/runtime/managedtype.cs | 18 ++- src/runtime/metatype.cs | 72 +++++------ src/runtime/methodbinder.cs | 96 +++++++------- src/runtime/methodbinding.cs | 53 ++++---- src/runtime/methodobject.cs | 76 ++++++----- src/runtime/modulefunctionobject.cs | 14 +-- src/runtime/moduleobject.cs | 60 ++++----- src/runtime/overload.cs | 30 ++--- src/runtime/propertyobject.cs | 36 +++--- src/runtime/pyansistring.cs | 4 - src/runtime/pydict.cs | 12 -- src/runtime/pyfloat.cs | 7 -- src/runtime/pyint.cs | 17 --- src/runtime/pyiter.cs | 2 - src/runtime/pylist.cs | 10 -- src/runtime/pylong.cs | 18 --- src/runtime/pynumber.cs | 1 - src/runtime/pysequence.cs | 8 -- src/runtime/pystring.cs | 4 - src/runtime/pythonengine.cs | 10 +- src/runtime/pythonexception.cs | 7 -- src/runtime/pytuple.cs | 6 - src/runtime/runtime.cs | 124 +++++++++--------- src/runtime/typemanager.cs | 86 ++++++------- src/runtime/typemethod.cs | 7 +- 49 files changed, 708 insertions(+), 964 deletions(-) diff --git a/src/runtime/arrayobject.cs b/src/runtime/arrayobject.cs index eaff49214..6096706dd 100644 --- a/src/runtime/arrayobject.cs +++ b/src/runtime/arrayobject.cs @@ -38,10 +38,9 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) } - //==================================================================== - // Implements __getitem__ for array types. - //==================================================================== - + /// + /// Implements __getitem__ for array types. + /// public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) { CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob); @@ -131,10 +130,9 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) } - //==================================================================== - // Implements __setitem__ for array types. - //==================================================================== - + /// + /// Implements __setitem__ for array types. + /// public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) { CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob); @@ -226,10 +224,9 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) } - //==================================================================== - // Implements __contains__ for array types. - //==================================================================== - + /// + /// Implements __contains__ for array types. + /// public static int sq_contains(IntPtr ob, IntPtr v) { CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob); @@ -251,10 +248,9 @@ public static int sq_contains(IntPtr ob, IntPtr v) } - //==================================================================== - // Implements __len__ for array types. - //==================================================================== - + /// + /// Implements __len__ for array types. + /// public static int mp_length(IntPtr ob) { CLRObject self = (CLRObject)ManagedType.GetManagedObject(ob); diff --git a/src/runtime/assemblymanager.cs b/src/runtime/assemblymanager.cs index f263728bb..b98455ec3 100644 --- a/src/runtime/assemblymanager.cs +++ b/src/runtime/assemblymanager.cs @@ -31,12 +31,11 @@ private AssemblyManager() { } - //=================================================================== - // Initialization performed on startup of the Python runtime. Here we - // scan all of the currently loaded assemblies to determine exported - // names, and register to be notified of new assembly loads. - //=================================================================== - + /// + /// Initialization performed on startup of the Python runtime. Here we + /// scan all of the currently loaded assemblies to determine exported + /// names, and register to be notified of new assembly loads. + /// internal static void Initialize() { namespaces = new ConcurrentDictionary>(); @@ -69,10 +68,9 @@ internal static void Initialize() } - //=================================================================== - // Cleanup resources upon shutdown of the Python runtime. - //=================================================================== - + /// + /// Cleanup resources upon shutdown of the Python runtime. + /// internal static void Shutdown() { AppDomain domain = AppDomain.CurrentDomain; @@ -81,14 +79,13 @@ internal static void Shutdown() } - //=================================================================== - // Event handler for assembly load events. At the time the Python - // runtime loads, we scan the app domain to map the assemblies that - // are loaded at the time. We also have to register this event handler - // so that we can know about assemblies that get loaded after the - // Python runtime is initialized. - //=================================================================== - + /// + /// Event handler for assembly load events. At the time the Python + /// runtime loads, we scan the app domain to map the assemblies that + /// are loaded at the time. We also have to register this event handler + /// so that we can know about assemblies that get loaded after the + /// Python runtime is initialized. + /// static void AssemblyLoadHandler(Object ob, AssemblyLoadEventArgs args) { Assembly assembly = args.LoadedAssembly; @@ -97,14 +94,13 @@ static void AssemblyLoadHandler(Object ob, AssemblyLoadEventArgs args) } - //=================================================================== - // Event handler for assembly resolve events. This is needed because - // we augment the assembly search path with the PYTHONPATH when we - // load an assembly from Python. Because of that, we need to listen - // for failed loads, because they might be dependencies of something - // we loaded from Python which also needs to be found on PYTHONPATH. - //=================================================================== - + /// + /// Event handler for assembly resolve events. This is needed because + /// we augment the assembly search path with the PYTHONPATH when we + /// load an assembly from Python. Because of that, we need to listen + /// for failed loads, because they might be dependencies of something + /// we loaded from Python which also needs to be found on PYTHONPATH. + /// static Assembly ResolveHandler(Object ob, ResolveEventArgs args) { string name = args.Name.ToLower(); @@ -120,19 +116,17 @@ static Assembly ResolveHandler(Object ob, ResolveEventArgs args) } - //=================================================================== - // We __really__ want to avoid using Python objects or APIs when - // probing for assemblies to load, since our ResolveHandler may be - // called in contexts where we don't have the Python GIL and can't - // even safely try to get it without risking a deadlock ;( - // - // To work around that, we update a managed copy of sys.path (which - // is the main thing we care about) when UpdatePath is called. The - // import hook calls this whenever it knows its about to use the - // assembly manager, which lets us keep up with changes to sys.path - // in a relatively lightweight and low-overhead way. - //=================================================================== - + /// + /// We __really__ want to avoid using Python objects or APIs when + /// probing for assemblies to load, since our ResolveHandler may be + /// called in contexts where we don't have the Python GIL and can't + /// even safely try to get it without risking a deadlock ;( + /// To work around that, we update a managed copy of sys.path (which + /// is the main thing we care about) when UpdatePath is called. The + /// import hook calls this whenever it knows its about to use the + /// assembly manager, which lets us keep up with changes to sys.path + /// in a relatively lightweight and low-overhead way. + /// internal static void UpdatePath() { IntPtr list = Runtime.PySys_GetObject("path"); @@ -154,12 +148,11 @@ internal static void UpdatePath() } - //=================================================================== - // Given an assembly name, try to find this assembly file using the - // PYTHONPATH. If not found, return null to indicate implicit load - // using standard load semantics (app base directory then GAC, etc.) - //=================================================================== - + /// + /// Given an assembly name, try to find this assembly file using the + /// PYTHONPATH. If not found, return null to indicate implicit load + /// using standard load semantics (app base directory then GAC, etc.) + /// public static string FindAssembly(string name) { char sep = Path.DirectorySeparatorChar; @@ -193,11 +186,10 @@ public static string FindAssembly(string name) } - //=================================================================== - // Loads an assembly from the application directory or the GAC - // given a simple assembly name. Returns the assembly if loaded. - //=================================================================== - + /// + /// Loads an assembly from the application directory or the GAC + /// given a simple assembly name. Returns the assembly if loaded. + /// public static Assembly LoadAssembly(string name) { Assembly assembly = null; @@ -216,10 +208,9 @@ public static Assembly LoadAssembly(string name) } - //=================================================================== - // Loads an assembly using an augmented search path (the python path). - //=================================================================== - + /// + /// Loads an assembly using an augmented search path (the python path). + /// public static Assembly LoadAssemblyPath(string name) { string path = FindAssembly(name); @@ -240,8 +231,10 @@ public static Assembly LoadAssemblyPath(string name) /// /// Loads an assembly using full path. /// - /// - /// + /// + /// + /// + /// public static Assembly LoadAssemblyFullPath(string name) { Assembly assembly = null; @@ -263,10 +256,9 @@ public static Assembly LoadAssemblyFullPath(string name) return assembly; } - //=================================================================== - // Returns an assembly that's already been loaded - //=================================================================== - + /// + /// Returns an assembly that's already been loaded + /// public static Assembly FindLoadedAssembly(string name) { foreach (Assembly a in assemblies) @@ -279,18 +271,19 @@ public static Assembly FindLoadedAssembly(string name) return null; } - //=================================================================== - // Given a qualified name of the form A.B.C.D, attempt to load - // an assembly named after each of A.B.C.D, A.B.C, A.B, A. This - // will only actually probe for the assembly once for each unique - // namespace. Returns true if any assemblies were loaded. - // TODO item 3 "* Deprecate implicit loading of assemblies": - // Set the fromFile flag if the name of the loaded assembly matches - // the fully qualified name that was requested if the framework - // actually loads an assembly. - // Call ONLY for namespaces that HAVE NOT been cached yet. - //=================================================================== - + /// + /// Given a qualified name of the form A.B.C.D, attempt to load + /// an assembly named after each of A.B.C.D, A.B.C, A.B, A. This + /// will only actually probe for the assembly once for each unique + /// namespace. Returns true if any assemblies were loaded. + /// + /// + /// TODO item 3 "* Deprecate implicit loading of assemblies": + /// Set the fromFile flag if the name of the loaded assembly matches + /// the fully qualified name that was requested if the framework + /// actually loads an assembly. + /// Call ONLY for namespaces that HAVE NOT been cached yet. + /// public static bool LoadImplicit(string name, bool warn = true) { string[] names = name.Split('.'); @@ -339,13 +332,12 @@ public static bool LoadImplicit(string name, bool warn = true) } - //=================================================================== - // Scans an assembly for exported namespaces, adding them to the - // mapping of valid namespaces. Note that for a given namespace - // a.b.c.d, each of a, a.b, a.b.c and a.b.c.d are considered to - // be valid namespaces (to better match Python import semantics). - //=================================================================== - + /// + /// Scans an assembly for exported namespaces, adding them to the + /// mapping of valid namespaces. Note that for a given namespace + /// a.b.c.d, each of a, a.b, a.b.c and a.b.c.d are considered to + /// be valid namespaces (to better match Python import semantics). + /// internal static void ScanAssembly(Assembly assembly) { // A couple of things we want to do here: first, we want to @@ -390,20 +382,18 @@ public static AssemblyName[] ListAssemblies() return names.ToArray(); } - //=================================================================== - // Returns true if the given qualified name matches a namespace - // exported by an assembly loaded in the current app domain. - //=================================================================== - + /// + /// Returns true if the given qualified name matches a namespace + /// exported by an assembly loaded in the current app domain. + /// public static bool IsValidNamespace(string name) { return !String.IsNullOrEmpty(name) && namespaces.ContainsKey(name); } - //=================================================================== - // Returns list of assemblies that declare types in a given namespace - //=================================================================== - + /// + /// Returns list of assemblies that declare types in a given namespace + /// public static IEnumerable GetAssemblies(string nsname) { if (!namespaces.ContainsKey(nsname)) @@ -412,10 +402,9 @@ public static IEnumerable GetAssemblies(string nsname) return namespaces[nsname].Keys; } - //=================================================================== - // Returns the current list of valid names for the input namespace. - //=================================================================== - + /// + /// Returns the current list of valid names for the input namespace. + /// public static List GetNames(string nsname) { //Dictionary seen = new Dictionary(); @@ -460,12 +449,11 @@ public static List GetNames(string nsname) return names; } - //=================================================================== - // Returns the System.Type object for a given qualified name, - // looking in the currently loaded assemblies for the named - // type. Returns null if the named type cannot be found. - //=================================================================== - + /// + /// Returns the System.Type object for a given qualified name, + /// looking in the currently loaded assemblies for the named + /// type. Returns null if the named type cannot be found. + /// public static Type LookupType(string qname) { foreach (Assembly assembly in assemblies) @@ -528,8 +516,8 @@ public IEnumerator GetEnumerator() } /// - /// Enumerator wrapping around 's enumerator. - /// Acquires and releases a read lock on during enumeration + /// Enumerator wrapping around 's enumerator. + /// Acquires and releases a read lock on during enumeration /// private class Enumerator : IEnumerator { diff --git a/src/runtime/classbase.cs b/src/runtime/classbase.cs index 7c7bb0509..6ed43689b 100644 --- a/src/runtime/classbase.cs +++ b/src/runtime/classbase.cs @@ -30,19 +30,17 @@ internal virtual bool CanSubclass() return (!this.type.IsEnum); } - //==================================================================== - // Implements __init__ for reflected classes and value types. - //==================================================================== - + /// + /// Implements __init__ for reflected classes and value types. + /// public static int tp_init(IntPtr ob, IntPtr args, IntPtr kw) { return 0; } - //==================================================================== - // Default implementation of [] semantics for reflected types. - //==================================================================== - + /// + /// Default implementation of [] semantics for reflected types. + /// public virtual IntPtr type_subscript(IntPtr idx) { Type[] types = Runtime.PythonArgsToTypeArray(idx); @@ -64,10 +62,9 @@ public virtual IntPtr type_subscript(IntPtr idx) return Exceptions.RaiseTypeError("no type matches params"); } - //==================================================================== - // Standard comparison implementation for instances of reflected types. - //==================================================================== - + /// + /// Standard comparison implementation for instances of reflected types. + /// public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) { CLRObject co1; @@ -173,12 +170,11 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) } } - //==================================================================== - // Standard iteration support for instances of reflected types. This - // allows natural iteration over objects that either are IEnumerable - // or themselves support IEnumerator directly. - //==================================================================== - + /// + /// Standard iteration support for instances of reflected types. This + /// allows natural iteration over objects that either are IEnumerable + /// or themselves support IEnumerator directly. + /// public static IntPtr tp_iter(IntPtr ob) { CLRObject co = GetManagedObject(ob) as CLRObject; @@ -209,10 +205,9 @@ public static IntPtr tp_iter(IntPtr ob) } - //==================================================================== - // Standard __hash__ implementation for instances of reflected types. - //==================================================================== - + /// + /// Standard __hash__ implementation for instances of reflected types. + /// public static IntPtr tp_hash(IntPtr ob) { CLRObject co = GetManagedObject(ob) as CLRObject; @@ -224,10 +219,9 @@ public static IntPtr tp_hash(IntPtr ob) } - //==================================================================== - // Standard __str__ implementation for instances of reflected types. - //==================================================================== - + /// + /// Standard __str__ implementation for instances of reflected types. + /// public static IntPtr tp_str(IntPtr ob) { CLRObject co = GetManagedObject(ob) as CLRObject; @@ -251,10 +245,9 @@ public static IntPtr tp_str(IntPtr ob) } - //==================================================================== - // Default implementations for required Python GC support. - //==================================================================== - + /// + /// Default implementations for required Python GC support. + /// public static int tp_traverse(IntPtr ob, IntPtr func, IntPtr args) { return 0; @@ -270,10 +263,9 @@ public static int tp_is_gc(IntPtr type) return 1; } - //==================================================================== - // Standard dealloc implementation for instances of reflected types. - //==================================================================== - + /// + /// Standard dealloc implementation for instances of reflected types. + /// public static void tp_dealloc(IntPtr ob) { ManagedType self = GetManagedObject(ob); diff --git a/src/runtime/classderived.cs b/src/runtime/classderived.cs index ea0cbb7e9..c7f60e7af 100644 --- a/src/runtime/classderived.cs +++ b/src/runtime/classderived.cs @@ -16,7 +16,6 @@ namespace Python.Runtime /// Python type objects. Each of those type objects is associated with /// an instance of ClassObject, which provides its implementation. /// - // interface used to idenfity which C# types were dynamically created as python subclasses public interface IPythonDerivedType { @@ -569,13 +568,13 @@ private static ModuleBuilder GetModuleBuilder(string assemblyName, string module // public class PythonDerivedType { - //==================================================================== - // This is the implementaion of the overriden methods in the derived - // type. It looks for a python method with the same name as the method - // on the managed base class and if it exists and isn't the managed - // method binding (ie it has been overriden in the derived python - // class) it calls it, otherwise it calls the base method. - //==================================================================== + /// + /// This is the implementaion of the overriden methods in the derived + /// type. It looks for a python method with the same name as the method + /// on the managed base class and if it exists and isn't the managed + /// method binding (ie it has been overriden in the derived python + /// class) it calls it, otherwise it calls the base method. + /// public static T InvokeMethod(IPythonDerivedType obj, string methodName, string origMethodName, Object[] args) { FieldInfo fi = obj.GetType().GetField("__pyobj__"); diff --git a/src/runtime/classmanager.cs b/src/runtime/classmanager.cs index 2588adf7e..2af783f12 100644 --- a/src/runtime/classmanager.cs +++ b/src/runtime/classmanager.cs @@ -35,11 +35,10 @@ static ClassManager() dtype = typeof(System.MulticastDelegate); } - //==================================================================== - // Return the ClassBase-derived instance that implements a particular - // reflected managed type, creating it if it doesn't yet exist. - //==================================================================== - + /// + /// Return the ClassBase-derived instance that implements a particular + /// reflected managed type, creating it if it doesn't yet exist. + /// internal static ClassBase GetClass(Type type) { ClassBase cb = null; @@ -56,12 +55,11 @@ internal static ClassBase GetClass(Type type) } - //==================================================================== - // Create a new ClassBase-derived instance that implements a reflected - // managed type. The new object will be associated with a generated - // Python type object. - //==================================================================== - + /// + /// Create a new ClassBase-derived instance that implements a reflected + /// managed type. The new object will be associated with a generated + /// Python type object. + /// private static ClassBase CreateClass(Type type) { // Next, select the appropriate managed implementation class. diff --git a/src/runtime/classobject.cs b/src/runtime/classobject.cs index 671f0c8e6..13eab44b0 100644 --- a/src/runtime/classobject.cs +++ b/src/runtime/classobject.cs @@ -26,10 +26,9 @@ internal ClassObject(Type tp) : base(tp) } - //==================================================================== - // Helper to get docstring from reflected constructor info. - //==================================================================== - + /// + /// Helper to get docstring from reflected constructor info. + /// internal IntPtr GetDocString() { MethodBase[] methods = binder.GetMethods(); @@ -44,10 +43,9 @@ internal IntPtr GetDocString() } - //==================================================================== - // Implements __new__ for reflected classes and value types. - //==================================================================== - + /// + /// Implements __new__ for reflected classes and value types. + /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { ClassObject self = GetManagedObject(tp) as ClassObject; @@ -108,12 +106,11 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) } - //==================================================================== - // Implementation of [] semantics for reflected types. This exists - // both to implement the Array[int] syntax for creating arrays and - // to support generic name overload resolution using []. - //==================================================================== - + /// + /// Implementation of [] semantics for reflected types. This exists + /// both to implement the Array[int] syntax for creating arrays and + /// to support generic name overload resolution using []. + /// public override IntPtr type_subscript(IntPtr idx) { // If this type is the Array type, the [] means we need to @@ -160,10 +157,9 @@ public override IntPtr type_subscript(IntPtr idx) } - //==================================================================== - // Implements __getitem__ for reflected classes and value types. - //==================================================================== - + /// + /// Implements __getitem__ for reflected classes and value types. + /// public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) { //ManagedType self = GetManagedObject(ob); @@ -208,10 +204,9 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) } - //==================================================================== - // Implements __setitem__ for reflected classes and value types. - //==================================================================== - + /// + /// Implements __setitem__ for reflected classes and value types. + /// public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) { //ManagedType self = GetManagedObject(ob); @@ -289,13 +284,12 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) } - //==================================================================== - // This is a hack. Generally, no managed class is considered callable - // from Python - with the exception of System.Delegate. It is useful - // to be able to call a System.Delegate instance directly, especially - // when working with multicast delegates. - //==================================================================== - + /// + /// This is a hack. Generally, no managed class is considered callable + /// from Python - with the exception of System.Delegate. It is useful + /// to be able to call a System.Delegate instance directly, especially + /// when working with multicast delegates. + /// public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { //ManagedType self = GetManagedObject(ob); diff --git a/src/runtime/codegenerator.cs b/src/runtime/codegenerator.cs index 527ef418a..d592843cb 100644 --- a/src/runtime/codegenerator.cs +++ b/src/runtime/codegenerator.cs @@ -29,20 +29,18 @@ internal CodeGenerator() mBuilder = aBuilder.DefineDynamicModule("__CodeGenerator_Module"); } - //==================================================================== - // DefineType is a shortcut utility to get a new TypeBuilder. - //==================================================================== - + /// + /// DefineType is a shortcut utility to get a new TypeBuilder. + /// internal TypeBuilder DefineType(string name) { TypeAttributes attrs = TypeAttributes.Public; return mBuilder.DefineType(name, attrs); } - //==================================================================== - // DefineType is a shortcut utility to get a new TypeBuilder. - //==================================================================== - + /// + /// DefineType is a shortcut utility to get a new TypeBuilder. + /// internal TypeBuilder DefineType(string name, Type basetype) { TypeAttributes attrs = TypeAttributes.Public; diff --git a/src/runtime/constructorbinder.cs b/src/runtime/constructorbinder.cs index 837c7ff2e..400a0dd54 100644 --- a/src/runtime/constructorbinder.cs +++ b/src/runtime/constructorbinder.cs @@ -3,14 +3,13 @@ namespace Python.Runtime { - //======================================================================== - // A ConstructorBinder encapsulates information about one or more managed - // constructors, and is responsible for selecting the right constructor - // given a set of Python arguments. This is slightly different than the - // standard MethodBinder because of a difference in invoking constructors - // using reflection (which is seems to be a CLR bug). - //======================================================================== - + /// + /// A ConstructorBinder encapsulates information about one or more managed + /// constructors, and is responsible for selecting the right constructor + /// given a set of Python arguments. This is slightly different than the + /// standard MethodBinder because of a difference in invoking constructors + /// using reflection (which is seems to be a CLR bug). + /// internal class ConstructorBinder : MethodBinder { private Type _containingType = null; @@ -20,15 +19,14 @@ internal ConstructorBinder(Type containingType) : base() _containingType = containingType; } - //==================================================================== - // Constructors get invoked when an instance of a wrapped managed - // class or a subclass of a managed class is created. This differs - // from the MethodBinder implementation in that we return the raw - // result of the constructor rather than wrapping it as a Python - // object - the reason is that only the caller knows the correct - // Python type to use when wrapping the result (may be a subclass). - //==================================================================== - + /// + /// Constructors get invoked when an instance of a wrapped managed + /// class or a subclass of a managed class is created. This differs + /// from the MethodBinder implementation in that we return the raw + /// result of the constructor rather than wrapping it as a Python + /// object - the reason is that only the caller knows the correct + /// Python type to use when wrapping the result (may be a subclass). + /// internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw) { return this.InvokeRaw(inst, args, kw, null); diff --git a/src/runtime/constructorbinding.cs b/src/runtime/constructorbinding.cs index 940650186..6a929eff7 100644 --- a/src/runtime/constructorbinding.cs +++ b/src/runtime/constructorbinding.cs @@ -77,9 +77,9 @@ public static IntPtr tp_descr_get(IntPtr op, IntPtr instance, IntPtr owner) return self.pyHandle; } - //==================================================================== - // Implement explicit overload selection using subscript syntax ([]). - //==================================================================== + /// + /// Implement explicit overload selection using subscript syntax ([]). + /// /// /// ConstructorBinding.GetItem(PyObject *o, PyObject *key) /// Return element of o corresponding to the object key or NULL on failure. @@ -112,10 +112,9 @@ public static IntPtr mp_subscript(IntPtr op, IntPtr key) return boundCtor.pyHandle; } - //==================================================================== - // ConstructorBinding __repr__ implementation [borrowed from MethodObject]. - //==================================================================== - + /// + /// ConstructorBinding __repr__ implementation [borrowed from MethodObject]. + /// public static IntPtr tp_repr(IntPtr ob) { ConstructorBinding self = (ConstructorBinding)GetManagedObject(ob); @@ -140,10 +139,9 @@ public static IntPtr tp_repr(IntPtr ob) return self.repr; } - //==================================================================== - // ConstructorBinding dealloc implementation. - //==================================================================== - + /// + /// ConstructorBinding dealloc implementation. + /// public static new void tp_dealloc(IntPtr ob) { ConstructorBinding self = (ConstructorBinding)GetManagedObject(ob); @@ -207,10 +205,9 @@ public static IntPtr tp_call(IntPtr op, IntPtr args, IntPtr kw) return CLRObject.GetInstHandle(obj, self.pyTypeHndl); } - //==================================================================== - // BoundContructor __repr__ implementation [borrowed from MethodObject]. - //==================================================================== - + /// + /// BoundContructor __repr__ implementation [borrowed from MethodObject]. + /// public static IntPtr tp_repr(IntPtr ob) { BoundContructor self = (BoundContructor)GetManagedObject(ob); @@ -228,10 +225,9 @@ public static IntPtr tp_repr(IntPtr ob) return self.repr; } - //==================================================================== - // ConstructorBinding dealloc implementation. - //==================================================================== - + /// + /// ConstructorBinding dealloc implementation. + /// public static new void tp_dealloc(IntPtr ob) { BoundContructor self = (BoundContructor)GetManagedObject(ob); diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 320d6eb58..697d84858 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -7,10 +7,9 @@ namespace Python.Runtime { - //======================================================================== - // Performs data conversions between managed types and Python types. - //======================================================================== - + /// + /// Performs data conversions between managed types and Python types. + /// [SuppressUnmanagedCodeSecurityAttribute()] internal class Converter { @@ -48,10 +47,9 @@ static Converter() } - //==================================================================== - // Given a builtin Python type, return the corresponding CLR type. - //==================================================================== - + /// + /// Given a builtin Python type, return the corresponding CLR type. + /// internal static Type GetTypeByAlias(IntPtr op) { if ((op == Runtime.PyStringType) || @@ -113,12 +111,12 @@ internal static IntPtr GetPythonTypeByAlias(Type op) } - //==================================================================== - // Return a Python object for the given native object, converting - // basic types (string, int, etc.) into equivalent Python objects. - // This always returns a new reference. Note that the System.Decimal - // type has no Python equivalent and converts to a managed instance. - //==================================================================== + /// + /// Return a Python object for the given native object, converting + /// basic types (string, int, etc.) into equivalent Python objects. + /// This always returns a new reference. Note that the System.Decimal + /// type has no Python equivalent and converts to a managed instance. + /// internal static IntPtr ToPython(T value) { return ToPython(value, typeof(T)); @@ -234,11 +232,10 @@ internal static IntPtr ToPython(Object value, Type type) } - //==================================================================== - // In a few situations, we don't have any advisory type information - // when we want to convert an object to Python. - //==================================================================== - + /// + /// In a few situations, we don't have any advisory type information + /// when we want to convert an object to Python. + /// internal static IntPtr ToPythonImplicit(Object value) { if (value == null) @@ -252,11 +249,10 @@ internal static IntPtr ToPythonImplicit(Object value) } - //==================================================================== - // Return a managed object for the given Python object, taking funny - // byref types into account. - //==================================================================== - + /// + /// Return a managed object for the given Python object, taking funny + /// byref types into account. + /// internal static bool ToManaged(IntPtr value, Type type, out object result, bool setError) { @@ -415,10 +411,9 @@ internal static bool ToManagedValue(IntPtr value, Type obType, return ToPrimitive(value, obType, out result, setError); } - //==================================================================== - // Convert a Python value to an instance of a primitive managed type. - //==================================================================== - + /// + /// Convert a Python value to an instance of a primitive managed type. + /// static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setError) { IntPtr overflow = Exceptions.OverflowError; @@ -826,12 +821,11 @@ static void SetConversionError(IntPtr value, Type target) } - //==================================================================== - // Convert a Python value to a correctly typed managed array instance. - // The Python value must support the Python sequence protocol and the - // items in the sequence must be convertible to the target array type. - //==================================================================== - + /// + /// Convert a Python value to a correctly typed managed array instance. + /// The Python value must support the Python sequence protocol and the + /// items in the sequence must be convertible to the target array type. + /// static bool ToArray(IntPtr value, Type obType, out Object result, bool setError) { Type elementType = obType.GetElementType(); @@ -878,10 +872,9 @@ static bool ToArray(IntPtr value, Type obType, out Object result, bool setError) } - //==================================================================== - // Convert a Python value to a correctly typed managed enum instance. - //==================================================================== - + /// + /// Convert a Python value to a correctly typed managed enum instance. + /// static bool ToEnum(IntPtr value, Type obType, out Object result, bool setError) { Type etype = Enum.GetUnderlyingType(obType); diff --git a/src/runtime/delegatemanager.cs b/src/runtime/delegatemanager.cs index a9e26fb01..0a29b8e13 100644 --- a/src/runtime/delegatemanager.cs +++ b/src/runtime/delegatemanager.cs @@ -33,12 +33,11 @@ public DelegateManager() codeGenerator = new CodeGenerator(); } - //==================================================================== - // Given a true delegate instance, return the PyObject handle of the - // Python object implementing the delegate (or IntPtr.Zero if the - // delegate is not implemented in Python code. - //==================================================================== - + /// + /// Given a true delegate instance, return the PyObject handle of the + /// Python object implementing the delegate (or IntPtr.Zero if the + /// delegate is not implemented in Python code. + /// public IntPtr GetPythonHandle(Delegate d) { if ((d != null) && (d.Target is Dispatcher)) @@ -49,11 +48,10 @@ public IntPtr GetPythonHandle(Delegate d) return IntPtr.Zero; } - //==================================================================== - // GetDispatcher is responsible for creating a class that provides - // an appropriate managed callback method for a given delegate type. - //==================================================================== - + /// + /// GetDispatcher is responsible for creating a class that provides + /// an appropriate managed callback method for a given delegate type. + /// private Type GetDispatcher(Type dtype) { // If a dispatcher type for the given delegate type has already @@ -154,12 +152,11 @@ private Type GetDispatcher(Type dtype) return disp; } - //==================================================================== - // Given a delegate type and a callable Python object, GetDelegate - // returns an instance of the delegate type. The delegate instance - // returned will dispatch calls to the given Python object. - //==================================================================== - + /// + /// Given a delegate type and a callable Python object, GetDelegate + /// returns an instance of the delegate type. The delegate instance + /// returned will dispatch calls to the given Python object. + /// internal Delegate GetDelegate(Type dtype, IntPtr callable) { Type dispatcher = GetDispatcher(dtype); diff --git a/src/runtime/delegateobject.cs b/src/runtime/delegateobject.cs index 2186e98ad..2d305e5f2 100644 --- a/src/runtime/delegateobject.cs +++ b/src/runtime/delegateobject.cs @@ -20,11 +20,10 @@ internal DelegateObject(Type tp) : base(tp) } - //==================================================================== - // Given a PyObject pointer to an instance of a delegate type, return - // the true managed delegate the Python object represents (or null). - //==================================================================== - + /// + /// Given a PyObject pointer to an instance of a delegate type, return + /// the true managed delegate the Python object represents (or null). + /// private static Delegate GetTrueDelegate(IntPtr op) { CLRObject o = GetManagedObject(op) as CLRObject; @@ -43,14 +42,13 @@ internal override bool CanSubclass() } - //==================================================================== - // DelegateObject __new__ implementation. The result of this is a new - // PyObject whose type is DelegateObject and whose ob_data is a handle - // to an actual delegate instance. The method wrapped by the actual - // delegate instance belongs to an object generated to relay the call - // to the Python callable passed in. - //==================================================================== - + /// + /// DelegateObject __new__ implementation. The result of this is a new + /// PyObject whose type is DelegateObject and whose ob_data is a handle + /// to an actual delegate instance. The method wrapped by the actual + /// delegate instance belongs to an object generated to relay the call + /// to the Python callable passed in. + /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { DelegateObject self = (DelegateObject)GetManagedObject(tp); @@ -73,10 +71,9 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) } - //==================================================================== - // Implements __call__ for reflected delegate types. - //==================================================================== - + /// + /// Implements __call__ for reflected delegate types. + /// public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { // todo: add fast type check! @@ -99,9 +96,9 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) } - //==================================================================== - // Implements __cmp__ for reflected delegate types. - //==================================================================== + /// + /// Implements __cmp__ for reflected delegate types. + /// #if PYTHON3 public static new IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) { diff --git a/src/runtime/eventbinding.cs b/src/runtime/eventbinding.cs index 090d812ca..b31286b4c 100644 --- a/src/runtime/eventbinding.cs +++ b/src/runtime/eventbinding.cs @@ -2,10 +2,9 @@ namespace Python.Runtime { - //======================================================================== - // Implements a Python event binding type, similar to a method binding. - //======================================================================== - + /// + /// Implements a Python event binding type, similar to a method binding. + /// internal class EventBinding : ExtensionType { EventObject e; @@ -19,10 +18,9 @@ public EventBinding(EventObject e, IntPtr target) : base() } - //==================================================================== - // EventBinding += operator implementation. - //==================================================================== - + /// + /// EventBinding += operator implementation. + /// public static IntPtr nb_inplace_add(IntPtr ob, IntPtr arg) { EventBinding self = (EventBinding)GetManagedObject(ob); @@ -43,10 +41,9 @@ public static IntPtr nb_inplace_add(IntPtr ob, IntPtr arg) } - //==================================================================== - // EventBinding -= operator implementation. - //==================================================================== - + /// + /// EventBinding -= operator implementation. + /// public static IntPtr nb_inplace_subtract(IntPtr ob, IntPtr arg) { EventBinding self = (EventBinding)GetManagedObject(ob); @@ -67,10 +64,9 @@ public static IntPtr nb_inplace_subtract(IntPtr ob, IntPtr arg) } - //==================================================================== - // EventBinding __hash__ implementation. - //==================================================================== - + /// + /// EventBinding __hash__ implementation. + /// public static IntPtr tp_hash(IntPtr ob) { EventBinding self = (EventBinding)GetManagedObject(ob); @@ -103,10 +99,9 @@ public static IntPtr tp_hash(IntPtr ob) } - //==================================================================== - // EventBinding __repr__ implementation. - //==================================================================== - + /// + /// EventBinding __repr__ implementation. + /// public static IntPtr tp_repr(IntPtr ob) { EventBinding self = (EventBinding)GetManagedObject(ob); @@ -116,10 +111,9 @@ public static IntPtr tp_repr(IntPtr ob) } - //==================================================================== - // EventBinding dealloc implementation. - //==================================================================== - + /// + /// EventBinding dealloc implementation. + /// public static new void tp_dealloc(IntPtr ob) { EventBinding self = (EventBinding)GetManagedObject(ob); diff --git a/src/runtime/eventobject.cs b/src/runtime/eventobject.cs index 191a95546..8ac0ed3ac 100644 --- a/src/runtime/eventobject.cs +++ b/src/runtime/eventobject.cs @@ -4,10 +4,9 @@ namespace Python.Runtime { - //======================================================================== - // Implements a Python descriptor type that provides access to CLR events. - //======================================================================== - + /// + /// Implements a Python descriptor type that provides access to CLR events. + /// internal class EventObject : ExtensionType { internal string name; @@ -22,10 +21,9 @@ public EventObject(EventInfo info) : base() } - //==================================================================== - // Register a new Python object event handler with the event. - //==================================================================== - + /// + /// Register a new Python object event handler with the event. + /// internal bool AddEventHandler(IntPtr target, IntPtr handler) { Object obj = null; @@ -71,10 +69,9 @@ internal bool AddEventHandler(IntPtr target, IntPtr handler) } - //==================================================================== - // Remove the given Python object event handler. - //==================================================================== - + /// + /// Remove the given Python object event handler. + /// internal bool RemoveEventHandler(IntPtr target, IntPtr handler) { Object obj = null; @@ -128,11 +125,10 @@ internal bool RemoveEventHandler(IntPtr target, IntPtr handler) } - //==================================================================== - // Descriptor __get__ implementation. A getattr on an event returns - // a "bound" event that keeps a reference to the object instance. - //==================================================================== - + /// + /// Descriptor __get__ implementation. A getattr on an event returns + /// a "bound" event that keeps a reference to the object instance. + /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { EventObject self = GetManagedObject(ds) as EventObject; @@ -168,14 +164,13 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) } - //==================================================================== - // Descriptor __set__ implementation. This actually never allows you - // to set anything; it exists solely to support the '+=' spelling of - // event handler registration. The reason is that given code like: - // 'ob.SomeEvent += method', Python will attempt to set the attribute - // SomeEvent on ob to the result of the '+=' operation. - //==================================================================== - + /// + /// Descriptor __set__ implementation. This actually never allows you + /// to set anything; it exists solely to support the '+=' spelling of + /// event handler registration. The reason is that given code like: + /// 'ob.SomeEvent += method', Python will attempt to set the attribute + /// SomeEvent on ob to the result of the '+=' operation. + /// public static new int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { EventBinding e = GetManagedObject(val) as EventBinding; @@ -191,10 +186,9 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) } - //==================================================================== - // Descriptor __repr__ implementation. - //==================================================================== - + /// + /// Descriptor __repr__ implementation. + /// public static IntPtr tp_repr(IntPtr ob) { EventObject self = (EventObject)GetManagedObject(ob); @@ -203,10 +197,9 @@ public static IntPtr tp_repr(IntPtr ob) } - //==================================================================== - // Descriptor dealloc implementation. - //==================================================================== - + /// + /// Descriptor dealloc implementation. + /// public static new void tp_dealloc(IntPtr ob) { EventObject self = (EventObject)GetManagedObject(ob); diff --git a/src/runtime/exceptions.cs b/src/runtime/exceptions.cs index 429c09212..448655213 100644 --- a/src/runtime/exceptions.cs +++ b/src/runtime/exceptions.cs @@ -38,10 +38,9 @@ internal static Exception ToException(IntPtr ob) return e; } - //==================================================================== - // Exception __str__ implementation - //==================================================================== - + /// + /// Exception __str__ implementation + /// public new static IntPtr tp_str(IntPtr ob) { Exception e = ToException(ob); @@ -78,10 +77,9 @@ private Exceptions() { } - //=================================================================== - // Initialization performed on startup of the Python runtime. - //=================================================================== - + /// + /// Initialization performed on startup of the Python runtime. + /// internal static void Initialize() { #if PYTHON3 @@ -111,10 +109,9 @@ internal static void Initialize() } - //=================================================================== - // Cleanup resources upon shutdown of the Python runtime. - //=================================================================== - + /// + /// Cleanup resources upon shutdown of the Python runtime. + /// internal static void Shutdown() { if (0 != Runtime.Py_IsInitialized()) diff --git a/src/runtime/extensiontype.cs b/src/runtime/extensiontype.cs index 769904444..a09f57696 100644 --- a/src/runtime/extensiontype.cs +++ b/src/runtime/extensiontype.cs @@ -46,10 +46,9 @@ public ExtensionType() : base() } - //==================================================================== - // Common finalization code to support custom tp_deallocs. - //==================================================================== - + /// + /// Common finalization code to support custom tp_deallocs. + /// public static void FinalizeObject(ManagedType self) { Runtime.PyObject_GC_Del(self.pyHandle); @@ -58,10 +57,9 @@ public static void FinalizeObject(ManagedType self) } - //==================================================================== - // Type __setattr__ implementation. - //==================================================================== - + /// + /// Type __setattr__ implementation. + /// public static int tp_setattro(IntPtr ob, IntPtr key, IntPtr val) { string message = "type does not support setting attributes"; @@ -74,11 +72,10 @@ public static int tp_setattro(IntPtr ob, IntPtr key, IntPtr val) } - //==================================================================== - // Default __set__ implementation - this prevents descriptor instances - // being silently replaced in a type __dict__ by default __setattr__. - //==================================================================== - + /// + /// Default __set__ implementation - this prevents descriptor instances + /// being silently replaced in a type __dict__ by default __setattr__. + /// public static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { string message = "attribute is read-only"; @@ -87,10 +84,9 @@ public static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) } - //==================================================================== - // Required Python GC support. - //==================================================================== - + /// + /// Required Python GC support. + /// public static int tp_traverse(IntPtr ob, IntPtr func, IntPtr args) { return 0; @@ -109,10 +105,9 @@ public static int tp_is_gc(IntPtr type) } - //==================================================================== - // Default dealloc implementation. - //==================================================================== - + /// + /// Default dealloc implementation. + /// public static void tp_dealloc(IntPtr ob) { // Clean up a Python instance of this extension type. This diff --git a/src/runtime/fieldobject.cs b/src/runtime/fieldobject.cs index 53597aee7..3d65f5fd3 100644 --- a/src/runtime/fieldobject.cs +++ b/src/runtime/fieldobject.cs @@ -5,10 +5,9 @@ namespace Python.Runtime { - //======================================================================== - // Implements a Python descriptor type that provides access to CLR fields. - //======================================================================== - + /// + /// Implements a Python descriptor type that provides access to CLR fields. + /// internal class FieldObject : ExtensionType { FieldInfo info; @@ -18,12 +17,11 @@ public FieldObject(FieldInfo info) : base() this.info = info; } - //==================================================================== - // Descriptor __get__ implementation. This method returns the - // value of the field on the given object. The returned value - // is converted to an appropriately typed Python object. - //==================================================================== - + /// + /// Descriptor __get__ implementation. This method returns the + /// value of the field on the given object. The returned value + /// is converted to an appropriately typed Python object. + /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { FieldObject self = (FieldObject)GetManagedObject(ds); @@ -69,12 +67,11 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) } } - //==================================================================== - // Descriptor __set__ implementation. This method sets the value of - // a field based on the given Python value. The Python value must be - // convertible to the type of the field. - //==================================================================== - + /// + /// Descriptor __set__ implementation. This method sets the value of + /// a field based on the given Python value. The Python value must be + /// convertible to the type of the field. + /// public static new int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { FieldObject self = (FieldObject)GetManagedObject(ds); @@ -136,10 +133,9 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) } } - //==================================================================== - // Descriptor __repr__ implementation. - //==================================================================== - + /// + /// Descriptor __repr__ implementation. + /// public static IntPtr tp_repr(IntPtr ob) { FieldObject self = (FieldObject)GetManagedObject(ob); diff --git a/src/runtime/generictype.cs b/src/runtime/generictype.cs index 19cde37bf..761efc045 100644 --- a/src/runtime/generictype.cs +++ b/src/runtime/generictype.cs @@ -15,10 +15,9 @@ internal GenericType(Type tp) : base(tp) { } - //==================================================================== - // Implements __new__ for reflected generic types. - //==================================================================== - + /// + /// Implements __new__ for reflected generic types. + /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { Exceptions.SetError(Exceptions.TypeError, "cannot instantiate an open generic type"); @@ -26,10 +25,9 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) } - //==================================================================== - // Implements __call__ for reflected generic types. - //==================================================================== - + /// + /// Implements __call__ for reflected generic types. + /// public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { Exceptions.SetError(Exceptions.TypeError, "object is not callable"); diff --git a/src/runtime/genericutil.cs b/src/runtime/genericutil.cs index 9870b2a5b..6568ac438 100644 --- a/src/runtime/genericutil.cs +++ b/src/runtime/genericutil.cs @@ -24,10 +24,9 @@ static GenericUtil() mapping = new Dictionary>>(); } - //==================================================================== - // Register a generic type that appears in a given namespace. - //==================================================================== - + /// + /// Register a generic type that appears in a given namespace. + /// internal static void Register(Type t) { if (null == t.Namespace || null == t.Name) @@ -56,10 +55,9 @@ internal static void Register(Type t) gnames.Add(t.Name); } - //==================================================================== - // xxx - //==================================================================== - + /// + /// xxx + /// public static List GetGenericBaseNames(string ns) { Dictionary> nsmap = null; @@ -76,10 +74,9 @@ public static List GetGenericBaseNames(string ns) return names; } - //==================================================================== - // xxx - //==================================================================== - + /// + /// xxx + /// public static Type GenericForType(Type t, int paramCount) { return GenericByName(t.Namespace, t.Name, paramCount); @@ -136,10 +133,9 @@ public static List GenericsByName(string ns, string basename) return result; } - //==================================================================== - // xxx - //==================================================================== - + /// + /// xxx + /// public static string GenericNameForBaseName(string ns, string name) { Dictionary> nsmap = null; diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index 851bf49d7..68d81ac14 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -4,10 +4,9 @@ namespace Python.Runtime { - //======================================================================== - // Implements the "import hook" used to integrate Python with the CLR. - //======================================================================== - + /// + /// Implements the "import hook" used to integrate Python with the CLR. + /// internal class ImportHook { static IntPtr py_import; @@ -25,10 +24,9 @@ internal static void InitializeModuleDef() } #endif - //=================================================================== - // Initialization performed on startup of the Python runtime. - //=================================================================== - + /// + /// Initialization performed on startup of the Python runtime. + /// internal static void Initialize() { // Initialize the Python <--> CLR module hook. We replace the @@ -70,10 +68,9 @@ internal static void Initialize() } - //=================================================================== - // Cleanup resources upon shutdown of the Python runtime. - //=================================================================== - + /// + /// Cleanup resources upon shutdown of the Python runtime. + /// internal static void Shutdown() { if (0 != Runtime.Py_IsInitialized()) @@ -88,9 +85,9 @@ internal static void Shutdown() } } - //=================================================================== - // Return the clr python module (new reference) - //=================================================================== + /// + /// Return the clr python module (new reference) + /// public static IntPtr GetCLRModule(IntPtr? fromList = null) { root.InitializePreload(); @@ -146,10 +143,9 @@ public static IntPtr GetCLRModule(IntPtr? fromList = null) #endif } - //=================================================================== - // The actual import hook that ties Python to the managed world. - //=================================================================== - + /// + /// The actual import hook that ties Python to the managed world. + /// public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) { // Replacement for the builtin __import__. The original import diff --git a/src/runtime/indexer.cs b/src/runtime/indexer.cs index 06355c9f7..7f0b6fe10 100644 --- a/src/runtime/indexer.cs +++ b/src/runtime/indexer.cs @@ -5,10 +5,9 @@ namespace Python.Runtime { - //======================================================================== - // Bundles the information required to support an indexer property. - //======================================================================== - + /// + /// Bundles the information required to support an indexer property. + /// internal class Indexer { public MethodBinder GetterBinder; @@ -81,7 +80,7 @@ internal bool NeedsDefaultArgs(IntPtr args) /// /// This will return default arguments a new instance of a tuple. The size - /// of the tuple will indicate the number of default arguments. + /// of the tuple will indicate the number of default arguments. /// /// This is pointing to the tuple args passed in /// a new instance of the tuple containing the default args diff --git a/src/runtime/interfaceobject.cs b/src/runtime/interfaceobject.cs index 076ecc727..8e64c24d7 100644 --- a/src/runtime/interfaceobject.cs +++ b/src/runtime/interfaceobject.cs @@ -30,10 +30,9 @@ static InterfaceObject() cc_attr = typeof(CoClassAttribute); } - //==================================================================== - // Implements __new__ for reflected interface types. - //==================================================================== - + /// + /// Implements __new__ for reflected interface types. + /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { InterfaceObject self = (InterfaceObject)GetManagedObject(tp); diff --git a/src/runtime/interop.cs b/src/runtime/interop.cs index 9be8169d2..148ca2d2c 100644 --- a/src/runtime/interop.cs +++ b/src/runtime/interop.cs @@ -7,12 +7,11 @@ namespace Python.Runtime { - //======================================================================= - // This file defines objects to support binary interop with the Python - // runtime. Generally, the definitions here need to be kept up to date - // when moving to new Python versions. - //======================================================================= - + /// + /// This file defines objects to support binary interop with the Python + /// runtime. Generally, the definitions here need to be kept up to date + /// when moving to new Python versions. + /// [Serializable()] [AttributeUsage(AttributeTargets.All)] public class DocStringAttribute : Attribute diff --git a/src/runtime/iterator.cs b/src/runtime/iterator.cs index dcab722f1..f2a32deb4 100644 --- a/src/runtime/iterator.cs +++ b/src/runtime/iterator.cs @@ -4,11 +4,10 @@ namespace Python.Runtime { - //======================================================================== - // Implements a generic Python iterator for IEnumerable objects and - // managed array objects. This supports 'for i in object:' in Python. - //======================================================================== - + /// + /// Implements a generic Python iterator for IEnumerable objects and + /// managed array objects. This supports 'for i in object:' in Python. + /// internal class Iterator : ExtensionType { IEnumerator iter; @@ -19,10 +18,9 @@ public Iterator(IEnumerator e) : base() } - //==================================================================== - // Implements support for the Python iteration protocol. - //==================================================================== - + /// + /// Implements support for the Python iteration protocol. + /// public static IntPtr tp_iternext(IntPtr ob) { Iterator self = GetManagedObject(ob) as Iterator; diff --git a/src/runtime/managedtype.cs b/src/runtime/managedtype.cs index ebb2057b9..0d46f2366 100644 --- a/src/runtime/managedtype.cs +++ b/src/runtime/managedtype.cs @@ -5,12 +5,11 @@ namespace Python.Runtime { - //======================================================================== - // Common base class for all objects that are implemented in managed - // code. It defines the common fields that associate CLR and Python - // objects and common utilities to convert between those identities. - //======================================================================== - + /// + /// Common base class for all objects that are implemented in managed + /// code. It defines the common fields that associate CLR and Python + /// objects and common utilities to convert between those identities. + /// internal abstract class ManagedType { internal GCHandle gcHandle; // Native handle @@ -18,10 +17,9 @@ internal abstract class ManagedType internal IntPtr tpHandle; // PyType * - //==================================================================== - // Given a Python object, return the associated managed object or null. - //==================================================================== - + /// + /// Given a Python object, return the associated managed object or null. + /// internal static ManagedType GetManagedObject(IntPtr ob) { if (ob != IntPtr.Zero) diff --git a/src/runtime/metatype.cs b/src/runtime/metatype.cs index b1761c2d7..6701a2a07 100644 --- a/src/runtime/metatype.cs +++ b/src/runtime/metatype.cs @@ -5,21 +5,19 @@ namespace Python.Runtime { - //======================================================================== - // The managed metatype. This object implements the type of all reflected - // types. It also provides support for single-inheritance from reflected - // managed types. - //======================================================================== - + /// + /// The managed metatype. This object implements the type of all reflected + /// types. It also provides support for single-inheritance from reflected + /// managed types. + /// internal class MetaType : ManagedType { static IntPtr PyCLRMetaType; - //==================================================================== - // Metatype initialization. This bootstraps the CLR metatype to life. - //==================================================================== - + /// + /// Metatype initialization. This bootstraps the CLR metatype to life. + /// public static IntPtr Initialize() { PyCLRMetaType = TypeManager.CreateMetaType(typeof(MetaType)); @@ -27,11 +25,10 @@ public static IntPtr Initialize() } - //==================================================================== - // Metatype __new__ implementation. This is called to create a new - // class / type when a reflected class is subclassed. - //==================================================================== - + /// + /// Metatype __new__ implementation. This is called to create a new + /// class / type when a reflected class is subclassed. + /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { int len = Runtime.PyTuple_Size(args); @@ -141,12 +138,11 @@ public static void tp_free(IntPtr tp) } - //==================================================================== - // Metatype __call__ implementation. This is needed to ensure correct - // initialization (__init__ support), because the tp_call we inherit - // from PyType_Type won't call __init__ for metatypes it doesnt know. - //==================================================================== - + /// + /// Metatype __call__ implementation. This is needed to ensure correct + /// initialization (__init__ support), because the tp_call we inherit + /// from PyType_Type won't call __init__ for metatypes it doesnt know. + /// public static IntPtr tp_call(IntPtr tp, IntPtr args, IntPtr kw) { IntPtr func = Marshal.ReadIntPtr(tp, TypeOffset.tp_new); @@ -192,14 +188,13 @@ public static IntPtr tp_call(IntPtr tp, IntPtr args, IntPtr kw) } - //==================================================================== - // Type __setattr__ implementation for reflected types. Note that this - // is slightly different than the standard setattr implementation for - // the normal Python metatype (PyTypeType). We need to look first in - // the type object of a reflected type for a descriptor in order to - // support the right setattr behavior for static fields and properties. - //==================================================================== - + /// + /// Type __setattr__ implementation for reflected types. Note that this + /// is slightly different than the standard setattr implementation for + /// the normal Python metatype (PyTypeType). We need to look first in + /// the type object of a reflected type for a descriptor in order to + /// support the right setattr behavior for static fields and properties. + /// public static int tp_setattro(IntPtr tp, IntPtr name, IntPtr value) { IntPtr descr = Runtime._PyType_Lookup(tp, name); @@ -232,11 +227,11 @@ public static int tp_setattro(IntPtr tp, IntPtr name, IntPtr value) return res; } - //==================================================================== - // The metatype has to implement [] semantics for generic types, so - // here we just delegate to the generic type def implementation. Its - // own mp_subscript - //==================================================================== + /// + /// The metatype has to implement [] semantics for generic types, so + /// here we just delegate to the generic type def implementation. Its + /// own mp_subscript + /// public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) { ClassBase cb = GetManagedObject(tp) as ClassBase; @@ -247,11 +242,10 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) return Exceptions.RaiseTypeError("unsubscriptable object"); } - //==================================================================== - // Dealloc implementation. This is called when a Python type generated - // by this metatype is no longer referenced from the Python runtime. - //==================================================================== - + /// + /// Dealloc implementation. This is called when a Python type generated + /// by this metatype is no longer referenced from the Python runtime. + /// public static void tp_dealloc(IntPtr tp) { // Fix this when we dont cheat on the handle for subclasses! diff --git a/src/runtime/methodbinder.cs b/src/runtime/methodbinder.cs index c4d41d156..651791599 100644 --- a/src/runtime/methodbinder.cs +++ b/src/runtime/methodbinder.cs @@ -4,13 +4,12 @@ namespace Python.Runtime { - //======================================================================== - // A MethodBinder encapsulates information about a (possibly overloaded) - // managed method, and is responsible for selecting the right method given - // a set of Python arguments. This is also used as a base class for the - // ConstructorBinder, a minor variation used to invoke constructors. - //======================================================================== - + /// + /// A MethodBinder encapsulates information about a (possibly overloaded) + /// managed method, and is responsible for selecting the right method given + /// a set of Python arguments. This is also used as a base class for the + /// ConstructorBinder, a minor variation used to invoke constructors. + /// internal class MethodBinder { public ArrayList list; @@ -39,11 +38,10 @@ internal void AddMethod(MethodBase m) this.list.Add(m); } - //==================================================================== - // Given a sequence of MethodInfo and a sequence of types, return the - // MethodInfo that matches the signature represented by those types. - //==================================================================== - + /// + /// Given a sequence of MethodInfo and a sequence of types, return the + /// MethodInfo that matches the signature represented by those types. + /// internal static MethodInfo MatchSignature(MethodInfo[] mi, Type[] tp) { if (tp == null) @@ -73,11 +71,10 @@ internal static MethodInfo MatchSignature(MethodInfo[] mi, Type[] tp) return null; } - //==================================================================== - // Given a sequence of MethodInfo and a sequence of type parameters, - // return the MethodInfo that represents the matching closed generic. - //==================================================================== - + /// + /// Given a sequence of MethodInfo and a sequence of type parameters, + /// return the MethodInfo that represents the matching closed generic. + /// internal static MethodInfo MatchParameters(MethodInfo[] mi, Type[] tp) { if (tp == null) @@ -102,11 +99,10 @@ internal static MethodInfo MatchParameters(MethodInfo[] mi, Type[] tp) } - //==================================================================== - // Given a sequence of MethodInfo and two sequences of type parameters, - // return the MethodInfo that matches the signature and the closed generic. - //==================================================================== - + /// + /// Given a sequence of MethodInfo and two sequences of type parameters, + /// return the MethodInfo that matches the signature and the closed generic. + /// internal static MethodInfo MatchSignatureAndParameters(MethodInfo[] mi, Type[] genericTp, Type[] sigTp) { if ((genericTp == null) || (sigTp == null)) @@ -153,12 +149,11 @@ internal static MethodInfo MatchSignatureAndParameters(MethodInfo[] mi, Type[] g } - //==================================================================== - // Return the array of MethodInfo for this method. The result array - // is arranged in order of precendence (done lazily to avoid doing it - // at all for methods that are never called). - //==================================================================== - + /// + /// Return the array of MethodInfo for this method. The result array + /// is arranged in order of precendence (done lazily to avoid doing it + /// at all for methods that are never called). + /// internal MethodBase[] GetMethods() { if (!init) @@ -171,11 +166,10 @@ internal MethodBase[] GetMethods() return methods; } - //==================================================================== - // Precedence algorithm largely lifted from jython - the concerns are - // generally the same so we'll start w/this and tweak as necessary. - //==================================================================== - + /// + /// Precedence algorithm largely lifted from jython - the concerns are + /// generally the same so we'll start w/this and tweak as necessary. + /// internal static int GetPrecedence(MethodBase mi) { ParameterInfo[] pi = mi.GetParameters(); @@ -191,10 +185,9 @@ internal static int GetPrecedence(MethodBase mi) return val; } - //==================================================================== - // Return a precedence value for a particular Type object. - //==================================================================== - + /// + /// Return a precedence value for a particular Type object. + /// internal static int ArgPrecedence(Type t) { Type objectType = typeof(Object); @@ -242,12 +235,11 @@ internal static int ArgPrecedence(Type t) return 2000; } - //==================================================================== - // Bind the given Python instance and arguments to a particular method - // overload and return a structure that contains the converted Python - // instance, converted arguments and the correct method to call. - //==================================================================== - + /// + /// Bind the given Python instance and arguments to a particular method + /// overload and return a structure that contains the converted Python + /// instance, converted arguments and the correct method to call. + /// internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw) { return this.Bind(inst, args, kw, null, null); @@ -567,10 +559,9 @@ internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase i } - //======================================================================== - // Utility class to sort method info by parameter type precedence. - //======================================================================== - + /// + /// Utility class to sort method info by parameter type precedence. + /// internal class MethodSorter : IComparer { int IComparer.Compare(Object m1, Object m2) @@ -586,12 +577,11 @@ int IComparer.Compare(Object m1, Object m2) } - //======================================================================== - // A Binding is a utility instance that bundles together a MethodInfo - // representing a method to call, a (possibly null) target instance for - // the call, and the arguments for the call (all as managed values). - //======================================================================== - + /// + /// A Binding is a utility instance that bundles together a MethodInfo + /// representing a method to call, a (possibly null) target instance for + /// the call, and the arguments for the call (all as managed values). + /// internal class Binding { public MethodBase info; diff --git a/src/runtime/methodbinding.cs b/src/runtime/methodbinding.cs index 9d328381f..878779989 100644 --- a/src/runtime/methodbinding.cs +++ b/src/runtime/methodbinding.cs @@ -4,12 +4,11 @@ namespace Python.Runtime { - //======================================================================== - // Implements a Python binding type for CLR methods. These work much like - // standard Python method bindings, but the same type is used to bind - // both static and instance methods. - //======================================================================== - + /// + /// Implements a Python binding type for CLR methods. These work much like + /// standard Python method bindings, but the same type is used to bind + /// both static and instance methods. + /// internal class MethodBinding : ExtensionType { internal MethodInfo info; @@ -35,10 +34,9 @@ public MethodBinding(MethodObject m, IntPtr target) : this(m, target, IntPtr.Zer { } - //==================================================================== - // Implement binding of generic methods using the subscript syntax []. - //==================================================================== - + /// + /// Implement binding of generic methods using the subscript syntax []. + /// public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) { MethodBinding self = (MethodBinding)GetManagedObject(tp); @@ -63,10 +61,9 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) } - //==================================================================== - // MethodBinding __getattribute__ implementation. - //==================================================================== - + /// + /// MethodBinding __getattribute__ implementation. + /// public static IntPtr tp_getattro(IntPtr ob, IntPtr key) { MethodBinding self = (MethodBinding)GetManagedObject(ob); @@ -97,10 +94,9 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key) } - //==================================================================== - // MethodBinding __call__ implementation. - //==================================================================== - + /// + /// MethodBinding __call__ implementation. + /// public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { MethodBinding self = (MethodBinding)GetManagedObject(ob); @@ -187,10 +183,9 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) } - //==================================================================== - // MethodBinding __hash__ implementation. - //==================================================================== - + /// + /// MethodBinding __hash__ implementation. + /// public static IntPtr tp_hash(IntPtr ob) { MethodBinding self = (MethodBinding)GetManagedObject(ob); @@ -222,10 +217,9 @@ public static IntPtr tp_hash(IntPtr ob) return new IntPtr(x); } - //==================================================================== - // MethodBinding __repr__ implementation. - //==================================================================== - + /// + /// MethodBinding __repr__ implementation. + /// public static IntPtr tp_repr(IntPtr ob) { MethodBinding self = (MethodBinding)GetManagedObject(ob); @@ -234,10 +228,9 @@ public static IntPtr tp_repr(IntPtr ob) return Runtime.PyString_FromStringAndSize(s, s.Length); } - //==================================================================== - // MethodBinding dealloc implementation. - //==================================================================== - + /// + /// MethodBinding dealloc implementation. + /// public static new void tp_dealloc(IntPtr ob) { MethodBinding self = (MethodBinding)GetManagedObject(ob); diff --git a/src/runtime/methodobject.cs b/src/runtime/methodobject.cs index b3e1a66c5..d30188d44 100644 --- a/src/runtime/methodobject.cs +++ b/src/runtime/methodobject.cs @@ -4,12 +4,13 @@ namespace Python.Runtime { - //======================================================================== - // Implements a Python type that represents a CLR method. Method objects - // support a subscript syntax [] to allow explicit overload selection. - //======================================================================== - // TODO: ForbidPythonThreadsAttribute per method info - + /// + /// Implements a Python type that represents a CLR method. Method objects + /// support a subscript syntax [] to allow explicit overload selection. + /// + /// + /// TODO: ForbidPythonThreadsAttribute per method info + /// internal class MethodObject : ExtensionType { internal MethodInfo[] info; @@ -58,10 +59,9 @@ public virtual IntPtr Invoke(IntPtr target, IntPtr args, IntPtr kw, MethodBase i return binder.Invoke(target, args, kw, info, this.info); } - //==================================================================== - // Helper to get docstrings from reflected method / param info. - //==================================================================== - + /// + /// Helper to get docstrings from reflected method / param info. + /// internal IntPtr GetDocString() { if (doc != IntPtr.Zero) @@ -91,28 +91,27 @@ internal IntPtr GetDocString() } - //==================================================================== - // This is a little tricky: a class can actually have a static method - // and instance methods all with the same name. That makes it tough - // to support calling a method 'unbound' (passing the instance as the - // first argument), because in this case we can't know whether to call - // the instance method unbound or call the static method. - // - // The rule we is that if there are both instance and static methods - // with the same name, then we always call the static method. So this - // method returns true if any of the methods that are represented by - // the descriptor are static methods (called by MethodBinding). - //==================================================================== - + /// + /// This is a little tricky: a class can actually have a static method + /// and instance methods all with the same name. That makes it tough + /// to support calling a method 'unbound' (passing the instance as the + /// first argument), because in this case we can't know whether to call + /// the instance method unbound or call the static method. + /// + /// + /// The rule we is that if there are both instance and static methods + /// with the same name, then we always call the static method. So this + /// method returns true if any of the methods that are represented by + /// the descriptor are static methods (called by MethodBinding). + /// internal bool IsStatic() { return this.is_static; } - //==================================================================== - // Descriptor __getattribute__ implementation. - //==================================================================== - + /// + /// Descriptor __getattribute__ implementation. + /// public static IntPtr tp_getattro(IntPtr ob, IntPtr key) { MethodObject self = (MethodObject)GetManagedObject(ob); @@ -133,11 +132,10 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key) return Runtime.PyObject_GenericGetAttr(ob, key); } - //==================================================================== - // Descriptor __get__ implementation. Accessing a CLR method returns - // a "bound" method similar to a Python bound method. - //==================================================================== - + /// + /// Descriptor __get__ implementation. Accessing a CLR method returns + /// a "bound" method similar to a Python bound method. + /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { MethodObject self = (MethodObject)GetManagedObject(ds); @@ -183,10 +181,9 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) return binding.pyHandle; } - //==================================================================== - // Descriptor __repr__ implementation. - //==================================================================== - + /// + /// Descriptor __repr__ implementation. + /// public static IntPtr tp_repr(IntPtr ob) { MethodObject self = (MethodObject)GetManagedObject(ob); @@ -194,10 +191,9 @@ public static IntPtr tp_repr(IntPtr ob) return Runtime.PyString_FromStringAndSize(s, s.Length); } - //==================================================================== - // Descriptor dealloc implementation. - //==================================================================== - + /// + /// Descriptor dealloc implementation. + /// public static new void tp_dealloc(IntPtr ob) { MethodObject self = (MethodObject)GetManagedObject(ob); diff --git a/src/runtime/modulefunctionobject.cs b/src/runtime/modulefunctionobject.cs index 667b37fe9..b6f2899d8 100644 --- a/src/runtime/modulefunctionobject.cs +++ b/src/runtime/modulefunctionobject.cs @@ -22,20 +22,18 @@ public ModuleFunctionObject(Type type, string name, MethodInfo[] info, bool allo } } - //==================================================================== - // __call__ implementation. - //==================================================================== - + /// + /// __call__ implementation. + /// public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { ModuleFunctionObject self = (ModuleFunctionObject)GetManagedObject(ob); return self.Invoke(ob, args, kw); } - //==================================================================== - // __repr__ implementation. - //==================================================================== - + /// + /// __repr__ implementation. + /// public static new IntPtr tp_repr(IntPtr ob) { ModuleFunctionObject self = (ModuleFunctionObject)GetManagedObject(ob); diff --git a/src/runtime/moduleobject.cs b/src/runtime/moduleobject.cs index c4fec976b..3b9ad94a9 100644 --- a/src/runtime/moduleobject.cs +++ b/src/runtime/moduleobject.cs @@ -7,11 +7,10 @@ namespace Python.Runtime { - //======================================================================== - // Implements a Python type that provides access to CLR namespaces. The - // type behaves like a Python module, and can contain other sub-modules. - //======================================================================== - + /// + /// Implements a Python type that provides access to CLR namespaces. The + /// type behaves like a Python module, and can contain other sub-modules. + /// internal class ModuleObject : ExtensionType { Dictionary cache; @@ -61,13 +60,12 @@ public ModuleObject(string name) : base() } - //=================================================================== - // Returns a ClassBase object representing a type that appears in - // this module's namespace or a ModuleObject representing a child - // namespace (or null if the name is not found). This method does - // not increment the Python refcount of the returned object. - //=================================================================== - + /// + /// Returns a ClassBase object representing a type that appears in + /// this module's namespace or a ModuleObject representing a child + /// namespace (or null if the name is not found). This method does + /// not increment the Python refcount of the returned object. + /// public ManagedType GetAttribute(string name, bool guess) { ManagedType cached = null; @@ -175,10 +173,9 @@ public ManagedType GetAttribute(string name, bool guess) } - //=================================================================== - // Stores an attribute in the instance dict for future lookups. - //=================================================================== - + /// + /// Stores an attribute in the instance dict for future lookups. + /// private void StoreAttribute(string name, ManagedType ob) { Runtime.PyDict_SetItemString(dict, name, ob.pyHandle); @@ -186,12 +183,11 @@ private void StoreAttribute(string name, ManagedType ob) } - //=================================================================== - // Preloads all currently-known names for the module namespace. This - // can be called multiple times, to add names from assemblies that - // may have been loaded since the last call to the method. - //=================================================================== - + /// + /// Preloads all currently-known names for the module namespace. This + /// can be called multiple times, to add names from assemblies that + /// may have been loaded since the last call to the method. + /// public void LoadNames() { ManagedType m = null; @@ -253,13 +249,12 @@ internal void InitializeModuleMembers() } - //==================================================================== - // ModuleObject __getattribute__ implementation. Module attributes - // are always either classes or sub-modules representing subordinate - // namespaces. CLR modules implement a lazy pattern - the sub-modules - // and classes are created when accessed and cached for future use. - //==================================================================== - + /// + /// ModuleObject __getattribute__ implementation. Module attributes + /// are always either classes or sub-modules representing subordinate + /// namespaces. CLR modules implement a lazy pattern - the sub-modules + /// and classes are created when accessed and cached for future use. + /// public static IntPtr tp_getattro(IntPtr ob, IntPtr key) { ModuleObject self = (ModuleObject)GetManagedObject(ob); @@ -296,10 +291,9 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key) return attr.pyHandle; } - //==================================================================== - // ModuleObject __repr__ implementation. - //==================================================================== - + /// + /// ModuleObject __repr__ implementation. + /// public static IntPtr tp_repr(IntPtr ob) { ModuleObject self = (ModuleObject)GetManagedObject(ob); diff --git a/src/runtime/overload.cs b/src/runtime/overload.cs index e7d548a23..a183863d6 100644 --- a/src/runtime/overload.cs +++ b/src/runtime/overload.cs @@ -3,11 +3,10 @@ namespace Python.Runtime { - //======================================================================== - // Implements the __overloads__ attribute of method objects. This object - // supports the [] syntax to explicitly select an overload by signature. - //======================================================================== - + /// + /// Implements the __overloads__ attribute of method objects. This object + /// supports the [] syntax to explicitly select an overload by signature. + /// internal class OverloadMapper : ExtensionType { MethodObject m; @@ -20,10 +19,9 @@ public OverloadMapper(MethodObject m, IntPtr target) : base() this.m = m; } - //==================================================================== - // Implement explicit overload selection using subscript syntax ([]). - //==================================================================== - + /// + /// Implement explicit overload selection using subscript syntax ([]). + /// public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) { OverloadMapper self = (OverloadMapper)GetManagedObject(tp); @@ -51,10 +49,9 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) return mb.pyHandle; } - //==================================================================== - // OverloadMapper __repr__ implementation. - //==================================================================== - + /// + /// OverloadMapper __repr__ implementation. + /// public static IntPtr tp_repr(IntPtr op) { OverloadMapper self = (OverloadMapper)GetManagedObject(op); @@ -63,10 +60,9 @@ public static IntPtr tp_repr(IntPtr op) return doc; } - //==================================================================== - // OverloadMapper dealloc implementation. - //==================================================================== - + /// + /// OverloadMapper dealloc implementation. + /// public static new void tp_dealloc(IntPtr ob) { OverloadMapper self = (OverloadMapper)GetManagedObject(ob); diff --git a/src/runtime/propertyobject.cs b/src/runtime/propertyobject.cs index bfb70899f..ea029cc91 100644 --- a/src/runtime/propertyobject.cs +++ b/src/runtime/propertyobject.cs @@ -5,10 +5,9 @@ namespace Python.Runtime { - //======================================================================== - // Implements a Python descriptor type that manages CLR properties. - //======================================================================== - + /// + /// Implements a Python descriptor type that manages CLR properties. + /// internal class PropertyObject : ExtensionType { PropertyInfo info; @@ -24,12 +23,11 @@ public PropertyObject(PropertyInfo md) : base() } - //==================================================================== - // Descriptor __get__ implementation. This method returns the - // value of the property on the given object. The returned value - // is converted to an appropriately typed Python object. - //==================================================================== - + /// + /// Descriptor __get__ implementation. This method returns the + /// value of the property on the given object. The returned value + /// is converted to an appropriately typed Python object. + /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { PropertyObject self = (PropertyObject)GetManagedObject(ds); @@ -85,12 +83,11 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) } - //==================================================================== - // Descriptor __set__ implementation. This method sets the value of - // a property based on the given Python value. The Python value must - // be convertible to the type of the property. - //==================================================================== - + /// + /// Descriptor __set__ implementation. This method sets the value of + /// a property based on the given Python value. The Python value must + /// be convertible to the type of the property. + /// public static new int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { PropertyObject self = (PropertyObject)GetManagedObject(ds); @@ -156,10 +153,9 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) } - //==================================================================== - // Descriptor __repr__ implementation. - //==================================================================== - + /// + /// Descriptor __repr__ implementation. + /// public static IntPtr tp_repr(IntPtr ob) { PropertyObject self = (PropertyObject)GetManagedObject(ob); diff --git a/src/runtime/pyansistring.cs b/src/runtime/pyansistring.cs index 71dec3362..d15961ee3 100644 --- a/src/runtime/pyansistring.cs +++ b/src/runtime/pyansistring.cs @@ -7,7 +7,6 @@ public class PyAnsiString : PySequence /// /// PyAnsiString Constructor /// - /// /// /// Creates a new PyAnsiString from an existing object reference. Note /// that the instance assumes ownership of the object reference. @@ -21,7 +20,6 @@ public PyAnsiString(IntPtr ptr) : base(ptr) /// /// PyString Constructor /// - /// /// /// Copy constructor - obtain a PyAnsiString from a generic PyObject. /// An ArgumentException will be thrown if the given object is not @@ -41,7 +39,6 @@ public PyAnsiString(PyObject o) : base() /// /// PyAnsiString Constructor /// - /// /// /// Creates a Python string from a managed string. /// @@ -58,7 +55,6 @@ public PyAnsiString(string s) : base() /// /// IsStringType Method /// - /// /// /// Returns true if the given object is a Python string. /// diff --git a/src/runtime/pydict.cs b/src/runtime/pydict.cs index 0d1449862..1672df4fe 100644 --- a/src/runtime/pydict.cs +++ b/src/runtime/pydict.cs @@ -12,7 +12,6 @@ public class PyDict : PyObject /// /// PyDict Constructor /// - /// /// /// Creates a new PyDict from an existing object reference. Note /// that the instance assumes ownership of the object reference. @@ -26,7 +25,6 @@ public PyDict(IntPtr ptr) : base(ptr) /// /// PyDict Constructor /// - /// /// /// Creates a new Python dictionary object. /// @@ -43,7 +41,6 @@ public PyDict() : base() /// /// PyDict Constructor /// - /// /// /// Copy constructor - obtain a PyDict from a generic PyObject. An /// ArgumentException will be thrown if the given object is not a @@ -63,7 +60,6 @@ public PyDict(PyObject o) : base() /// /// IsDictType Method /// - /// /// /// Returns true if the given object is a Python dictionary. /// @@ -76,7 +72,6 @@ public static bool IsDictType(PyObject value) /// /// HasKey Method /// - /// /// /// Returns true if the object key appears in the dictionary. /// @@ -89,7 +84,6 @@ public bool HasKey(PyObject key) /// /// HasKey Method /// - /// /// /// Returns true if the string key appears in the dictionary. /// @@ -103,7 +97,6 @@ public bool HasKey(string key) /// /// Keys Method /// - /// /// /// Returns a sequence containing the keys of the dictionary. /// @@ -121,7 +114,6 @@ public PyObject Keys() /// /// Values Method /// - /// /// /// Returns a sequence containing the values of the dictionary. /// @@ -139,7 +131,6 @@ public PyObject Values() /// /// Items Method /// - /// /// /// Returns a sequence containing the items of the dictionary. /// @@ -157,7 +148,6 @@ public PyObject Items() /// /// Copy Method /// - /// /// /// Returns a copy of the dictionary. /// @@ -175,7 +165,6 @@ public PyDict Copy() /// /// Update Method /// - /// /// /// Update the dictionary from another dictionary. /// @@ -192,7 +181,6 @@ public void Update(PyObject other) /// /// Clear Method /// - /// /// /// Clears the dictionary. /// diff --git a/src/runtime/pyfloat.cs b/src/runtime/pyfloat.cs index c8a363ea8..bcd5ad23d 100644 --- a/src/runtime/pyfloat.cs +++ b/src/runtime/pyfloat.cs @@ -12,7 +12,6 @@ public class PyFloat : PyNumber /// /// PyFloat Constructor /// - /// /// /// Creates a new PyFloat from an existing object reference. Note /// that the instance assumes ownership of the object reference. @@ -26,7 +25,6 @@ public PyFloat(IntPtr ptr) : base(ptr) /// /// PyFloat Constructor /// - /// /// /// Copy constructor - obtain a PyFloat from a generic PyObject. An /// ArgumentException will be thrown if the given object is not a @@ -46,7 +44,6 @@ public PyFloat(PyObject o) : base() /// /// PyFloat Constructor /// - /// /// /// Creates a new Python float from a double value. /// @@ -63,7 +60,6 @@ public PyFloat(double value) : base() /// /// PyFloat Constructor /// - /// /// /// Creates a new Python float from a string value. /// @@ -83,7 +79,6 @@ public PyFloat(string value) : base() /// /// IsFloatType Method /// - /// /// /// Returns true if the given object is a Python float. /// @@ -96,8 +91,6 @@ public static bool IsFloatType(PyObject value) /// /// AsFloat Method /// - /// - /// /// /// Convert a Python object to a Python float if possible, raising /// a PythonException if the conversion is not possible. This is diff --git a/src/runtime/pyint.cs b/src/runtime/pyint.cs index 847ad2ebf..43f9d02aa 100644 --- a/src/runtime/pyint.cs +++ b/src/runtime/pyint.cs @@ -12,7 +12,6 @@ public class PyInt : PyNumber /// /// PyInt Constructor /// - /// /// /// Creates a new PyInt from an existing object reference. Note /// that the instance assumes ownership of the object reference. @@ -26,7 +25,6 @@ public PyInt(IntPtr ptr) : base(ptr) /// /// PyInt Constructor /// - /// /// /// Copy constructor - obtain a PyInt from a generic PyObject. An /// ArgumentException will be thrown if the given object is not a @@ -46,7 +44,6 @@ public PyInt(PyObject o) : base() /// /// PyInt Constructor /// - /// /// /// Creates a new Python int from an int32 value. /// @@ -63,7 +60,6 @@ public PyInt(int value) : base() /// /// PyInt Constructor /// - /// /// /// Creates a new Python int from a uint32 value. /// @@ -81,7 +77,6 @@ public PyInt(uint value) : base(IntPtr.Zero) /// /// PyInt Constructor /// - /// /// /// Creates a new Python int from an int64 value. /// @@ -98,7 +93,6 @@ public PyInt(long value) : base(IntPtr.Zero) /// /// PyInt Constructor /// - /// /// /// Creates a new Python int from a uint64 value. /// @@ -116,7 +110,6 @@ public PyInt(ulong value) : base(IntPtr.Zero) /// /// PyInt Constructor /// - /// /// /// Creates a new Python int from an int16 value. /// @@ -128,7 +121,6 @@ public PyInt(short value) : this((int)value) /// /// PyInt Constructor /// - /// /// /// Creates a new Python int from a uint16 value. /// @@ -141,7 +133,6 @@ public PyInt(ushort value) : this((int)value) /// /// PyInt Constructor /// - /// /// /// Creates a new Python int from a byte value. /// @@ -153,7 +144,6 @@ public PyInt(byte value) : this((int)value) /// /// PyInt Constructor /// - /// /// /// Creates a new Python int from an sbyte value. /// @@ -166,7 +156,6 @@ public PyInt(sbyte value) : this((int)value) /// /// PyInt Constructor /// - /// /// /// Creates a new Python int from a string value. /// @@ -183,7 +172,6 @@ public PyInt(string value) : base() /// /// IsIntType Method /// - /// /// /// Returns true if the given object is a Python int. /// @@ -196,8 +184,6 @@ public static bool IsIntType(PyObject value) /// /// AsInt Method /// - /// - /// /// /// Convert a Python object to a Python int if possible, raising /// a PythonException if the conversion is not possible. This is @@ -217,7 +203,6 @@ public static PyInt AsInt(PyObject value) /// /// ToInt16 Method /// - /// /// /// Return the value of the Python int object as an int16. /// @@ -230,7 +215,6 @@ public short ToInt16() /// /// ToInt32 Method /// - /// /// /// Return the value of the Python int object as an int32. /// @@ -243,7 +227,6 @@ public int ToInt32() /// /// ToInt64 Method /// - /// /// /// Return the value of the Python int object as an int64. /// diff --git a/src/runtime/pyiter.cs b/src/runtime/pyiter.cs index 5310c4d8b..a2f239ccf 100644 --- a/src/runtime/pyiter.cs +++ b/src/runtime/pyiter.cs @@ -14,7 +14,6 @@ public class PyIter : PyObject, IEnumerator /// /// PyIter Constructor /// - /// /// /// Creates a new PyIter from an existing iterator reference. Note /// that the instance assumes ownership of the object reference. @@ -27,7 +26,6 @@ public PyIter(IntPtr ptr) : base(ptr) /// /// PyIter Constructor /// - /// /// /// Creates a Python iterator from an iterable. Like doing "iter(iterable)" in python. /// diff --git a/src/runtime/pylist.cs b/src/runtime/pylist.cs index 681e864a4..235f39c77 100644 --- a/src/runtime/pylist.cs +++ b/src/runtime/pylist.cs @@ -11,7 +11,6 @@ public class PyList : PySequence /// /// PyList Constructor /// - /// /// /// Creates a new PyList from an existing object reference. Note /// that the instance assumes ownership of the object reference. @@ -25,7 +24,6 @@ public PyList(IntPtr ptr) : base(ptr) /// /// PyList Constructor /// - /// /// /// Copy constructor - obtain a PyList from a generic PyObject. An /// ArgumentException will be thrown if the given object is not a @@ -45,7 +43,6 @@ public PyList(PyObject o) : base() /// /// PyList Constructor /// - /// /// /// Creates a new empty Python list object. /// @@ -62,7 +59,6 @@ public PyList() : base() /// /// PyList Constructor /// - /// /// /// Creates a new Python list object from an array of PyObjects. /// @@ -86,7 +82,6 @@ public PyList(PyObject[] items) : base() /// /// IsListType Method /// - /// /// /// Returns true if the given object is a Python list. /// @@ -99,7 +94,6 @@ public static bool IsListType(PyObject value) /// /// AsList Method /// - /// /// /// Converts a Python object to a Python list if possible, raising /// a PythonException if the conversion is not possible. This is @@ -119,7 +113,6 @@ public static PyList AsList(PyObject value) /// /// Append Method /// - /// /// /// Append an item to the list object. /// @@ -135,7 +128,6 @@ public void Append(PyObject item) /// /// Insert Method /// - /// /// /// Insert an item in the list object at the given index. /// @@ -152,7 +144,6 @@ public void Insert(int index, PyObject item) /// /// Reverse Method /// - /// /// /// Reverse the order of the list object in place. /// @@ -169,7 +160,6 @@ public void Reverse() /// /// Sort Method /// - /// /// /// Sort the list in place. /// diff --git a/src/runtime/pylong.cs b/src/runtime/pylong.cs index 8e17d2a59..a4ce60279 100644 --- a/src/runtime/pylong.cs +++ b/src/runtime/pylong.cs @@ -11,7 +11,6 @@ public class PyLong : PyNumber /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from an existing object reference. Note /// that the instance assumes ownership of the object reference. @@ -25,7 +24,6 @@ public PyLong(IntPtr ptr) : base(ptr) /// /// PyLong Constructor /// - /// /// /// Copy constructor - obtain a PyLong from a generic PyObject. An /// ArgumentException will be thrown if the given object is not a @@ -45,7 +43,6 @@ public PyLong(PyObject o) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from an int32 value. /// @@ -62,7 +59,6 @@ public PyLong(int value) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from a uint32 value. /// @@ -80,7 +76,6 @@ public PyLong(uint value) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from an int64 value. /// @@ -97,7 +92,6 @@ public PyLong(long value) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from a uint64 value. /// @@ -115,7 +109,6 @@ public PyLong(ulong value) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from an int16 value. /// @@ -132,7 +125,6 @@ public PyLong(short value) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from an uint16 value. /// @@ -150,7 +142,6 @@ public PyLong(ushort value) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from a byte value. /// @@ -167,7 +158,6 @@ public PyLong(byte value) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from an sbyte value. /// @@ -185,7 +175,6 @@ public PyLong(sbyte value) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from an double value. /// @@ -202,7 +191,6 @@ public PyLong(double value) : base() /// /// PyLong Constructor /// - /// /// /// Creates a new PyLong from a string value. /// @@ -219,7 +207,6 @@ public PyLong(string value) : base() /// /// IsLongType Method /// - /// /// /// Returns true if the given object is a Python long. /// @@ -232,8 +219,6 @@ public static bool IsLongType(PyObject value) /// /// AsLong Method /// - /// - /// /// /// Convert a Python object to a Python long if possible, raising /// a PythonException if the conversion is not possible. This is @@ -252,7 +237,6 @@ public static PyLong AsLong(PyObject value) /// /// ToInt16 Method /// - /// /// /// Return the value of the Python long object as an int16. /// @@ -265,7 +249,6 @@ public short ToInt16() /// /// ToInt32 Method /// - /// /// /// Return the value of the Python long object as an int32. /// @@ -278,7 +261,6 @@ public int ToInt32() /// /// ToInt64 Method /// - /// /// /// Return the value of the Python long object as an int64. /// diff --git a/src/runtime/pynumber.cs b/src/runtime/pynumber.cs index e6805d708..14b32b593 100644 --- a/src/runtime/pynumber.cs +++ b/src/runtime/pynumber.cs @@ -21,7 +21,6 @@ protected PyNumber() : base() /// /// IsNumberType Method /// - /// /// /// Returns true if the given object is a Python numeric type. /// diff --git a/src/runtime/pysequence.cs b/src/runtime/pysequence.cs index a5f6f3dad..85101128b 100644 --- a/src/runtime/pysequence.cs +++ b/src/runtime/pysequence.cs @@ -22,7 +22,6 @@ protected PySequence() : base() /// /// IsSequenceType Method /// - /// /// /// Returns true if the given object implements the sequence protocol. /// @@ -35,7 +34,6 @@ public static bool IsSequenceType(PyObject value) /// /// GetSlice Method /// - /// /// /// Return the slice of the sequence with the given indices. /// @@ -53,7 +51,6 @@ public PyObject GetSlice(int i1, int i2) /// /// SetSlice Method /// - /// /// /// Sets the slice of the sequence with the given indices. /// @@ -70,7 +67,6 @@ public void SetSlice(int i1, int i2, PyObject v) /// /// DelSlice Method /// - /// /// /// Deletes the slice of the sequence with the given indices. /// @@ -87,7 +83,6 @@ public void DelSlice(int i1, int i2) /// /// Index Method /// - /// /// /// Return the index of the given item in the sequence, or -1 if /// the item does not appear in the sequence. @@ -107,7 +102,6 @@ public int Index(PyObject item) /// /// Contains Method /// - /// /// /// Return true if the sequence contains the given item. This method /// throws a PythonException if an error occurs during the check. @@ -126,7 +120,6 @@ public bool Contains(PyObject item) /// /// Concat Method /// - /// /// /// Return the concatenation of the sequence object with the passed in /// sequence object. @@ -145,7 +138,6 @@ public PyObject Concat(PyObject other) /// /// Repeat Method /// - /// /// /// Return the sequence object repeated N times. This is equivalent /// to the Python expression "object * count". diff --git a/src/runtime/pystring.cs b/src/runtime/pystring.cs index a3d198a2c..1fe3a6d7e 100644 --- a/src/runtime/pystring.cs +++ b/src/runtime/pystring.cs @@ -12,7 +12,6 @@ public class PyString : PySequence /// /// PyString Constructor /// - /// /// /// Creates a new PyString from an existing object reference. Note /// that the instance assumes ownership of the object reference. @@ -26,7 +25,6 @@ public PyString(IntPtr ptr) : base(ptr) /// /// PyString Constructor /// - /// /// /// Copy constructor - obtain a PyString from a generic PyObject. /// An ArgumentException will be thrown if the given object is not @@ -46,7 +44,6 @@ public PyString(PyObject o) : base() /// /// PyString Constructor /// - /// /// /// Creates a Python string from a managed string. /// @@ -63,7 +60,6 @@ public PyString(string s) : base() /// /// IsStringType Method /// - /// /// /// Returns true if the given object is a Python string. /// diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 3f0022467..a2eccff0d 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -210,11 +210,11 @@ public static void Initialize(IEnumerable args) } } - //==================================================================== - // A helper to perform initialization from the context of an active - // CPython interpreter process - this bootstraps the managed runtime - // when it is imported by the CLR extension module. - //==================================================================== + /// + /// A helper to perform initialization from the context of an active + /// CPython interpreter process - this bootstraps the managed runtime + /// when it is imported by the CLR extension module. + /// #if PYTHON3 public static IntPtr InitExt() #elif PYTHON2 diff --git a/src/runtime/pythonexception.cs b/src/runtime/pythonexception.cs index 124636457..d2475664c 100644 --- a/src/runtime/pythonexception.cs +++ b/src/runtime/pythonexception.cs @@ -76,7 +76,6 @@ public void Restore() /// /// PyType Property /// - /// /// /// Returns the exception type as a Python object. /// @@ -88,7 +87,6 @@ public IntPtr PyType /// /// PyValue Property /// - /// /// /// Returns the exception value as a Python object. /// @@ -100,7 +98,6 @@ public IntPtr PyValue /// /// PyTB Property /// - /// /// /// Returns the TraceBack as a Python object. /// @@ -112,7 +109,6 @@ public IntPtr PyTB /// /// Message Property /// - /// /// /// A string representing the python exception message. /// @@ -124,7 +120,6 @@ public override string Message /// /// StackTrace Property /// - /// /// /// A string representing the python exception stack trace. /// @@ -137,7 +132,6 @@ public override string StackTrace /// /// Dispose Method /// - /// /// /// The Dispose method provides a way to explicitly release the /// Python objects represented by a PythonException. @@ -166,7 +160,6 @@ public void Dispose() /// /// Matches Method /// - /// /// /// Returns true if the Python exception type represented by the /// PythonException instance matches the given exception type. diff --git a/src/runtime/pytuple.cs b/src/runtime/pytuple.cs index 97f4c5bbc..682ed3f50 100644 --- a/src/runtime/pytuple.cs +++ b/src/runtime/pytuple.cs @@ -11,7 +11,6 @@ public class PyTuple : PySequence /// /// PyTuple Constructor /// - /// /// /// Creates a new PyTuple from an existing object reference. Note /// that the instance assumes ownership of the object reference. @@ -25,7 +24,6 @@ public PyTuple(IntPtr ptr) : base(ptr) /// /// PyTuple Constructor /// - /// /// /// Copy constructor - obtain a PyTuple from a generic PyObject. An /// ArgumentException will be thrown if the given object is not a @@ -45,7 +43,6 @@ public PyTuple(PyObject o) : base() /// /// PyTuple Constructor /// - /// /// /// Creates a new empty PyTuple. /// @@ -62,7 +59,6 @@ public PyTuple() : base() /// /// PyTuple Constructor /// - /// /// /// Creates a new PyTuple from an array of PyObject instances. /// @@ -86,7 +82,6 @@ public PyTuple(PyObject[] items) : base() /// /// IsTupleType Method /// - /// /// /// Returns true if the given object is a Python tuple. /// @@ -99,7 +94,6 @@ public static bool IsTupleType(PyObject value) /// /// AsTuple Method /// - /// /// /// Convert a Python object to a Python tuple if possible, raising /// a PythonException if the conversion is not possible. This is diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index f79daa970..2c1ab87ab 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -184,7 +184,7 @@ public class Runtime internal static bool is32bit; /// - /// Intitialize the runtime... + /// Initialize the runtime... /// internal static void Initialize() { @@ -333,7 +333,7 @@ internal static void Shutdown() Py_Finalize(); } - // called *without* the GIL aquired by clr._AtExit + // called *without* the GIL acquired by clr._AtExit internal static int AtExit() { lock (IsFinalizingLock) @@ -497,12 +497,11 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) return types; } - //=================================================================== - // Managed exports of the Python C API. Where appropriate, we do - // some optimization to avoid managed <--> unmanaged transitions - // (mostly for heavily used methods). - //=================================================================== - + /// + /// Managed exports of the Python C API. Where appropriate, we do + /// some optimization to avoid managed <--> unmanaged transitions + /// (mostly for heavily used methods). + /// internal unsafe static void XIncref(IntPtr op) { #if Py_DEBUG @@ -877,14 +876,14 @@ internal unsafe static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); - //==================================================================== - // Python abstract object API - //==================================================================== - - // A macro-like method to get the type of a Python object. This is - // designed to be lean and mean in IL & avoid managed <-> unmanaged - // transitions. Note that this does not incref the type object. - + /// + /// Python abstract object API + /// + /// + /// A macro-like method to get the type of a Python object. This is + /// designed to be lean and mean in IL & avoid managed <-> unmanaged + /// transitions. Note that this does not incref the type object. + /// internal unsafe static IntPtr PyObject_TYPE(IntPtr op) { @@ -908,10 +907,11 @@ internal unsafe static IntPtr } } - // Managed version of the standard Python C API PyObject_Type call. - // This version avoids a managed <-> unmanaged transition. This one - // does incref the returned type object. - + /// + /// Managed version of the standard Python C API PyObject_Type call. + /// This version avoids a managed <-> unmanaged transition. This one + /// does incref the returned type object. + /// internal unsafe static IntPtr PyObject_Type(IntPtr op) { @@ -1089,10 +1089,9 @@ internal unsafe static extern IntPtr PyObject_Dir(IntPtr pointer); - //==================================================================== - // Python number API - //==================================================================== - + /// + /// Python number API + /// #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyNumber_Long", @@ -1394,10 +1393,9 @@ internal unsafe static extern IntPtr internal unsafe static extern IntPtr PyNumber_Invert(IntPtr o1); - //==================================================================== - // Python sequence API - //==================================================================== - + /// + /// Python sequence API + /// [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern bool @@ -1474,10 +1472,9 @@ internal unsafe static extern IntPtr PySequence_List(IntPtr pointer); - //==================================================================== - // Python string API - //==================================================================== - + /// + /// Python string API + /// internal static bool IsStringType(IntPtr op) { IntPtr t = PyObject_TYPE(op); @@ -1769,10 +1766,9 @@ internal unsafe static string GetManagedString(IntPtr op) return null; } - //==================================================================== - // Python dictionary API - //==================================================================== - + /// + /// Python dictionary API + /// internal static bool PyDict_Check(IntPtr ob) { return PyObject_TYPE(ob) == Runtime.PyDictType; @@ -1859,10 +1855,9 @@ internal unsafe static extern int PyDict_Size(IntPtr pointer); - //==================================================================== - // Python list API - //==================================================================== - + /// + /// Python list API + /// internal static bool PyList_Check(IntPtr ob) { return PyObject_TYPE(ob) == Runtime.PyListType; @@ -1924,10 +1919,9 @@ internal unsafe static extern int PyList_Size(IntPtr pointer); - //==================================================================== - // Python tuple API - //==================================================================== - + /// + /// Python tuple API + /// internal static bool PyTuple_Check(IntPtr ob) { return PyObject_TYPE(ob) == Runtime.PyTupleType; @@ -1959,10 +1953,9 @@ internal unsafe static extern int PyTuple_Size(IntPtr pointer); - //==================================================================== - // Python iterator API - //==================================================================== - + /// + /// Python iterator API + /// #if PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -1983,10 +1976,9 @@ internal static bool internal unsafe static extern IntPtr PyIter_Next(IntPtr pointer); - //==================================================================== - // Python module API - //==================================================================== - + /// + /// Python module API + /// [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr @@ -2070,10 +2062,9 @@ internal unsafe static extern int PySys_SetObject(string name, IntPtr ob); - //==================================================================== - // Python type object API - //==================================================================== - + /// + /// Python type object API + /// internal static bool PyType_Check(IntPtr ob) { return PyObject_TypeCheck(ob, Runtime.PyTypeType); @@ -2151,10 +2142,9 @@ internal unsafe static extern void PyObject_GC_UnTrack(IntPtr tp); - //==================================================================== - // Python memory API - //==================================================================== - + /// + /// Python memory API + /// [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr @@ -2171,10 +2161,9 @@ internal unsafe static extern void PyMem_Free(IntPtr ptr); - //==================================================================== - // Python exception API - //==================================================================== - + /// + /// Python exception API + /// [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern void @@ -2236,10 +2225,9 @@ internal unsafe static extern void PyErr_Print(); - //==================================================================== - // Miscellaneous - //==================================================================== - + /// + /// Miscellaneous + /// [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr diff --git a/src/runtime/typemanager.cs b/src/runtime/typemanager.cs index d6c474f8d..d85bdf9bb 100644 --- a/src/runtime/typemanager.cs +++ b/src/runtime/typemanager.cs @@ -8,11 +8,10 @@ namespace Python.Runtime { - //======================================================================= - // The TypeManager class is responsible for building binary-compatible - // Python type objects that are implemented in managed code. - //======================================================================= - + /// + /// The TypeManager class is responsible for building binary-compatible + /// Python type objects that are implemented in managed code. + /// internal class TypeManager { static BindingFlags tbFlags; @@ -25,13 +24,12 @@ static TypeManager() } - //==================================================================== - // Given a managed Type derived from ExtensionType, get the handle to - // a Python type object that delegates its implementation to the Type - // object. These Python type instances are used to implement internal - // descriptor and utility types like ModuleObject, PropertyObject, etc. - //==================================================================== - + /// + /// Given a managed Type derived from ExtensionType, get the handle to + /// a Python type object that delegates its implementation to the Type + /// object. These Python type instances are used to implement internal + /// descriptor and utility types like ModuleObject, PropertyObject, etc. + /// internal static IntPtr GetTypeHandle(Type type) { // Note that these types are cached with a refcount of 1, so they @@ -48,12 +46,11 @@ internal static IntPtr GetTypeHandle(Type type) } - //==================================================================== - // Get the handle of a Python type that reflects the given CLR type. - // The given ManagedType instance is a managed object that implements - // the appropriate semantics in Python for the reflected managed type. - //==================================================================== - + /// + /// Get the handle of a Python type that reflects the given CLR type. + /// The given ManagedType instance is a managed object that implements + /// the appropriate semantics in Python for the reflected managed type. + /// internal static IntPtr GetTypeHandle(ManagedType obj, Type type) { IntPtr handle = IntPtr.Zero; @@ -68,15 +65,14 @@ internal static IntPtr GetTypeHandle(ManagedType obj, Type type) } - //==================================================================== - // The following CreateType implementations do the necessary work to - // create Python types to represent managed extension types, reflected - // types, subclasses of reflected types and the managed metatype. The - // dance is slightly different for each kind of type due to different - // behavior needed and the desire to have the existing Python runtime - // do as much of the allocation and initialization work as possible. - //==================================================================== - + /// + /// The following CreateType implementations do the necessary work to + /// create Python types to represent managed extension types, reflected + /// types, subclasses of reflected types and the managed metatype. The + /// dance is slightly different for each kind of type due to different + /// behavior needed and the desire to have the existing Python runtime + /// do as much of the allocation and initialization work as possible. + /// internal static IntPtr CreateType(Type impl) { IntPtr type = AllocateTypeObject(impl.Name); @@ -395,10 +391,9 @@ internal static IntPtr BasicSubType(string name, IntPtr base_, Type impl) } - //==================================================================== - // Utility method to allocate a type object & do basic initialization. - //==================================================================== - + /// + /// Utility method to allocate a type object & do basic initialization. + /// internal static IntPtr AllocateTypeObject(string name) { IntPtr type = Runtime.PyType_GenericAlloc(Runtime.PyTypeType, 0); @@ -445,12 +440,11 @@ internal static IntPtr AllocateTypeObject(string name) } - //==================================================================== - // Given a newly allocated Python type object and a managed Type that - // provides the implementation for the type, connect the type slots of - // the Python object to the managed methods of the implementing Type. - //==================================================================== - + /// + /// Given a newly allocated Python type object and a managed Type that + /// provides the implementation for the type, connect the type slots of + /// the Python object to the managed methods of the implementing Type. + /// internal static void InitializeSlots(IntPtr type, Type impl) { Hashtable seen = new Hashtable(8); @@ -492,12 +486,11 @@ internal static void InitializeSlots(IntPtr type, Type impl) } - //==================================================================== - // Given a newly allocated Python type object and a managed Type that - // implements it, initialize any methods defined by the Type that need - // to appear in the Python type __dict__ (based on custom attribute). - //==================================================================== - + /// + /// Given a newly allocated Python type object and a managed Type that + /// implements it, initialize any methods defined by the Type that need + /// to appear in the Python type __dict__ (based on custom attribute). + /// private static void InitMethods(IntPtr pytype, Type type) { IntPtr dict = Marshal.ReadIntPtr(pytype, TypeOffset.tp_dict); @@ -531,10 +524,9 @@ private static void InitMethods(IntPtr pytype, Type type) } - //==================================================================== - // Utility method to copy slots from a given type to another type. - //==================================================================== - + /// + /// Utility method to copy slots from a given type to another type. + /// internal static void CopySlot(IntPtr from, IntPtr to, int offset) { IntPtr fp = Marshal.ReadIntPtr(from, offset); diff --git a/src/runtime/typemethod.cs b/src/runtime/typemethod.cs index 0c60301a0..50577f93d 100644 --- a/src/runtime/typemethod.cs +++ b/src/runtime/typemethod.cs @@ -4,10 +4,9 @@ namespace Python.Runtime { - //======================================================================== - // Implements a Python type that provides access to CLR object methods. - //======================================================================== - + /// + /// Implements a Python type that provides access to CLR object methods. + /// internal class TypeMethod : MethodObject { public TypeMethod(Type type, string name, MethodInfo[] info) : From 82f965b434150f34caf8be515cd5511cc2f87d43 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Feb 2017 23:56:57 -0700 Subject: [PATCH 059/245] Update API website on docs & fix section headers Runtime.cs section headers got changed to docs. --- src/runtime/pydict.cs | 4 +- src/runtime/pyfloat.cs | 4 +- src/runtime/pyint.cs | 4 +- src/runtime/pyiter.cs | 4 +- src/runtime/pylist.cs | 4 +- src/runtime/pylong.cs | 4 +- src/runtime/pynumber.cs | 4 +- src/runtime/pyobject.cs | 4 +- src/runtime/pysequence.cs | 4 +- src/runtime/pystring.cs | 8 ++- src/runtime/pytuple.cs | 4 +- src/runtime/runtime.cs | 103 +++++++++++++++++++++----------------- 12 files changed, 94 insertions(+), 57 deletions(-) diff --git a/src/runtime/pydict.cs b/src/runtime/pydict.cs index 1672df4fe..18f0939b2 100644 --- a/src/runtime/pydict.cs +++ b/src/runtime/pydict.cs @@ -5,7 +5,9 @@ namespace Python.Runtime { /// /// Represents a Python dictionary object. See the documentation at - /// http://www.python.org/doc/current/api/dictObjects.html for details. + /// PY2: https://docs.python.org/2/c-api/dict.html + /// PY3: https://docs.python.org/3/c-api/dict.html + /// for details. /// public class PyDict : PyObject { diff --git a/src/runtime/pyfloat.cs b/src/runtime/pyfloat.cs index bcd5ad23d..959657118 100644 --- a/src/runtime/pyfloat.cs +++ b/src/runtime/pyfloat.cs @@ -5,7 +5,9 @@ namespace Python.Runtime { /// /// Represents a Python float object. See the documentation at - /// http://www.python.org/doc/current/api/floatObjects.html + /// PY2: https://docs.python.org/2/c-api/float.html + /// PY3: https://docs.python.org/3/c-api/float.html + /// for details. /// public class PyFloat : PyNumber { diff --git a/src/runtime/pyint.cs b/src/runtime/pyint.cs index 43f9d02aa..e89c1e87e 100644 --- a/src/runtime/pyint.cs +++ b/src/runtime/pyint.cs @@ -5,7 +5,9 @@ namespace Python.Runtime { /// /// Represents a Python integer object. See the documentation at - /// http://www.python.org/doc/current/api/intObjects.html for details. + /// PY2: https://docs.python.org/2/c-api/int.html + /// PY3: No equivalent + /// for details. /// public class PyInt : PyNumber { diff --git a/src/runtime/pyiter.cs b/src/runtime/pyiter.cs index a2f239ccf..c1bab2781 100644 --- a/src/runtime/pyiter.cs +++ b/src/runtime/pyiter.cs @@ -5,7 +5,9 @@ namespace Python.Runtime { /// /// Represents a standard Python iterator object. See the documentation at - /// http://www.python.org/doc/2.4.4/api/iterator.html for details. + /// PY2: https://docs.python.org/2/c-api/iterator.html + /// PY3: https://docs.python.org/3/c-api/iterator.html + /// for details. /// public class PyIter : PyObject, IEnumerator { diff --git a/src/runtime/pylist.cs b/src/runtime/pylist.cs index 235f39c77..8a369f654 100644 --- a/src/runtime/pylist.cs +++ b/src/runtime/pylist.cs @@ -4,7 +4,9 @@ namespace Python.Runtime { /// /// Represents a standard Python list object. See the documentation at - /// http://www.python.org/doc/current/api/listObjects.html for details. + /// PY2: https://docs.python.org/2/c-api/list.html + /// PY3: https://docs.python.org/3/c-api/list.html + /// for details. /// public class PyList : PySequence { diff --git a/src/runtime/pylong.cs b/src/runtime/pylong.cs index a4ce60279..8deac242e 100644 --- a/src/runtime/pylong.cs +++ b/src/runtime/pylong.cs @@ -4,7 +4,9 @@ namespace Python.Runtime { /// /// Represents a Python long int object. See the documentation at - /// http://www.python.org/doc/current/api/longObjects.html + /// PY2: https://docs.python.org/2/c-api/long.html + /// PY3: https://docs.python.org/3/c-api/long.html + /// for details. /// public class PyLong : PyNumber { diff --git a/src/runtime/pynumber.cs b/src/runtime/pynumber.cs index 14b32b593..73dde6744 100644 --- a/src/runtime/pynumber.cs +++ b/src/runtime/pynumber.cs @@ -5,7 +5,9 @@ namespace Python.Runtime /// /// Represents a generic Python number. The methods of this class are /// equivalent to the Python "abstract number API". See - /// http://www.python.org/doc/current/api/number.html for details. + /// PY2: https://docs.python.org/2/c-api/number.html + /// PY3: https://docs.python.org/3/c-api/number.html + /// for details. /// public class PyNumber : PyObject { diff --git a/src/runtime/pyobject.cs b/src/runtime/pyobject.cs index 19a2f178b..ccebb708e 100644 --- a/src/runtime/pyobject.cs +++ b/src/runtime/pyobject.cs @@ -8,7 +8,9 @@ namespace Python.Runtime /// /// Represents a generic Python object. The methods of this class are /// generally equivalent to the Python "abstract object API". See - /// http://www.python.org/doc/current/api/object.html for details. + /// PY2: https://docs.python.org/2/c-api/object.html + /// PY3: https://docs.python.org/3/c-api/object.html + /// for details. /// public class PyObject : DynamicObject, IDisposable { diff --git a/src/runtime/pysequence.cs b/src/runtime/pysequence.cs index 85101128b..d54959599 100644 --- a/src/runtime/pysequence.cs +++ b/src/runtime/pysequence.cs @@ -6,7 +6,9 @@ namespace Python.Runtime /// /// Represents a generic Python sequence. The methods of this class are /// equivalent to the Python "abstract sequence API". See - /// http://www.python.org/doc/current/api/sequence.html for details. + /// PY2: https://docs.python.org/2/c-api/sequence.html + /// PY3: https://docs.python.org/3/c-api/sequence.html + /// for details. /// public class PySequence : PyObject, IEnumerable { diff --git a/src/runtime/pystring.cs b/src/runtime/pystring.cs index 1fe3a6d7e..39e7a8f96 100644 --- a/src/runtime/pystring.cs +++ b/src/runtime/pystring.cs @@ -4,9 +4,13 @@ namespace Python.Runtime { /// /// Represents a Python (ansi) string object. See the documentation at - /// http://www.python.org/doc/current/api/stringObjects.html for details. - /// 2011-01-29: ...Then why does the string constructor call PyUnicode_FromUnicode()??? + /// PY2: https://docs.python.org/2/c-api/string.html + /// PY3: No Equivalent + /// for details. /// + /// + /// 2011-01-29: ...Then why does the string constructor call PyUnicode_FromUnicode()??? + /// public class PyString : PySequence { /// diff --git a/src/runtime/pytuple.cs b/src/runtime/pytuple.cs index 682ed3f50..76ca616ae 100644 --- a/src/runtime/pytuple.cs +++ b/src/runtime/pytuple.cs @@ -4,7 +4,9 @@ namespace Python.Runtime { /// /// Represents a Python tuple object. See the documentation at - /// http://www.python.org/doc/current/api/tupleObjects.html for details. + /// PY2: https://docs.python.org/2/c-api/tupleObjects.html + /// PY3: https://docs.python.org/3/c-api/tupleObjects.html + /// for details. /// public class PyTuple : PySequence { diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 2c1ab87ab..3757ce6aa 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -88,13 +88,13 @@ static public IntPtr GetProcAddress(IntPtr dllHandle, string name) #endif } + /// + /// Encapsulates the low-level Python C API. Note that it is + /// the responsibility of the caller to have acquired the GIL + /// before calling any of these methods. + /// public class Runtime { - /// - /// Encapsulates the low-level Python C API. Note that it is - /// the responsibility of the caller to have acquired the GIL - /// before calling any of these methods. - /// #if UCS4 public const int UCS = 4; #elif UCS2 @@ -876,14 +876,15 @@ internal unsafe static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); + //==================================================================== + // Python abstract object API + //==================================================================== + /// - /// Python abstract object API - /// - /// /// A macro-like method to get the type of a Python object. This is /// designed to be lean and mean in IL & avoid managed <-> unmanaged /// transitions. Note that this does not incref the type object. - /// + /// internal unsafe static IntPtr PyObject_TYPE(IntPtr op) { @@ -1089,9 +1090,10 @@ internal unsafe static extern IntPtr PyObject_Dir(IntPtr pointer); - /// - /// Python number API - /// + //==================================================================== + // Python number API + //==================================================================== + #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyNumber_Long", @@ -1393,9 +1395,10 @@ internal unsafe static extern IntPtr internal unsafe static extern IntPtr PyNumber_Invert(IntPtr o1); - /// - /// Python sequence API - /// + //==================================================================== + // Python sequence API + //==================================================================== + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern bool @@ -1472,9 +1475,10 @@ internal unsafe static extern IntPtr PySequence_List(IntPtr pointer); - /// - /// Python string API - /// + //==================================================================== + // Python string API + //==================================================================== + internal static bool IsStringType(IntPtr op) { IntPtr t = PyObject_TYPE(op); @@ -1766,9 +1770,10 @@ internal unsafe static string GetManagedString(IntPtr op) return null; } - /// - /// Python dictionary API - /// + //==================================================================== + // Python dictionary API + //==================================================================== + internal static bool PyDict_Check(IntPtr ob) { return PyObject_TYPE(ob) == Runtime.PyDictType; @@ -1855,9 +1860,10 @@ internal unsafe static extern int PyDict_Size(IntPtr pointer); - /// - /// Python list API - /// + //==================================================================== + // Python list API + //==================================================================== + internal static bool PyList_Check(IntPtr ob) { return PyObject_TYPE(ob) == Runtime.PyListType; @@ -1919,9 +1925,10 @@ internal unsafe static extern int PyList_Size(IntPtr pointer); - /// - /// Python tuple API - /// + //==================================================================== + // Python tuple API + //==================================================================== + internal static bool PyTuple_Check(IntPtr ob) { return PyObject_TYPE(ob) == Runtime.PyTupleType; @@ -1953,9 +1960,10 @@ internal unsafe static extern int PyTuple_Size(IntPtr pointer); - /// - /// Python iterator API - /// + //==================================================================== + // Python iterator API + //==================================================================== + #if PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -1976,9 +1984,10 @@ internal static bool internal unsafe static extern IntPtr PyIter_Next(IntPtr pointer); - /// - /// Python module API - /// + //==================================================================== + // Python module API + //==================================================================== + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr @@ -2062,9 +2071,10 @@ internal unsafe static extern int PySys_SetObject(string name, IntPtr ob); - /// - /// Python type object API - /// + //==================================================================== + // Python type object API + //==================================================================== + internal static bool PyType_Check(IntPtr ob) { return PyObject_TypeCheck(ob, Runtime.PyTypeType); @@ -2142,9 +2152,10 @@ internal unsafe static extern void PyObject_GC_UnTrack(IntPtr tp); - /// - /// Python memory API - /// + //==================================================================== + // Python memory API + //==================================================================== + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr @@ -2161,9 +2172,10 @@ internal unsafe static extern void PyMem_Free(IntPtr ptr); - /// - /// Python exception API - /// + //==================================================================== + // Python exception API + //==================================================================== + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern void @@ -2225,9 +2237,10 @@ internal unsafe static extern void PyErr_Print(); - /// - /// Miscellaneous - /// + //==================================================================== + // Miscellaneous + //==================================================================== + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr From 26ce7d8badb50f5dbee937c26070fd3855977fd4 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Feb 2017 11:17:47 -0700 Subject: [PATCH 060/245] Alias root.pyHandle to py_clr_module --- src/runtime/importhook.cs | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index 68d81ac14..255be0d5a 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -12,9 +12,9 @@ internal class ImportHook static IntPtr py_import; static CLRModule root; static MethodWrapper hook; + static IntPtr py_clr_module; #if PYTHON3 - static IntPtr py_clr_module; static IntPtr module_def = IntPtr.Zero; internal static void InitializeModuleDef() @@ -36,11 +36,10 @@ internal static void Initialize() IntPtr dict = Runtime.PyImport_GetModuleDict(); #if PYTHON3 IntPtr mod = Runtime.PyImport_ImportModule("builtins"); - py_import = Runtime.PyObject_GetAttrString(mod, "__import__"); #elif PYTHON2 IntPtr mod = Runtime.PyDict_GetItemString(dict, "__builtin__"); - py_import = Runtime.PyObject_GetAttrString(mod, "__import__"); #endif + py_import = Runtime.PyObject_GetAttrString(mod, "__import__"); hook = new MethodWrapper(typeof(ImportHook), "__import__", "TernaryFunc"); Runtime.PyObject_SetAttrString(mod, "__import__", hook.ptr); Runtime.XDecref(hook.ptr); @@ -58,13 +57,12 @@ internal static void Initialize() clr_dict = (IntPtr)Marshal.PtrToStructure(clr_dict, typeof(IntPtr)); Runtime.PyDict_Update(mod_dict, clr_dict); - Runtime.PyDict_SetItemString(dict, "CLR", py_clr_module); - Runtime.PyDict_SetItemString(dict, "clr", py_clr_module); #elif PYTHON2 Runtime.XIncref(root.pyHandle); // we are using the module two times - Runtime.PyDict_SetItemString(dict, "CLR", root.pyHandle); - Runtime.PyDict_SetItemString(dict, "clr", root.pyHandle); + py_clr_module = root.pyHandle; // Alias handle for PY2/PY3 #endif + Runtime.PyDict_SetItemString(dict, "CLR", py_clr_module); + Runtime.PyDict_SetItemString(dict, "clr", py_clr_module); } @@ -75,11 +73,7 @@ internal static void Shutdown() { if (0 != Runtime.Py_IsInitialized()) { -#if PYTHON3 Runtime.XDecref(py_clr_module); -#elif PYTHON2 - Runtime.XDecref(root.pyHandle); -#endif Runtime.XDecref(root.pyHandle); Runtime.XDecref(py_import); } @@ -134,13 +128,9 @@ public static IntPtr GetCLRModule(IntPtr? fromList = null) } } } - +#endif Runtime.XIncref(py_clr_module); return py_clr_module; -#elif PYTHON2 - Runtime.XIncref(root.pyHandle); - return root.pyHandle; -#endif } /// From 0e74f869ad1e6423b3680858f9e43144fb75271a Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Feb 2017 11:57:51 -0700 Subject: [PATCH 061/245] Syntax cleanup --- src/runtime/importhook.cs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index 255be0d5a..e5843d436 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -71,7 +71,7 @@ internal static void Initialize() /// internal static void Shutdown() { - if (0 != Runtime.Py_IsInitialized()) + if (Runtime.Py_IsInitialized() != 0) { Runtime.XDecref(py_clr_module); Runtime.XDecref(root.pyHandle); @@ -111,11 +111,11 @@ public static IntPtr GetCLRModule(IntPtr? fromList = null) continue; string s = item.AsManagedObject(typeof(string)) as string; - if (null == s) + if (s == null) continue; ManagedType attr = root.GetAttribute(s, true); - if (null == attr) + if (attr == null) continue; Runtime.XIncref(attr.pyHandle); @@ -190,7 +190,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) } if (mod_name == "CLR") { - Exceptions.deprecation("The CLR module is deprecated. " + "Please use 'clr'."); + Exceptions.deprecation("The CLR module is deprecated. Please use 'clr'."); IntPtr clr_module = GetCLRModule(fromList); if (clr_module != IntPtr.Zero) { @@ -305,9 +305,8 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) ModuleObject tail = root; root.InitializePreload(); - for (int i = 0; i < names.Length; i++) + foreach (string name in names) { - string name = names[i]; ManagedType mt = tail.GetAttribute(name, true); if (!(mt is ModuleObject)) { From 7cf4ba96f76e5fa7546af374cf4c38f3bdcdba56 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Feb 2017 09:47:44 -0700 Subject: [PATCH 062/245] Simple classes cleanup (#348) --- src/runtime/arrayobject.cs | 44 ++++++++++----------- src/runtime/assemblymanager.cs | 55 +++++++++++++-------------- src/runtime/classbase.cs | 20 +++++----- src/runtime/clrobject.cs | 24 ++++++------ src/runtime/codegenerator.cs | 12 ++---- src/runtime/constructorbinder.cs | 14 +++---- src/runtime/debughelper.cs | 27 ++++++------- src/runtime/delegateobject.cs | 14 +++---- src/runtime/extensiontype.cs | 17 ++++----- src/runtime/fieldobject.cs | 31 +++++++-------- src/runtime/generictype.cs | 1 - src/runtime/genericutil.cs | 8 +++- src/runtime/importhook.cs | 20 +++++----- src/runtime/interfaceobject.cs | 12 +++--- src/runtime/interfaces.cs | 2 - src/runtime/iterator.cs | 7 ++-- src/runtime/managedtype.cs | 10 ++--- src/runtime/methodwrapper.cs | 2 - src/runtime/modulefunctionobject.cs | 18 ++++----- src/runtime/modulepropertyobject.cs | 4 +- src/runtime/monosupport.cs | 6 +-- src/runtime/nativecall.cs | 27 ++++++------- src/runtime/overload.cs | 17 ++++----- src/runtime/propertyobject.cs | 33 ++++++++-------- src/runtime/pyansistring.cs | 4 +- src/runtime/pydict.cs | 11 +++--- src/runtime/pyfloat.cs | 9 ++--- src/runtime/pyint.cs | 13 +++---- src/runtime/pyiter.cs | 8 +++- src/runtime/pylist.cs | 8 ++-- src/runtime/pylong.cs | 38 +++++++++---------- src/runtime/pynumber.cs | 2 +- src/runtime/pysequence.cs | 4 +- src/runtime/pystring.cs | 4 +- src/runtime/pythonexception.cs | 10 ++--- src/runtime/pytuple.cs | 8 ++-- src/runtime/typemanager.cs | 59 +++++++++++++++-------------- src/runtime/typemethod.cs | 6 +-- 38 files changed, 290 insertions(+), 319 deletions(-) diff --git a/src/runtime/arrayobject.cs b/src/runtime/arrayobject.cs index 6096706dd..caf40ca50 100644 --- a/src/runtime/arrayobject.cs +++ b/src/runtime/arrayobject.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Reflection; namespace Python.Runtime { @@ -22,13 +21,13 @@ internal override bool CanSubclass() public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { - ArrayObject self = GetManagedObject(tp) as ArrayObject; + var self = GetManagedObject(tp) as ArrayObject; if (Runtime.PyTuple_Size(args) != 1) { return Exceptions.RaiseTypeError("array expects 1 argument"); } IntPtr op = Runtime.PyTuple_GetItem(args, 0); - Object result; + object result; if (!Converter.ToManaged(op, self.type, out result, true)) { @@ -43,11 +42,11 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) /// public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) { - CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob); - Array items = obj.inst as Array; + var obj = (CLRObject)GetManagedObject(ob); + var items = obj.inst as Array; Type itemType = obj.inst.GetType().GetElementType(); int rank = items.Rank; - int index = 0; + int index; object value; // Note that CLR 1.0 only supports int indexes - methods to @@ -61,7 +60,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) if (rank == 1) { - index = (int)Runtime.PyInt_AsLong(idx); + index = Runtime.PyInt_AsLong(idx); if (Exceptions.ErrorOccurred()) { @@ -83,7 +82,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) return IntPtr.Zero; } - return Converter.ToPython(items.GetValue(index), itemType); + return Converter.ToPython(value, itemType); } // Multi-dimensional arrays can be indexed a la: list[1, 2, 3]. @@ -96,12 +95,12 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) int count = Runtime.PyTuple_Size(idx); - Array args = Array.CreateInstance(typeof(Int32), count); + var args = new int[count]; - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr op = Runtime.PyTuple_GetItem(idx, i); - index = (int)Runtime.PyInt_AsLong(op); + index = Runtime.PyInt_AsLong(op); if (Exceptions.ErrorOccurred()) { @@ -135,11 +134,11 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) /// public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) { - CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob); - Array items = obj.inst as Array; + var obj = (CLRObject)GetManagedObject(ob); + var items = obj.inst as Array; Type itemType = obj.inst.GetType().GetElementType(); int rank = items.Rank; - int index = 0; + int index; object value; if (items.IsReadOnly) @@ -155,7 +154,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) if (rank == 1) { - index = (int)Runtime.PyInt_AsLong(idx); + index = Runtime.PyInt_AsLong(idx); if (Exceptions.ErrorOccurred()) { @@ -188,13 +187,12 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) } int count = Runtime.PyTuple_Size(idx); + var args = new int[count]; - Array args = Array.CreateInstance(typeof(Int32), count); - - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr op = Runtime.PyTuple_GetItem(idx, i); - index = (int)Runtime.PyInt_AsLong(op); + index = Runtime.PyInt_AsLong(op); if (Exceptions.ErrorOccurred()) { @@ -229,9 +227,9 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) /// public static int sq_contains(IntPtr ob, IntPtr v) { - CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob); + var obj = (CLRObject)GetManagedObject(ob); Type itemType = obj.inst.GetType().GetElementType(); - IList items = obj.inst as IList; + var items = obj.inst as IList; object value; if (!Converter.ToManaged(v, itemType, out value, false)) @@ -253,8 +251,8 @@ public static int sq_contains(IntPtr ob, IntPtr v) /// public static int mp_length(IntPtr ob) { - CLRObject self = (CLRObject)ManagedType.GetManagedObject(ob); - Array items = self.inst as Array; + var self = (CLRObject)GetManagedObject(ob); + var items = self.inst as Array; return items.Length; } } diff --git a/src/runtime/assemblymanager.cs b/src/runtime/assemblymanager.cs index b98455ec3..29851c32e 100644 --- a/src/runtime/assemblymanager.cs +++ b/src/runtime/assemblymanager.cs @@ -21,8 +21,10 @@ internal class AssemblyManager //static Dictionary> generics; static AssemblyLoadEventHandler lhandler; static ResolveEventHandler rhandler; + // updated only under GIL? static Dictionary probed; + // modified from event handlers below, potentially triggered from different .NET threads static AssemblyList assemblies; internal static List pypath; @@ -53,7 +55,7 @@ internal static void Initialize() domain.AssemblyResolve += rhandler; Assembly[] items = domain.GetAssemblies(); - foreach (var a in items) + foreach (Assembly a in items) { try { @@ -62,7 +64,7 @@ internal static void Initialize() } catch (Exception ex) { - Debug.WriteLine(string.Format("Error scanning assembly {0}. {1}", a, ex)); + Debug.WriteLine("Error scanning assembly {0}. {1}", a, ex); } } } @@ -86,7 +88,7 @@ internal static void Shutdown() /// so that we can know about assemblies that get loaded after the /// Python runtime is initialized. /// - static void AssemblyLoadHandler(Object ob, AssemblyLoadEventArgs args) + private static void AssemblyLoadHandler(object ob, AssemblyLoadEventArgs args) { Assembly assembly = args.LoadedAssembly; assemblies.Add(assembly); @@ -101,7 +103,7 @@ static void AssemblyLoadHandler(Object ob, AssemblyLoadEventArgs args) /// for failed loads, because they might be dependencies of something /// we loaded from Python which also needs to be found on PYTHONPATH. /// - static Assembly ResolveHandler(Object ob, ResolveEventArgs args) + private static Assembly ResolveHandler(object ob, ResolveEventArgs args) { string name = args.Name.ToLower(); foreach (Assembly a in assemblies) @@ -135,7 +137,7 @@ internal static void UpdatePath() { pypath.Clear(); probed.Clear(); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr item = Runtime.PyList_GetItem(list, i); string path = Runtime.GetManagedString(item); @@ -159,7 +161,7 @@ public static string FindAssembly(string name) string path; string temp; - for (int i = 0; i < pypath.Count; i++) + for (var i = 0; i < pypath.Count; i++) { string head = pypath[i]; if (head == null || head.Length == 0) @@ -197,7 +199,7 @@ public static Assembly LoadAssembly(string name) { assembly = Assembly.Load(name); } - catch (System.Exception) + catch (Exception) { //if (!(e is System.IO.FileNotFoundException)) //{ @@ -221,7 +223,7 @@ public static Assembly LoadAssemblyPath(string name) { assembly = Assembly.LoadFrom(path); } - catch + catch (Exception) { } } @@ -241,7 +243,9 @@ public static Assembly LoadAssemblyFullPath(string name) if (Path.IsPathRooted(name)) { if (!Path.HasExtension(name)) + { name = name + ".dll"; + } if (File.Exists(name)) { try @@ -287,13 +291,13 @@ public static Assembly FindLoadedAssembly(string name) public static bool LoadImplicit(string name, bool warn = true) { string[] names = name.Split('.'); - bool loaded = false; - string s = ""; + var loaded = false; + var s = ""; Assembly lastAssembly = null; HashSet assembliesSet = null; - for (int i = 0; i < names.Length; i++) + for (var i = 0; i < names.Length; i++) { - s = (i == 0) ? names[0] : s + "." + names[i]; + s = i == 0 ? names[0] : s + "." + names[i]; if (!probed.ContainsKey(s)) { if (assembliesSet == null) @@ -321,7 +325,7 @@ public static bool LoadImplicit(string name, bool warn = true) // Deprecation warning if (warn && loaded) { - string deprWarning = String.Format( + string deprWarning = string.Format( "\nThe module was found, but not in a referenced namespace.\n" + "Implicit loading is deprecated. Please use clr.AddReference(\"{0}\").", Path.GetFileNameWithoutExtension(lastAssembly.Location)); @@ -345,24 +349,23 @@ internal static void ScanAssembly(Assembly assembly) // the assembly. Type[] types = assembly.GetTypes(); - for (int i = 0; i < types.Length; i++) + foreach (Type t in types) { - Type t = types[i]; string ns = t.Namespace ?? ""; if (!namespaces.ContainsKey(ns)) { string[] names = ns.Split('.'); - string s = ""; - for (int n = 0; n < names.Length; n++) + var s = ""; + for (var n = 0; n < names.Length; n++) { - s = (n == 0) ? names[0] : s + "." + names[n]; + s = n == 0 ? names[0] : s + "." + names[n]; namespaces.TryAdd(s, new ConcurrentDictionary()); } } if (ns != null) { - namespaces[ns].TryAdd(assembly, String.Empty); + namespaces[ns].TryAdd(assembly, string.Empty); } if (ns != null && t.IsGenericTypeDefinition) @@ -374,7 +377,7 @@ internal static void ScanAssembly(Assembly assembly) public static AssemblyName[] ListAssemblies() { - List names = new List(assemblies.Count); + var names = new List(assemblies.Count); foreach (Assembly assembly in assemblies) { names.Add(assembly.GetName()); @@ -388,7 +391,7 @@ public static AssemblyName[] ListAssemblies() /// public static bool IsValidNamespace(string name) { - return !String.IsNullOrEmpty(name) && namespaces.ContainsKey(name); + return !string.IsNullOrEmpty(name) && namespaces.ContainsKey(name); } /// @@ -396,10 +399,7 @@ public static bool IsValidNamespace(string name) /// public static IEnumerable GetAssemblies(string nsname) { - if (!namespaces.ContainsKey(nsname)) - return new List(); - - return namespaces[nsname].Keys; + return !namespaces.ContainsKey(nsname) ? new List() : namespaces[nsname].Keys; } /// @@ -408,7 +408,7 @@ public static IEnumerable GetAssemblies(string nsname) public static List GetNames(string nsname) { //Dictionary seen = new Dictionary(); - List names = new List(8); + var names = new List(8); List g = GenericUtil.GetGenericBaseNames(nsname); if (g != null) @@ -424,9 +424,8 @@ public static List GetNames(string nsname) foreach (Assembly a in namespaces[nsname].Keys) { Type[] types = a.GetTypes(); - for (int i = 0; i < types.Length; i++) + foreach (Type t in types) { - Type t = types[i]; if ((t.Namespace ?? "") == nsname) { names.Add(t.Name); diff --git a/src/runtime/classbase.cs b/src/runtime/classbase.cs index 6ed43689b..580fcabe4 100644 --- a/src/runtime/classbase.cs +++ b/src/runtime/classbase.cs @@ -19,7 +19,7 @@ internal class ClassBase : ManagedType internal Indexer indexer; internal Type type; - internal ClassBase(Type tp) : base() + internal ClassBase(Type tp) { indexer = null; type = tp; @@ -97,10 +97,10 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) return pyfalse; } - Object o1 = co1.inst; - Object o2 = co2.inst; + object o1 = co1.inst; + object o2 = co2.inst; - if (Object.Equals(o1, o2)) + if (Equals(o1, o2)) { Runtime.XIncref(pytrue); return pytrue; @@ -121,7 +121,7 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) return Exceptions.RaiseTypeError("Cannot convert object of type " + co1.GetType() + " to IComparable"); try { - var cmp = co1Comp.CompareTo(co2.inst); + int cmp = co1Comp.CompareTo(co2.inst); IntPtr pyCmp; if (cmp < 0) @@ -177,13 +177,13 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) /// public static IntPtr tp_iter(IntPtr ob) { - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { return Exceptions.RaiseTypeError("invalid object"); } - IEnumerable e = co.inst as IEnumerable; + var e = co.inst as IEnumerable; IEnumerator o; if (e != null) @@ -196,7 +196,7 @@ public static IntPtr tp_iter(IntPtr ob) if (o == null) { - string message = "iteration over non-sequence"; + var message = "iteration over non-sequence"; return Exceptions.RaiseTypeError(message); } } @@ -210,7 +210,7 @@ public static IntPtr tp_iter(IntPtr ob) /// public static IntPtr tp_hash(IntPtr ob) { - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { return Exceptions.RaiseTypeError("unhashable type"); @@ -224,7 +224,7 @@ public static IntPtr tp_hash(IntPtr ob) /// public static IntPtr tp_str(IntPtr ob) { - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { return Exceptions.RaiseTypeError("invalid object"); diff --git a/src/runtime/clrobject.cs b/src/runtime/clrobject.cs index e7bb345f8..472e5dcbb 100644 --- a/src/runtime/clrobject.cs +++ b/src/runtime/clrobject.cs @@ -1,19 +1,17 @@ using System; -using System.Collections; -using System.Reflection; using System.Runtime.InteropServices; namespace Python.Runtime { internal class CLRObject : ManagedType { - internal Object inst; + internal object inst; - internal CLRObject(Object ob, IntPtr tp) : base() + internal CLRObject(object ob, IntPtr tp) { IntPtr py = Runtime.PyType_GenericAlloc(tp, 0); - int flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); + var flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Subclass) != 0) { IntPtr dict = Marshal.ReadIntPtr(py, ObjectOffset.DictOffset(tp)); @@ -26,9 +24,9 @@ internal CLRObject(Object ob, IntPtr tp) : base() GCHandle gc = GCHandle.Alloc(this); Marshal.WriteIntPtr(py, ObjectOffset.magic(tp), (IntPtr)gc); - this.tpHandle = tp; - this.pyHandle = py; - this.gcHandle = gc; + tpHandle = tp; + pyHandle = py; + gcHandle = gc; inst = ob; // Fix the BaseException args (and __cause__ in case of Python 3) @@ -37,27 +35,27 @@ internal CLRObject(Object ob, IntPtr tp) : base() } - internal static CLRObject GetInstance(Object ob, IntPtr pyType) + internal static CLRObject GetInstance(object ob, IntPtr pyType) { return new CLRObject(ob, pyType); } - internal static CLRObject GetInstance(Object ob) + internal static CLRObject GetInstance(object ob) { ClassBase cc = ClassManager.GetClass(ob.GetType()); return GetInstance(ob, cc.tpHandle); } - internal static IntPtr GetInstHandle(Object ob, IntPtr pyType) + internal static IntPtr GetInstHandle(object ob, IntPtr pyType) { CLRObject co = GetInstance(ob, pyType); return co.pyHandle; } - internal static IntPtr GetInstHandle(Object ob, Type type) + internal static IntPtr GetInstHandle(object ob, Type type) { ClassBase cc = ClassManager.GetClass(type); CLRObject co = GetInstance(ob, cc.tpHandle); @@ -65,7 +63,7 @@ internal static IntPtr GetInstHandle(Object ob, Type type) } - internal static IntPtr GetInstHandle(Object ob) + internal static IntPtr GetInstHandle(object ob) { CLRObject co = GetInstance(ob); return co.pyHandle; diff --git a/src/runtime/codegenerator.cs b/src/runtime/codegenerator.cs index d592843cb..4620b0f0c 100644 --- a/src/runtime/codegenerator.cs +++ b/src/runtime/codegenerator.cs @@ -1,8 +1,5 @@ using System; using System.Threading; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Collections; using System.Reflection; using System.Reflection.Emit; @@ -21,9 +18,8 @@ internal class CodeGenerator internal CodeGenerator() { - AssemblyName aname = new AssemblyName(); - aname.Name = "__CodeGenerator_Assembly"; - AssemblyBuilderAccess aa = AssemblyBuilderAccess.Run; + var aname = new AssemblyName { Name = "__CodeGenerator_Assembly" }; + var aa = AssemblyBuilderAccess.Run; aBuilder = Thread.GetDomain().DefineDynamicAssembly(aname, aa); mBuilder = aBuilder.DefineDynamicModule("__CodeGenerator_Module"); @@ -34,7 +30,7 @@ internal CodeGenerator() /// internal TypeBuilder DefineType(string name) { - TypeAttributes attrs = TypeAttributes.Public; + var attrs = TypeAttributes.Public; return mBuilder.DefineType(name, attrs); } @@ -43,7 +39,7 @@ internal TypeBuilder DefineType(string name) /// internal TypeBuilder DefineType(string name, Type basetype) { - TypeAttributes attrs = TypeAttributes.Public; + var attrs = TypeAttributes.Public; return mBuilder.DefineType(name, attrs, basetype); } } diff --git a/src/runtime/constructorbinder.cs b/src/runtime/constructorbinder.cs index 400a0dd54..1fc541920 100644 --- a/src/runtime/constructorbinder.cs +++ b/src/runtime/constructorbinder.cs @@ -12,9 +12,9 @@ namespace Python.Runtime /// internal class ConstructorBinder : MethodBinder { - private Type _containingType = null; + private Type _containingType; - internal ConstructorBinder(Type containingType) : base() + internal ConstructorBinder(Type containingType) { _containingType = containingType; } @@ -29,7 +29,7 @@ internal ConstructorBinder(Type containingType) : base() /// internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw) { - return this.InvokeRaw(inst, args, kw, null); + return InvokeRaw(inst, args, kw, null); } /// @@ -49,7 +49,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw) /// internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) { - Object result; + object result; if (_containingType.IsValueType && !_containingType.IsPrimitive && !_containingType.IsEnum && _containingType != typeof(decimal) && @@ -76,7 +76,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) return result; } - Binding binding = this.Bind(inst, args, kw, info); + Binding binding = Bind(inst, args, kw, info); if (binding == null) { @@ -88,7 +88,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) // any extra args are intended for the subclass' __init__. IntPtr eargs = Runtime.PyTuple_New(0); - binding = this.Bind(inst, eargs, kw); + binding = Bind(inst, eargs, kw); Runtime.XDecref(eargs); if (binding == null) @@ -99,7 +99,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) } // Fire the selected ctor and catch errors... - ConstructorInfo ci = (ConstructorInfo)binding.info; + var ci = (ConstructorInfo)binding.info; // Object construction is presumed to be non-blocking and fast // enough that we shouldn't really need to release the GIL. try diff --git a/src/runtime/debughelper.cs b/src/runtime/debughelper.cs index 94dd026f6..f42ad2e37 100644 --- a/src/runtime/debughelper.cs +++ b/src/runtime/debughelper.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Reflection; using System.Runtime.InteropServices; using System.Diagnostics; @@ -20,19 +19,18 @@ public static void Print(string msg, params IntPtr[] args) string result = msg; result += " "; - for (int i = 0; i < args.Length; i++) + foreach (IntPtr t in args) { - if (args[i] == IntPtr.Zero) + if (t == IntPtr.Zero) { Console.WriteLine("null arg to print"); } - IntPtr ob = Runtime.PyObject_Repr(args[i]); + IntPtr ob = Runtime.PyObject_Repr(t); result += Runtime.GetManagedString(ob); Runtime.XDecref(ob); result += " "; } Console.WriteLine(result); - return; } [Conditional("DEBUG")] @@ -50,13 +48,13 @@ internal static void DumpType(IntPtr type) Console.WriteLine("Dump type: {0}", name); op = Marshal.ReadIntPtr(type, TypeOffset.ob_type); - DebugUtil.Print(" type: ", op); + Print(" type: ", op); op = Marshal.ReadIntPtr(type, TypeOffset.tp_base); - DebugUtil.Print(" base: ", op); + Print(" base: ", op); op = Marshal.ReadIntPtr(type, TypeOffset.tp_bases); - DebugUtil.Print(" bases: ", op); + Print(" bases: ", op); //op = Marshal.ReadIntPtr(type, TypeOffset.tp_mro); //DebugUtil.Print(" mro: ", op); @@ -65,7 +63,7 @@ internal static void DumpType(IntPtr type) FieldInfo[] slots = typeof(TypeOffset).GetFields(); int size = IntPtr.Size; - for (int i = 0; i < slots.Length; i++) + for (var i = 0; i < slots.Length; i++) { int offset = i * size; name = slots[i].Name; @@ -83,7 +81,7 @@ internal static void DumpType(IntPtr type) } else { - DebugUtil.Print(" dict: ", op); + Print(" dict: ", op); } } @@ -91,11 +89,11 @@ internal static void DumpType(IntPtr type) internal static void DumpInst(IntPtr ob) { IntPtr tp = Runtime.PyObject_TYPE(ob); - int sz = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_basicsize); + var sz = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_basicsize); - for (int i = 0; i < sz; i += IntPtr.Size) + for (var i = 0; i < sz; i += IntPtr.Size) { - IntPtr pp = new IntPtr(ob.ToInt64() + i); + var pp = new IntPtr(ob.ToInt64() + i); IntPtr v = Marshal.ReadIntPtr(pp); Console.WriteLine("offset {0}: {1}", i, v); } @@ -107,7 +105,7 @@ internal static void DumpInst(IntPtr ob) [Conditional("DEBUG")] internal static void debug(string msg) { - StackTrace st = new StackTrace(1, true); + var st = new StackTrace(1, true); StackFrame sf = st.GetFrame(0); MethodBase mb = sf.GetMethod(); Type mt = mb.DeclaringType; @@ -116,7 +114,6 @@ internal static void debug(string msg) string tid = t.GetHashCode().ToString(); Console.WriteLine("thread {0} : {1}", tid, caller); Console.WriteLine(" {0}", msg); - return; } } } diff --git a/src/runtime/delegateobject.cs b/src/runtime/delegateobject.cs index 2d305e5f2..ff64ff094 100644 --- a/src/runtime/delegateobject.cs +++ b/src/runtime/delegateobject.cs @@ -26,10 +26,10 @@ internal DelegateObject(Type tp) : base(tp) /// private static Delegate GetTrueDelegate(IntPtr op) { - CLRObject o = GetManagedObject(op) as CLRObject; + var o = GetManagedObject(op) as CLRObject; if (o != null) { - Delegate d = o.inst as Delegate; + var d = o.inst as Delegate; return d; } return null; @@ -51,11 +51,11 @@ internal override bool CanSubclass() /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { - DelegateObject self = (DelegateObject)GetManagedObject(tp); + var self = (DelegateObject)GetManagedObject(tp); if (Runtime.PyTuple_Size(args) != 1) { - string message = "class takes exactly one argument"; + var message = "class takes exactly one argument"; return Exceptions.RaiseTypeError(message); } @@ -78,15 +78,15 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { // todo: add fast type check! IntPtr pytype = Runtime.PyObject_TYPE(ob); - DelegateObject self = (DelegateObject)GetManagedObject(pytype); - CLRObject o = GetManagedObject(ob) as CLRObject; + var self = (DelegateObject)GetManagedObject(pytype); + var o = GetManagedObject(ob) as CLRObject; if (o == null) { return Exceptions.RaiseTypeError("invalid argument"); } - Delegate d = o.inst as Delegate; + var d = o.inst as Delegate; if (d == null) { diff --git a/src/runtime/extensiontype.cs b/src/runtime/extensiontype.cs index a09f57696..37ab11239 100644 --- a/src/runtime/extensiontype.cs +++ b/src/runtime/extensiontype.cs @@ -1,7 +1,5 @@ using System; using System.Runtime.InteropServices; -using System.Collections; -using System.Reflection; namespace Python.Runtime { @@ -12,14 +10,14 @@ namespace Python.Runtime /// internal abstract class ExtensionType : ManagedType { - public ExtensionType() : base() + public ExtensionType() { // Create a new PyObject whose type is a generated type that is // implemented by the particuar concrete ExtensionType subclass. // The Python instance object is related to an instance of a // particular concrete subclass with a hidden CLR gchandle. - IntPtr tp = TypeManager.GetTypeHandle(this.GetType()); + IntPtr tp = TypeManager.GetTypeHandle(GetType()); //int rc = (int)Marshal.ReadIntPtr(tp, TypeOffset.ob_refcnt); //if (rc > 1050) @@ -40,9 +38,9 @@ public ExtensionType() : base() Runtime.PyObject_GC_UnTrack(py); - this.tpHandle = tp; - this.pyHandle = py; - this.gcHandle = gc; + tpHandle = tp; + pyHandle = py; + gcHandle = gc; } @@ -62,7 +60,7 @@ public static void FinalizeObject(ManagedType self) /// public static int tp_setattro(IntPtr ob, IntPtr key, IntPtr val) { - string message = "type does not support setting attributes"; + var message = "type does not support setting attributes"; if (val == IntPtr.Zero) { message = "readonly attribute"; @@ -78,8 +76,7 @@ public static int tp_setattro(IntPtr ob, IntPtr key, IntPtr val) /// public static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { - string message = "attribute is read-only"; - Exceptions.SetError(Exceptions.AttributeError, message); + Exceptions.SetError(Exceptions.AttributeError, "attribute is read-only"); return -1; } diff --git a/src/runtime/fieldobject.cs b/src/runtime/fieldobject.cs index 3d65f5fd3..6eefb5b0a 100644 --- a/src/runtime/fieldobject.cs +++ b/src/runtime/fieldobject.cs @@ -1,7 +1,5 @@ using System; -using System.Collections; using System.Reflection; -using System.Runtime.InteropServices; namespace Python.Runtime { @@ -12,7 +10,7 @@ internal class FieldObject : ExtensionType { FieldInfo info; - public FieldObject(FieldInfo info) : base() + public FieldObject(FieldInfo info) { this.info = info; } @@ -24,8 +22,8 @@ public FieldObject(FieldInfo info) : base() /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { - FieldObject self = (FieldObject)GetManagedObject(ds); - Object result; + var self = (FieldObject)GetManagedObject(ds); + object result; if (self == null) { @@ -34,12 +32,12 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) FieldInfo info = self.info; - if ((ob == IntPtr.Zero) || (ob == Runtime.PyNone)) + if (ob == IntPtr.Zero || ob == Runtime.PyNone) { if (!info.IsStatic) { Exceptions.SetError(Exceptions.TypeError, - "instance attribute must be accessed " + "through a class instance"); + "instance attribute must be accessed through a class instance"); return IntPtr.Zero; } try @@ -56,7 +54,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) try { - CLRObject co = (CLRObject)GetManagedObject(ob); + var co = (CLRObject)GetManagedObject(ob); result = info.GetValue(co.inst); return Converter.ToPython(result, info.FieldType); } @@ -72,10 +70,10 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// a field based on the given Python value. The Python value must be /// convertible to the type of the field. /// - public static new int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) + public new static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { - FieldObject self = (FieldObject)GetManagedObject(ds); - Object newval; + var self = (FieldObject)GetManagedObject(ds); + object newval; if (self == null) { @@ -98,12 +96,11 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) bool is_static = info.IsStatic; - if ((ob == IntPtr.Zero) || (ob == Runtime.PyNone)) + if (ob == IntPtr.Zero || ob == Runtime.PyNone) { if (!is_static) { - Exceptions.SetError(Exceptions.TypeError, - "instance attribute must be set " + "through a class instance"); + Exceptions.SetError(Exceptions.TypeError, "instance attribute must be set through a class instance"); return -1; } } @@ -117,7 +114,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { if (!is_static) { - CLRObject co = (CLRObject)GetManagedObject(ob); + var co = (CLRObject)GetManagedObject(ob); info.SetValue(co.inst, newval); } else @@ -138,8 +135,8 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// public static IntPtr tp_repr(IntPtr ob) { - FieldObject self = (FieldObject)GetManagedObject(ob); - string s = String.Format("", self.info.Name); + var self = (FieldObject)GetManagedObject(ob); + string s = $""; return Runtime.PyString_FromStringAndSize(s, s.Length); } } diff --git a/src/runtime/generictype.cs b/src/runtime/generictype.cs index 761efc045..eeae801d2 100644 --- a/src/runtime/generictype.cs +++ b/src/runtime/generictype.cs @@ -1,5 +1,4 @@ using System; -using System.Reflection; namespace Python.Runtime { diff --git a/src/runtime/genericutil.cs b/src/runtime/genericutil.cs index 6568ac438..d1de1c374 100644 --- a/src/runtime/genericutil.cs +++ b/src/runtime/genericutil.cs @@ -30,7 +30,9 @@ static GenericUtil() internal static void Register(Type t) { if (null == t.Namespace || null == t.Name) + { return; + } Dictionary> nsmap = null; mapping.TryGetValue(t.Namespace, out nsmap); @@ -66,7 +68,7 @@ public static List GetGenericBaseNames(string ns) { return null; } - List names = new List(); + var names = new List(); foreach (string key in nsmap.Keys) { names.Add(key); @@ -87,7 +89,9 @@ public static Type GenericByName(string ns, string name, int paramCount) foreach (Type t in GenericsByName(ns, name)) { if (t.GetGenericArguments().Length == paramCount) + { return t; + } } return null; } @@ -119,7 +123,7 @@ public static List GenericsByName(string ns, string basename) return null; } - List result = new List(); + var result = new List(); foreach (string name in names) { string qname = ns + "." + name; diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index e5843d436..96a343773 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -59,7 +59,7 @@ internal static void Initialize() Runtime.PyDict_Update(mod_dict, clr_dict); #elif PYTHON2 Runtime.XIncref(root.pyHandle); // we are using the module two times - py_clr_module = root.pyHandle; // Alias handle for PY2/PY3 + py_clr_module = root.pyHandle; // Alias handle for PY2/PY3 #endif Runtime.PyDict_SetItemString(dict, "CLR", py_clr_module); Runtime.PyDict_SetItemString(dict, "clr", py_clr_module); @@ -150,8 +150,8 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) // borrowed reference IntPtr py_mod_name = Runtime.PyTuple_GetItem(args, 0); - if ((py_mod_name == IntPtr.Zero) || - (!Runtime.IsStringType(py_mod_name))) + if (py_mod_name == IntPtr.Zero || + !Runtime.IsStringType(py_mod_name)) { return Exceptions.RaiseTypeError("string expected"); } @@ -160,12 +160,12 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) // This determines whether we return the head or tail module. IntPtr fromList = IntPtr.Zero; - bool fromlist = false; + var fromlist = false; if (num_args >= 4) { fromList = Runtime.PyTuple_GetItem(args, 3); - if ((fromList != IntPtr.Zero) && - (Runtime.PyObject_IsTrue(fromList) == 1)) + if (fromList != IntPtr.Zero && + Runtime.PyObject_IsTrue(fromList) == 1) { fromlist = true; } @@ -208,7 +208,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) { clr_prefix = "CLR."; // prepend when adding the module to sys.modules realname = mod_name.Substring(4); - string msg = String.Format("Importing from the CLR.* namespace " + + string msg = string.Format("Importing from the CLR.* namespace " + "is deprecated. Please import '{0}' directly.", realname); Exceptions.deprecation(msg); } @@ -301,7 +301,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) // enable preloading in a non-interactive python processing by // setting clr.preload = True - ModuleObject head = (mod_name == realname) ? null : root; + ModuleObject head = mod_name == realname ? null : root; ModuleObject tail = root; root.InitializePreload(); @@ -310,7 +310,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) ManagedType mt = tail.GetAttribute(name, true); if (!(mt is ModuleObject)) { - string error = String.Format("No module named {0}", name); + string error = string.Format("No module named {0}", name); Exceptions.SetError(Exceptions.ImportError, error); return IntPtr.Zero; } @@ -339,7 +339,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) if (fromlist && Runtime.PySequence_Size(fromList) == 1) { IntPtr fp = Runtime.PySequence_GetItem(fromList, 0); - if ((!CLRModule.preload) && Runtime.GetManagedString(fp) == "*") + if (!CLRModule.preload && Runtime.GetManagedString(fp) == "*") { mod.LoadNames(); } diff --git a/src/runtime/interfaceobject.cs b/src/runtime/interfaceobject.cs index 8e64c24d7..e1c816f01 100644 --- a/src/runtime/interfaceobject.cs +++ b/src/runtime/interfaceobject.cs @@ -16,7 +16,7 @@ internal class InterfaceObject : ClassBase internal InterfaceObject(Type tp) : base(tp) { - CoClassAttribute coclass = (CoClassAttribute)Attribute.GetCustomAttribute(tp, cc_attr); + var coclass = (CoClassAttribute)Attribute.GetCustomAttribute(tp, cc_attr); if (coclass != null) { ctor = coclass.CoClass.GetConstructor(Type.EmptyTypes); @@ -35,17 +35,17 @@ static InterfaceObject() /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { - InterfaceObject self = (InterfaceObject)GetManagedObject(tp); + var self = (InterfaceObject)GetManagedObject(tp); int nargs = Runtime.PyTuple_Size(args); Type type = self.type; - Object obj; + object obj; if (nargs == 1) { IntPtr inst = Runtime.PyTuple_GetItem(args, 0); - CLRObject co = GetManagedObject(inst) as CLRObject; + var co = GetManagedObject(inst) as CLRObject; - if ((co == null) || (!type.IsInstanceOfType(co.inst))) + if (co == null || !type.IsInstanceOfType(co.inst)) { string msg = "object does not implement " + type.Name; Exceptions.SetError(Exceptions.TypeError, msg); @@ -55,7 +55,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) obj = co.inst; } - else if ((nargs == 0) && (self.ctor != null)) + else if (nargs == 0 && self.ctor != null) { obj = self.ctor.Invoke(null); diff --git a/src/runtime/interfaces.cs b/src/runtime/interfaces.cs index d0edfbf9c..5ce319858 100644 --- a/src/runtime/interfaces.cs +++ b/src/runtime/interfaces.cs @@ -1,6 +1,4 @@ using System; -using System.Reflection; -using System.Runtime.InteropServices; namespace Python.Runtime { diff --git a/src/runtime/iterator.cs b/src/runtime/iterator.cs index f2a32deb4..efa49537c 100644 --- a/src/runtime/iterator.cs +++ b/src/runtime/iterator.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Reflection; namespace Python.Runtime { @@ -12,9 +11,9 @@ internal class Iterator : ExtensionType { IEnumerator iter; - public Iterator(IEnumerator e) : base() + public Iterator(IEnumerator e) { - this.iter = e; + iter = e; } @@ -23,7 +22,7 @@ public Iterator(IEnumerator e) : base() /// public static IntPtr tp_iternext(IntPtr ob) { - Iterator self = GetManagedObject(ob) as Iterator; + var self = GetManagedObject(ob) as Iterator; if (!self.iter.MoveNext()) { Exceptions.SetError(Exceptions.StopIteration, Runtime.PyNone); diff --git a/src/runtime/managedtype.cs b/src/runtime/managedtype.cs index 0d46f2366..9ee8d223b 100644 --- a/src/runtime/managedtype.cs +++ b/src/runtime/managedtype.cs @@ -1,7 +1,5 @@ using System; using System.Runtime.InteropServices; -using System.Collections; -using System.Reflection; namespace Python.Runtime { @@ -30,13 +28,13 @@ internal static ManagedType GetManagedObject(IntPtr ob) tp = ob; } - int flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); + var flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Managed) != 0) { - IntPtr op = (tp == ob) + IntPtr op = tp == ob ? Marshal.ReadIntPtr(tp, TypeOffset.magic()) : Marshal.ReadIntPtr(ob, ObjectOffset.magic(ob)); - GCHandle gc = (GCHandle)op; + var gc = (GCHandle)op; return (ManagedType)gc.Target; } } @@ -65,7 +63,7 @@ internal static bool IsManagedType(IntPtr ob) tp = ob; } - int flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); + var flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Managed) != 0) { return true; diff --git a/src/runtime/methodwrapper.cs b/src/runtime/methodwrapper.cs index 71932ddd0..2f3ce3ef2 100644 --- a/src/runtime/methodwrapper.cs +++ b/src/runtime/methodwrapper.cs @@ -1,6 +1,4 @@ using System; -using System.Collections; -using System.Runtime.InteropServices; namespace Python.Runtime { diff --git a/src/runtime/modulefunctionobject.cs b/src/runtime/modulefunctionobject.cs index b6f2899d8..aa4c8fb06 100644 --- a/src/runtime/modulefunctionobject.cs +++ b/src/runtime/modulefunctionobject.cs @@ -1,5 +1,5 @@ using System; -using System.Collections; +using System.Linq; using System.Reflection; namespace Python.Runtime @@ -12,13 +12,9 @@ internal class ModuleFunctionObject : MethodObject public ModuleFunctionObject(Type type, string name, MethodInfo[] info, bool allow_threads) : base(type, name, info, allow_threads) { - for (int i = 0; i < info.Length; i++) + if (info.Any(item => !item.IsStatic)) { - MethodInfo item = (MethodInfo)info[i]; - if (!item.IsStatic) - { - throw new Exception("Module function must be static."); - } + throw new Exception("Module function must be static."); } } @@ -27,17 +23,17 @@ public ModuleFunctionObject(Type type, string name, MethodInfo[] info, bool allo /// public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { - ModuleFunctionObject self = (ModuleFunctionObject)GetManagedObject(ob); + var self = (ModuleFunctionObject)GetManagedObject(ob); return self.Invoke(ob, args, kw); } /// /// __repr__ implementation. /// - public static new IntPtr tp_repr(IntPtr ob) + public new static IntPtr tp_repr(IntPtr ob) { - ModuleFunctionObject self = (ModuleFunctionObject)GetManagedObject(ob); - string s = String.Format("", self.name); + var self = (ModuleFunctionObject)GetManagedObject(ob); + string s = $""; return Runtime.PyString_FromStringAndSize(s, s.Length); } } diff --git a/src/runtime/modulepropertyobject.cs b/src/runtime/modulepropertyobject.cs index 7f7841890..8f5edb6ef 100644 --- a/src/runtime/modulepropertyobject.cs +++ b/src/runtime/modulepropertyobject.cs @@ -1,7 +1,5 @@ using System; -using System.Collections; using System.Reflection; -using System.Security.Permissions; namespace Python.Runtime { @@ -10,7 +8,7 @@ namespace Python.Runtime /// internal class ModulePropertyObject : ExtensionType { - public ModulePropertyObject(PropertyInfo md) : base() + public ModulePropertyObject(PropertyInfo md) { throw new NotImplementedException("ModulePropertyObject"); } diff --git a/src/runtime/monosupport.cs b/src/runtime/monosupport.cs index 7ddf9aa1a..fc39f9065 100644 --- a/src/runtime/monosupport.cs +++ b/src/runtime/monosupport.cs @@ -31,10 +31,8 @@ public int GetNativeDataSize() public IntPtr MarshalManagedToNative(object obj) { - string s = obj as string; - if (s == null) - return IntPtr.Zero; - return UnixMarshal.StringToHeap(s, Encoding.UTF32); + var s = obj as string; + return s == null ? IntPtr.Zero : UnixMarshal.StringToHeap(s, Encoding.UTF32); } public object MarshalNativeToManaged(IntPtr pNativeData) diff --git a/src/runtime/nativecall.cs b/src/runtime/nativecall.cs index 7eb8b87c8..f49f08e7b 100644 --- a/src/runtime/nativecall.cs +++ b/src/runtime/nativecall.cs @@ -13,12 +13,10 @@ namespace Python.Runtime /// C API can just be wrapped with p/invoke, but there are some /// situations (specifically, calling functions through Python /// type structures) where we need to call functions indirectly. - /// /// This class uses Reflection.Emit to generate IJW thunks that /// support indirect calls to native code using various common /// call signatures. This is mainly a workaround for the fact /// that you can't spell an indirect call in C# (but can in IL). - /// /// Another approach that would work is for this to be turned /// into a separate utility program that could be run during the /// build process to generate the thunks as a separate assembly @@ -40,14 +38,14 @@ static NativeCall() // interface (defined below) and generate the required thunk // code based on the method signatures. - AssemblyName aname = new AssemblyName(); + var aname = new AssemblyName(); aname.Name = "e__NativeCall_Assembly"; - AssemblyBuilderAccess aa = AssemblyBuilderAccess.Run; + var aa = AssemblyBuilderAccess.Run; aBuilder = Thread.GetDomain().DefineDynamicAssembly(aname, aa); mBuilder = aBuilder.DefineDynamicModule("e__NativeCall_Module"); - TypeAttributes ta = TypeAttributes.Public; + var ta = TypeAttributes.Public; TypeBuilder tBuilder = mBuilder.DefineType("e__NativeCall", ta); Type iType = typeof(INativeCall); @@ -72,8 +70,8 @@ private static void GenerateThunk(TypeBuilder tb, MethodInfo method) int count = pi.Length; int argc = count - 1; - Type[] args = new Type[count]; - for (int i = 0; i < count; i++) + var args = new Type[count]; + for (var i = 0; i < count; i++) { args[i] = pi[i].ParameterType; } @@ -84,16 +82,16 @@ private static void GenerateThunk(TypeBuilder tb, MethodInfo method) MethodAttributes.Virtual, method.ReturnType, args - ); + ); // Build the method signature for the actual native function. // This is essentially the signature of the wrapper method // minus the first argument (the passed in function pointer). - Type[] nargs = new Type[argc]; - for (int i = 1; i < count; i++) + var nargs = new Type[argc]; + for (var i = 1; i < count; i++) { - nargs[(i - 1)] = args[i]; + nargs[i - 1] = args[i]; } // IL generation: the (implicit) first argument of the method @@ -103,9 +101,9 @@ private static void GenerateThunk(TypeBuilder tb, MethodInfo method) ILGenerator il = mb.GetILGenerator(); - for (int i = 0; i < argc; i++) + for (var i = 0; i < argc; i++) { - il.Emit(OpCodes.Ldarg_S, (i + 2)); + il.Emit(OpCodes.Ldarg_S, i + 2); } il.Emit(OpCodes.Ldarg_1); @@ -114,12 +112,11 @@ private static void GenerateThunk(TypeBuilder tb, MethodInfo method) CallingConvention.Cdecl, method.ReturnType, nargs - ); + ); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(mb, method); - return; } diff --git a/src/runtime/overload.cs b/src/runtime/overload.cs index a183863d6..e8f51c01d 100644 --- a/src/runtime/overload.cs +++ b/src/runtime/overload.cs @@ -12,7 +12,7 @@ internal class OverloadMapper : ExtensionType MethodObject m; IntPtr target; - public OverloadMapper(MethodObject m, IntPtr target) : base() + public OverloadMapper(MethodObject m, IntPtr target) { Runtime.XIncref(target); this.target = target; @@ -24,7 +24,7 @@ public OverloadMapper(MethodObject m, IntPtr target) : base() /// public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) { - OverloadMapper self = (OverloadMapper)GetManagedObject(tp); + var self = (OverloadMapper)GetManagedObject(tp); // Note: if the type provides a non-generic method with N args // and a generic method that takes N params, then we always @@ -39,12 +39,11 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) MethodInfo mi = MethodBinder.MatchSignature(self.m.info, types); if (mi == null) { - string e = "No match found for signature"; + var e = "No match found for signature"; return Exceptions.RaiseTypeError(e); } - MethodBinding mb = new MethodBinding(self.m, self.target); - mb.info = mi; + var mb = new MethodBinding(self.m, self.target) { info = mi }; Runtime.XIncref(mb.pyHandle); return mb.pyHandle; } @@ -54,7 +53,7 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) /// public static IntPtr tp_repr(IntPtr op) { - OverloadMapper self = (OverloadMapper)GetManagedObject(op); + var self = (OverloadMapper)GetManagedObject(op); IntPtr doc = self.m.GetDocString(); Runtime.XIncref(doc); return doc; @@ -63,11 +62,11 @@ public static IntPtr tp_repr(IntPtr op) /// /// OverloadMapper dealloc implementation. /// - public static new void tp_dealloc(IntPtr ob) + public new static void tp_dealloc(IntPtr ob) { - OverloadMapper self = (OverloadMapper)GetManagedObject(ob); + var self = (OverloadMapper)GetManagedObject(ob); Runtime.XDecref(self.target); - ExtensionType.FinalizeObject(self); + FinalizeObject(self); } } } diff --git a/src/runtime/propertyobject.cs b/src/runtime/propertyobject.cs index ea029cc91..dae47667f 100644 --- a/src/runtime/propertyobject.cs +++ b/src/runtime/propertyobject.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Reflection; using System.Security.Permissions; @@ -14,8 +13,8 @@ internal class PropertyObject : ExtensionType MethodInfo getter; MethodInfo setter; - [StrongNameIdentityPermissionAttribute(SecurityAction.Assert)] - public PropertyObject(PropertyInfo md) : base() + [StrongNameIdentityPermission(SecurityAction.Assert)] + public PropertyObject(PropertyInfo md) { getter = md.GetGetMethod(true); setter = md.GetSetMethod(true); @@ -30,9 +29,9 @@ public PropertyObject(PropertyInfo md) : base() /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { - PropertyObject self = (PropertyObject)GetManagedObject(ds); + var self = (PropertyObject)GetManagedObject(ds); MethodInfo getter = self.getter; - Object result; + object result; if (getter == null) @@ -40,12 +39,12 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) return Exceptions.RaiseTypeError("property cannot be read"); } - if ((ob == IntPtr.Zero) || (ob == Runtime.PyNone)) + if (ob == IntPtr.Zero || ob == Runtime.PyNone) { - if (!(getter.IsStatic)) + if (!getter.IsStatic) { Exceptions.SetError(Exceptions.TypeError, - "instance property must be accessed through " + "a class instance"); + "instance property must be accessed through a class instance"); return IntPtr.Zero; } @@ -60,7 +59,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) } } - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { return Exceptions.RaiseTypeError("invalid target"); @@ -88,11 +87,11 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// a property based on the given Python value. The Python value must /// be convertible to the type of the property. /// - public static new int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) + public new static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { - PropertyObject self = (PropertyObject)GetManagedObject(ds); + var self = (PropertyObject)GetManagedObject(ds); MethodInfo setter = self.setter; - Object newval; + object newval; if (val == IntPtr.Zero) { @@ -114,9 +113,9 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) bool is_static = setter.IsStatic; - if ((ob == IntPtr.Zero) || (ob == Runtime.PyNone)) + if (ob == IntPtr.Zero || ob == Runtime.PyNone) { - if (!(is_static)) + if (!is_static) { Exceptions.RaiseTypeError("instance property must be set on an instance"); return -1; @@ -127,7 +126,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { if (!is_static) { - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { Exceptions.RaiseTypeError("invalid target"); @@ -158,8 +157,8 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// public static IntPtr tp_repr(IntPtr ob) { - PropertyObject self = (PropertyObject)GetManagedObject(ob); - string s = String.Format("", self.info.Name); + var self = (PropertyObject)GetManagedObject(ob); + string s = $""; return Runtime.PyString_FromStringAndSize(s, s.Length); } } diff --git a/src/runtime/pyansistring.cs b/src/runtime/pyansistring.cs index d15961ee3..4973d8b2a 100644 --- a/src/runtime/pyansistring.cs +++ b/src/runtime/pyansistring.cs @@ -25,7 +25,7 @@ public PyAnsiString(IntPtr ptr) : base(ptr) /// An ArgumentException will be thrown if the given object is not /// a Python string object. /// - public PyAnsiString(PyObject o) : base() + public PyAnsiString(PyObject o) { if (!IsStringType(o)) { @@ -42,7 +42,7 @@ public PyAnsiString(PyObject o) : base() /// /// Creates a Python string from a managed string. /// - public PyAnsiString(string s) : base() + public PyAnsiString(string s) { obj = Runtime.PyString_FromStringAndSize(s, s.Length); if (obj == IntPtr.Zero) diff --git a/src/runtime/pydict.cs b/src/runtime/pydict.cs index 18f0939b2..7237d1990 100644 --- a/src/runtime/pydict.cs +++ b/src/runtime/pydict.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.InteropServices; namespace Python.Runtime { @@ -30,7 +29,7 @@ public PyDict(IntPtr ptr) : base(ptr) /// /// Creates a new Python dictionary object. /// - public PyDict() : base() + public PyDict() { obj = Runtime.PyDict_New(); if (obj == IntPtr.Zero) @@ -48,7 +47,7 @@ public PyDict() : base() /// ArgumentException will be thrown if the given object is not a /// Python dictionary object. /// - public PyDict(PyObject o) : base() + public PyDict(PyObject o) { if (!IsDictType(o)) { @@ -79,7 +78,7 @@ public static bool IsDictType(PyObject value) /// public bool HasKey(PyObject key) { - return (Runtime.PyMapping_HasKey(obj, key.obj) != 0); + return Runtime.PyMapping_HasKey(obj, key.obj) != 0; } @@ -91,8 +90,10 @@ public bool HasKey(PyObject key) /// public bool HasKey(string key) { - using (PyString str = new PyString(key)) + using (var str = new PyString(key)) + { return HasKey(str); + } } diff --git a/src/runtime/pyfloat.cs b/src/runtime/pyfloat.cs index 959657118..cca436def 100644 --- a/src/runtime/pyfloat.cs +++ b/src/runtime/pyfloat.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.InteropServices; namespace Python.Runtime { @@ -32,7 +31,7 @@ public PyFloat(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python float object. /// - public PyFloat(PyObject o) : base() + public PyFloat(PyObject o) { if (!IsFloatType(o)) { @@ -49,7 +48,7 @@ public PyFloat(PyObject o) : base() /// /// Creates a new Python float from a double value. /// - public PyFloat(double value) : base() + public PyFloat(double value) { obj = Runtime.PyFloat_FromDouble(value); if (obj == IntPtr.Zero) @@ -65,9 +64,9 @@ public PyFloat(double value) : base() /// /// Creates a new Python float from a string value. /// - public PyFloat(string value) : base() + public PyFloat(string value) { - using (PyString s = new PyString(value)) + using (var s = new PyString(value)) { obj = Runtime.PyFloat_FromString(s.obj, IntPtr.Zero); if (obj == IntPtr.Zero) diff --git a/src/runtime/pyint.cs b/src/runtime/pyint.cs index e89c1e87e..c84939482 100644 --- a/src/runtime/pyint.cs +++ b/src/runtime/pyint.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.InteropServices; namespace Python.Runtime { @@ -32,7 +31,7 @@ public PyInt(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python int object. /// - public PyInt(PyObject o) : base() + public PyInt(PyObject o) { if (!IsIntType(o)) { @@ -49,7 +48,7 @@ public PyInt(PyObject o) : base() /// /// Creates a new Python int from an int32 value. /// - public PyInt(int value) : base() + public PyInt(int value) { obj = Runtime.PyInt_FromInt32(value); if (obj == IntPtr.Zero) @@ -68,7 +67,7 @@ public PyInt(int value) : base() [CLSCompliant(false)] public PyInt(uint value) : base(IntPtr.Zero) { - obj = Runtime.PyInt_FromInt64((long)value); + obj = Runtime.PyInt_FromInt64(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -161,7 +160,7 @@ public PyInt(sbyte value) : this((int)value) /// /// Creates a new Python int from a string value. /// - public PyInt(string value) : base() + public PyInt(string value) { obj = Runtime.PyInt_FromString(value, IntPtr.Zero, 0); if (obj == IntPtr.Zero) @@ -210,7 +209,7 @@ public static PyInt AsInt(PyObject value) /// public short ToInt16() { - return System.Convert.ToInt16(this.ToInt32()); + return Convert.ToInt16(ToInt32()); } @@ -234,7 +233,7 @@ public int ToInt32() /// public long ToInt64() { - return System.Convert.ToInt64(this.ToInt32()); + return Convert.ToInt64(ToInt32()); } } } diff --git a/src/runtime/pyiter.cs b/src/runtime/pyiter.cs index c1bab2781..3c9b2a238 100644 --- a/src/runtime/pyiter.cs +++ b/src/runtime/pyiter.cs @@ -11,7 +11,7 @@ namespace Python.Runtime /// public class PyIter : PyObject, IEnumerator { - private PyObject _current = null; + private PyObject _current; /// /// PyIter Constructor @@ -31,11 +31,13 @@ public PyIter(IntPtr ptr) : base(ptr) /// /// Creates a Python iterator from an iterable. Like doing "iter(iterable)" in python. /// - public PyIter(PyObject iterable) : base() + public PyIter(PyObject iterable) { obj = Runtime.PyObject_GetIter(iterable.obj); if (obj == IntPtr.Zero) + { throw new PythonException(); + } } protected override void Dispose(bool disposing) @@ -61,7 +63,9 @@ public bool MoveNext() IntPtr next = Runtime.PyIter_Next(obj); if (next == IntPtr.Zero) + { return false; + } _current = new PyObject(next); return true; diff --git a/src/runtime/pylist.cs b/src/runtime/pylist.cs index 8a369f654..b22d9d51f 100644 --- a/src/runtime/pylist.cs +++ b/src/runtime/pylist.cs @@ -31,7 +31,7 @@ public PyList(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python list object. /// - public PyList(PyObject o) : base() + public PyList(PyObject o) { if (!IsListType(o)) { @@ -48,7 +48,7 @@ public PyList(PyObject o) : base() /// /// Creates a new empty Python list object. /// - public PyList() : base() + public PyList() { obj = Runtime.PyList_New(0); if (obj == IntPtr.Zero) @@ -64,11 +64,11 @@ public PyList() : base() /// /// Creates a new Python list object from an array of PyObjects. /// - public PyList(PyObject[] items) : base() + public PyList(PyObject[] items) { int count = items.Length; obj = Runtime.PyList_New(count); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr ptr = items[i].obj; Runtime.XIncref(ptr); diff --git a/src/runtime/pylong.cs b/src/runtime/pylong.cs index 8deac242e..ade7cb42c 100644 --- a/src/runtime/pylong.cs +++ b/src/runtime/pylong.cs @@ -31,7 +31,7 @@ public PyLong(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python long object. /// - public PyLong(PyObject o) : base() + public PyLong(PyObject o) { if (!IsLongType(o)) { @@ -48,9 +48,9 @@ public PyLong(PyObject o) : base() /// /// Creates a new PyLong from an int32 value. /// - public PyLong(int value) : base() + public PyLong(int value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -65,9 +65,9 @@ public PyLong(int value) : base() /// Creates a new PyLong from a uint32 value. /// [CLSCompliant(false)] - public PyLong(uint value) : base() + public PyLong(uint value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -81,7 +81,7 @@ public PyLong(uint value) : base() /// /// Creates a new PyLong from an int64 value. /// - public PyLong(long value) : base() + public PyLong(long value) { obj = Runtime.PyLong_FromLongLong(value); if (obj == IntPtr.Zero) @@ -98,7 +98,7 @@ public PyLong(long value) : base() /// Creates a new PyLong from a uint64 value. /// [CLSCompliant(false)] - public PyLong(ulong value) : base() + public PyLong(ulong value) { obj = Runtime.PyLong_FromUnsignedLongLong(value); if (obj == IntPtr.Zero) @@ -114,9 +114,9 @@ public PyLong(ulong value) : base() /// /// Creates a new PyLong from an int16 value. /// - public PyLong(short value) : base() + public PyLong(short value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -131,9 +131,9 @@ public PyLong(short value) : base() /// Creates a new PyLong from an uint16 value. /// [CLSCompliant(false)] - public PyLong(ushort value) : base() + public PyLong(ushort value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -147,9 +147,9 @@ public PyLong(ushort value) : base() /// /// Creates a new PyLong from a byte value. /// - public PyLong(byte value) : base() + public PyLong(byte value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -164,9 +164,9 @@ public PyLong(byte value) : base() /// Creates a new PyLong from an sbyte value. /// [CLSCompliant(false)] - public PyLong(sbyte value) : base() + public PyLong(sbyte value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -180,7 +180,7 @@ public PyLong(sbyte value) : base() /// /// Creates a new PyLong from an double value. /// - public PyLong(double value) : base() + public PyLong(double value) { obj = Runtime.PyLong_FromDouble(value); if (obj == IntPtr.Zero) @@ -196,7 +196,7 @@ public PyLong(double value) : base() /// /// Creates a new PyLong from a string value. /// - public PyLong(string value) : base() + public PyLong(string value) { obj = Runtime.PyLong_FromString(value, IntPtr.Zero, 0); if (obj == IntPtr.Zero) @@ -244,7 +244,7 @@ public static PyLong AsLong(PyObject value) /// public short ToInt16() { - return System.Convert.ToInt16(this.ToInt64()); + return Convert.ToInt16(ToInt64()); } @@ -256,7 +256,7 @@ public short ToInt16() /// public int ToInt32() { - return System.Convert.ToInt32(this.ToInt64()); + return Convert.ToInt32(ToInt64()); } diff --git a/src/runtime/pynumber.cs b/src/runtime/pynumber.cs index 73dde6744..371d9f4f6 100644 --- a/src/runtime/pynumber.cs +++ b/src/runtime/pynumber.cs @@ -15,7 +15,7 @@ protected PyNumber(IntPtr ptr) : base(ptr) { } - protected PyNumber() : base() + protected PyNumber() { } diff --git a/src/runtime/pysequence.cs b/src/runtime/pysequence.cs index d54959599..bfaee79a6 100644 --- a/src/runtime/pysequence.cs +++ b/src/runtime/pysequence.cs @@ -16,7 +16,7 @@ protected PySequence(IntPtr ptr) : base(ptr) { } - protected PySequence() : base() + protected PySequence() { } @@ -115,7 +115,7 @@ public bool Contains(PyObject item) { throw new PythonException(); } - return (r != 0); + return r != 0; } diff --git a/src/runtime/pystring.cs b/src/runtime/pystring.cs index 39e7a8f96..3bd99b87c 100644 --- a/src/runtime/pystring.cs +++ b/src/runtime/pystring.cs @@ -34,7 +34,7 @@ public PyString(IntPtr ptr) : base(ptr) /// An ArgumentException will be thrown if the given object is not /// a Python string object. /// - public PyString(PyObject o) : base() + public PyString(PyObject o) { if (!IsStringType(o)) { @@ -51,7 +51,7 @@ public PyString(PyObject o) : base() /// /// Creates a Python string from a managed string. /// - public PyString(string s) : base() + public PyString(string s) { obj = Runtime.PyUnicode_FromUnicode(s, s.Length); if (obj == IntPtr.Zero) diff --git a/src/runtime/pythonexception.cs b/src/runtime/pythonexception.cs index d2475664c..8e2f992f4 100644 --- a/src/runtime/pythonexception.cs +++ b/src/runtime/pythonexception.cs @@ -15,26 +15,26 @@ public class PythonException : System.Exception private string _message = ""; private bool disposed = false; - public PythonException() : base() + public PythonException() { IntPtr gs = PythonEngine.AcquireLock(); Runtime.PyErr_Fetch(ref _pyType, ref _pyValue, ref _pyTB); Runtime.XIncref(_pyType); Runtime.XIncref(_pyValue); Runtime.XIncref(_pyTB); - if ((_pyType != IntPtr.Zero) && (_pyValue != IntPtr.Zero)) + if (_pyType != IntPtr.Zero && _pyValue != IntPtr.Zero) { string type; string message; Runtime.XIncref(_pyType); - using (PyObject pyType = new PyObject(_pyType)) + using (var pyType = new PyObject(_pyType)) using (PyObject pyTypeName = pyType.GetAttr("__name__")) { type = pyTypeName.ToString(); } Runtime.XIncref(_pyValue); - using (PyObject pyValue = new PyObject(_pyValue)) + using (var pyValue = new PyObject(_pyValue)) { message = pyValue.ToString(); } @@ -44,7 +44,7 @@ public PythonException() : base() { PyObject tb_module = PythonEngine.ImportModule("traceback"); Runtime.XIncref(_pyTB); - using (PyObject pyTB = new PyObject(_pyTB)) + using (var pyTB = new PyObject(_pyTB)) { _tb = tb_module.InvokeMethod("format_tb", pyTB).ToString(); } diff --git a/src/runtime/pytuple.cs b/src/runtime/pytuple.cs index 76ca616ae..b3fb95733 100644 --- a/src/runtime/pytuple.cs +++ b/src/runtime/pytuple.cs @@ -31,7 +31,7 @@ public PyTuple(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python tuple object. /// - public PyTuple(PyObject o) : base() + public PyTuple(PyObject o) { if (!IsTupleType(o)) { @@ -48,7 +48,7 @@ public PyTuple(PyObject o) : base() /// /// Creates a new empty PyTuple. /// - public PyTuple() : base() + public PyTuple() { obj = Runtime.PyTuple_New(0); if (obj == IntPtr.Zero) @@ -64,11 +64,11 @@ public PyTuple() : base() /// /// Creates a new PyTuple from an array of PyObject instances. /// - public PyTuple(PyObject[] items) : base() + public PyTuple(PyObject[] items) { int count = items.Length; obj = Runtime.PyTuple_New(count); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr ptr = items[i].obj; Runtime.XIncref(ptr); diff --git a/src/runtime/typemanager.cs b/src/runtime/typemanager.cs index d85bdf9bb..49c931183 100644 --- a/src/runtime/typemanager.cs +++ b/src/runtime/typemanager.cs @@ -1,10 +1,8 @@ using System; using System.Runtime.InteropServices; -using System.Reflection.Emit; using System.Collections.Generic; using System.Collections; using System.Reflection; -using System.Threading; namespace Python.Runtime { @@ -34,7 +32,7 @@ internal static IntPtr GetTypeHandle(Type type) { // Note that these types are cached with a refcount of 1, so they // effectively exist until the CPython runtime is finalized. - IntPtr handle = IntPtr.Zero; + IntPtr handle; cache.TryGetValue(type, out handle); if (handle != IntPtr.Zero) { @@ -53,7 +51,7 @@ internal static IntPtr GetTypeHandle(Type type) /// internal static IntPtr GetTypeHandle(ManagedType obj, Type type) { - IntPtr handle = IntPtr.Zero; + IntPtr handle; cache.TryGetValue(type, out handle); if (handle != IntPtr.Zero) { @@ -81,7 +79,7 @@ internal static IntPtr CreateType(Type impl) // Set tp_basicsize to the size of our managed instance objects. Marshal.WriteIntPtr(type, TypeOffset.tp_basicsize, (IntPtr)ob_size); - IntPtr offset = (IntPtr)ObjectOffset.DictOffset(type); + var offset = (IntPtr)ObjectOffset.DictOffset(type); Marshal.WriteIntPtr(type, TypeOffset.tp_dictoffset, offset); InitializeSlots(type, impl); @@ -124,13 +122,13 @@ internal static IntPtr CreateType(ManagedType impl, Type clrType) // XXX Hack, use a different base class for System.Exception // Python 2.5+ allows new style class exceptions but they *must* // subclass BaseException (or better Exception). - if (typeof(System.Exception).IsAssignableFrom(clrType)) + if (typeof(Exception).IsAssignableFrom(clrType)) { ob_size = ObjectOffset.Size(Exceptions.Exception); tp_dictoffset = ObjectOffset.DictOffset(Exceptions.Exception); } - if (clrType == typeof(System.Exception)) + if (clrType == typeof(Exception)) { base_ = Exceptions.Exception; } @@ -171,7 +169,7 @@ internal static IntPtr CreateType(ManagedType impl, Type clrType) Runtime.PyType_Ready(type); IntPtr dict = Marshal.ReadIntPtr(type, TypeOffset.tp_dict); - string mn = clrType.Namespace != null ? clrType.Namespace : ""; + string mn = clrType.Namespace ?? ""; IntPtr mod = Runtime.PyString_FromString(mn); Runtime.PyDict_SetItemString(dict, "__module__", mod); @@ -200,37 +198,43 @@ internal static IntPtr CreateSubType(IntPtr py_name, IntPtr py_base_type, IntPtr object assembly = null; object namespaceStr = null; - List disposeList = new List(); + var disposeList = new List(); try { - PyObject assemblyKey = new PyObject(Converter.ToPython("__assembly__", typeof(String))); + var assemblyKey = new PyObject(Converter.ToPython("__assembly__", typeof(string))); disposeList.Add(assemblyKey); if (0 != Runtime.PyMapping_HasKey(py_dict, assemblyKey.Handle)) { - PyObject pyAssembly = new PyObject(Runtime.PyDict_GetItem(py_dict, assemblyKey.Handle)); + var pyAssembly = new PyObject(Runtime.PyDict_GetItem(py_dict, assemblyKey.Handle)); disposeList.Add(pyAssembly); - if (!Converter.ToManagedValue(pyAssembly.Handle, typeof(String), out assembly, false)) + if (!Converter.ToManagedValue(pyAssembly.Handle, typeof(string), out assembly, false)) + { throw new InvalidCastException("Couldn't convert __assembly__ value to string"); + } } - PyObject namespaceKey = new PyObject(Converter.ToPythonImplicit("__namespace__")); + var namespaceKey = new PyObject(Converter.ToPythonImplicit("__namespace__")); disposeList.Add(namespaceKey); if (0 != Runtime.PyMapping_HasKey(py_dict, namespaceKey.Handle)) { - PyObject pyNamespace = new PyObject(Runtime.PyDict_GetItem(py_dict, namespaceKey.Handle)); + var pyNamespace = new PyObject(Runtime.PyDict_GetItem(py_dict, namespaceKey.Handle)); disposeList.Add(pyNamespace); - if (!Converter.ToManagedValue(pyNamespace.Handle, typeof(String), out namespaceStr, false)) + if (!Converter.ToManagedValue(pyNamespace.Handle, typeof(string), out namespaceStr, false)) + { throw new InvalidCastException("Couldn't convert __namespace__ value to string"); + } } } finally { foreach (PyObject o in disposeList) + { o.Dispose(); + } } // create the new managed type subclassing the base managed type - ClassBase baseClass = ManagedType.GetManagedObject(py_base_type) as ClassBase; + var baseClass = ManagedType.GetManagedObject(py_base_type) as ClassBase; if (null == baseClass) { return Exceptions.RaiseTypeError("invalid base class, expected CLR class type"); @@ -264,9 +268,9 @@ internal static IntPtr CreateSubType(IntPtr py_name, IntPtr py_base_type, IntPtr internal static IntPtr WriteMethodDef(IntPtr mdef, IntPtr name, IntPtr func, int flags, IntPtr doc) { Marshal.WriteIntPtr(mdef, name); - Marshal.WriteIntPtr(mdef, (1 * IntPtr.Size), func); - Marshal.WriteInt32(mdef, (2 * IntPtr.Size), flags); - Marshal.WriteIntPtr(mdef, (3 * IntPtr.Size), doc); + Marshal.WriteIntPtr(mdef, 1 * IntPtr.Size, func); + Marshal.WriteInt32(mdef, 2 * IntPtr.Size, flags); + Marshal.WriteIntPtr(mdef, 3 * IntPtr.Size, doc); return mdef + 4 * IntPtr.Size; } @@ -321,7 +325,7 @@ internal static IntPtr CreateMetaType(Type impl) // We need space for 3 PyMethodDef structs, each of them // 4 int-ptrs in size. - IntPtr mdef = Runtime.PyMem_Malloc(3 * (4 * IntPtr.Size)); + IntPtr mdef = Runtime.PyMem_Malloc(3 * 4 * IntPtr.Size); IntPtr mdefStart = mdef; mdef = WriteMethodDef( mdef, @@ -335,6 +339,7 @@ internal static IntPtr CreateMetaType(Type impl) Interop.GetThunk(typeof(MetaType).GetMethod("__subclasscheck__"), "BinaryFunc") ); + // FIXME: mdef is not used mdef = WriteMethodDefSentinel(mdef); Marshal.WriteIntPtr(type, TypeOffset.tp_methods, mdefStart); @@ -447,15 +452,14 @@ internal static IntPtr AllocateTypeObject(string name) /// internal static void InitializeSlots(IntPtr type, Type impl) { - Hashtable seen = new Hashtable(8); + var seen = new Hashtable(8); Type offsetType = typeof(TypeOffset); while (impl != null) { MethodInfo[] methods = impl.GetMethods(tbFlags); - for (int i = 0; i < methods.Length; i++) + foreach (MethodInfo method in methods) { - MethodInfo method = methods[i]; string name = method.Name; if (!(name.StartsWith("tp_") || name.StartsWith("nb_") || @@ -473,7 +477,7 @@ internal static void InitializeSlots(IntPtr type, Type impl) } FieldInfo fi = offsetType.GetField(name); - int offset = (int)fi.GetValue(offsetType); + var offset = (int)fi.GetValue(offsetType); IntPtr slot = Interop.GetThunk(method); Marshal.WriteIntPtr(type, offset, slot); @@ -497,21 +501,20 @@ private static void InitMethods(IntPtr pytype, Type type) Type marker = typeof(PythonMethodAttribute); BindingFlags flags = BindingFlags.Public | BindingFlags.Static; - HashSet addedMethods = new HashSet(); + var addedMethods = new HashSet(); while (type != null) { MethodInfo[] methods = type.GetMethods(flags); - for (int i = 0; i < methods.Length; i++) + foreach (MethodInfo method in methods) { - MethodInfo method = methods[i]; if (!addedMethods.Contains(method.Name)) { object[] attrs = method.GetCustomAttributes(marker, false); if (attrs.Length > 0) { string method_name = method.Name; - MethodInfo[] mi = new MethodInfo[1]; + var mi = new MethodInfo[1]; mi[0] = method; MethodObject m = new TypeMethod(type, method_name, mi); Runtime.PyDict_SetItemString(dict, method_name, m.pyHandle); diff --git a/src/runtime/typemethod.cs b/src/runtime/typemethod.cs index 50577f93d..946c769b2 100644 --- a/src/runtime/typemethod.cs +++ b/src/runtime/typemethod.cs @@ -21,15 +21,15 @@ public TypeMethod(Type type, string name, MethodInfo[] info, bool allow_threads) public override IntPtr Invoke(IntPtr ob, IntPtr args, IntPtr kw) { - MethodInfo mi = this.info[0]; - Object[] arglist = new Object[3]; + MethodInfo mi = info[0]; + var arglist = new object[3]; arglist[0] = ob; arglist[1] = args; arglist[2] = kw; try { - Object inst = null; + object inst = null; if (ob != IntPtr.Zero) { inst = GetManagedObject(ob); From 448117e29328d42f1c356b0bdc95b5aa19c3ded5 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 30 Jan 2017 21:44:33 -0700 Subject: [PATCH 063/245] Standarize properties used across projects Console had it owns set of properties going on --- pythonnet.sln | 37 +++++---- src/console/Console.csproj | 162 +++++++++++-------------------------- 2 files changed, 64 insertions(+), 135 deletions(-) diff --git a/pythonnet.sln b/pythonnet.sln index 0a4dbe1f7..520dd9709 100644 --- a/pythonnet.sln +++ b/pythonnet.sln @@ -1,7 +1,6 @@ - Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.30110.0 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Python.Runtime", "src\runtime\Python.Runtime.csproj", "{097B4AC0-74E9-4C58-BCF8-C69746EC8271}" EndProject @@ -73,22 +72,22 @@ Global {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWin|x64.Build.0 = ReleaseWin|x64 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWin|x86.ActiveCfg = ReleaseWin|x86 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWin|x86.Build.0 = ReleaseWin|x86 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x64.ActiveCfg = DebugMono_x86|x64 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x64.Build.0 = DebugMono_x86|x64 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x86.ActiveCfg = DebugMono_x86|x86 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x86.Build.0 = DebugMono_x86|x86 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x64.ActiveCfg = DebugMono_x86|x64 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x64.Build.0 = DebugMono_x86|x64 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x86.ActiveCfg = DebugMono_x86|x86 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x86.Build.0 = DebugMono_x86|x86 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x64.ActiveCfg = Release|x64 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x64.Build.0 = Release|x64 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x86.ActiveCfg = Release|x86 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x86.Build.0 = Release|x86 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x64.ActiveCfg = Release|x64 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x64.Build.0 = Release|x64 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x86.ActiveCfg = Release|x86 - {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x86.Build.0 = Release|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x64.ActiveCfg = DebugMono|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x64.Build.0 = DebugMono|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x86.ActiveCfg = DebugMono|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x86.Build.0 = DebugMono|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x64.ActiveCfg = DebugWin|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x64.Build.0 = DebugWin|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x86.ActiveCfg = DebugWin|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x86.Build.0 = DebugWin|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x64.ActiveCfg = ReleaseMono|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x64.Build.0 = ReleaseMono|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x86.ActiveCfg = ReleaseMono|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x86.Build.0 = ReleaseMono|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x64.ActiveCfg = ReleaseWin|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x64.Build.0 = ReleaseWin|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x86.ActiveCfg = ReleaseWin|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x86.Build.0 = ReleaseWin|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMono|x64.ActiveCfg = DebugWin|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMono|x86.ActiveCfg = DebugWin|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWin|x64.ActiveCfg = DebugWin|x64 diff --git a/src/console/Console.csproj b/src/console/Console.csproj index 53306e47f..a2834c7f6 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -15,143 +15,73 @@ ..\..\ $(SolutionDir) - - True - full - False - bin\Debug\ - DEBUG;TRACE - 4 - - - pdbonly - True - bin\Release\ - TRACE - True - false - 4 - - - True - bin\EmbeddingTest\ - DEBUG;TRACE - full - AnyCPU - 4 - False - - - True - bin\UnitTests\ - DEBUG;TRACE - full - AnyCPU - 4 - False - - - True - bin\x86\Debug\ + + true + bin\x86\DebugMono\ DEBUG;TRACE full x86 - True - 4 - False - False - - - True - bin\x86\Release\ - TRACE - True - pdbonly - x86 - false - 4 + prompt - - True - bin\x86\EmbeddingTest\ + + true + bin\x64\DebugMono\ DEBUG;TRACE full - x86 - 4 - False + x64 + prompt - - True - bin\x86\UnitTests\ - DEBUG;TRACE - full + + bin\x86\ReleaseMono\ + + + true + pdbonly x86 - 4 - False + prompt - - True - bin\DebugMono_x86\ - DEBUG;TRACE - full - AnyCPU - 4 - False + + bin\x64\ReleaseMono\ + + + true + pdbonly + x64 + prompt - - True - bin\x86\DebugMono_x86\ + + true + bin\x86\DebugWin\ DEBUG;TRACE full x86 - 4 - False + prompt - - True - bin\x64\Debug\ + + true + bin\x64\DebugWin\ DEBUG;TRACE full x64 - 4 - False + prompt - - True - bin\x64\Release\ - TRACE - True + + bin\x86\ReleaseWin\ + + + true pdbonly - x64 - false - 4 - - - True - bin\x64\EmbeddingTest\ - DEBUG;TRACE - full - x64 - 4 - False - - - True - bin\x64\UnitTests\ - DEBUG;TRACE - full - x64 - 4 - False + x86 + prompt - - True - bin\x64\DebugMono_x86\ - DEBUG;TRACE - full + + bin\x64\ReleaseWin\ + + + true + pdbonly x64 - 4 - False + prompt $(PythonManifest) From 9e070f91cc765ddc1efbb78926851d8e48bc5a3b Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 30 Jan 2017 22:01:33 -0700 Subject: [PATCH 064/245] Add pyproj from @denfromufa Corrected the configs, won't interfere with users without PTVS --- src/tests/tests.pyproj | 67 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/tests/tests.pyproj diff --git a/src/tests/tests.pyproj b/src/tests/tests.pyproj new file mode 100644 index 000000000..737ec2e79 --- /dev/null +++ b/src/tests/tests.pyproj @@ -0,0 +1,67 @@ + + + + Debug + 2.0 + {250c535c-c060-4f0c-bd80-41f2bf373565} + + runtests.py + + . + . + {888888a0-9f3d-457c-b088-3a5042f75d52} + Standard Python launcher + + + + + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 01a3c8d2fcd6b1bac27897ba4b9b0ce142a598c6 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 10:50:46 -0700 Subject: [PATCH 065/245] Consolidate output paths http://stackoverflow.com/questions/30191387/what-are-the-consequences-of-setting-same-output-path-for-all-configurations --- .travis.yml | 2 +- ci/appveyor_run_tests.ps1 | 4 ++-- src/clrmodule/clrmodule.csproj | 16 ++++++++-------- src/console/Console.csproj | 16 ++++++++-------- src/embed_tests/Python.EmbeddingTest.csproj | 16 ++++++++-------- src/runtime/Python.Runtime.csproj | 16 ++++++++-------- src/testing/Python.Test.csproj | 16 ++++++++-------- 7 files changed, 43 insertions(+), 43 deletions(-) diff --git a/.travis.yml b/.travis.yml index f23a4ee6c..df89014f4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,7 +36,7 @@ install: script: - export PYTHONPATH=`pwd`:$PYTHONPATH - python src/tests/runtests.py - # - nunit-console src/embed_tests/bin/x64/ReleaseMono/Python.EmbeddingTest.dll + # - nunit-console src/embed_tests/bin/Python.EmbeddingTest.dll after_success: # Uncomment if need to geninterop, ie. py37 final diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 index 9f9a470bd..3a7d25af8 100644 --- a/ci/appveyor_run_tests.ps1 +++ b/ci/appveyor_run_tests.ps1 @@ -7,8 +7,8 @@ $NUNIT = Resolve-Path .\packages\NUnit.ConsoleRunner*\tools\nunit3-console.exe $PY = Get-Command python # Can't use ".\build\*\Python.EmbeddingTest.dll". Missing framework files. -$CS_TESTS = Resolve-Path .\src\embed_tests\bin\*\*\Python.EmbeddingTest.dll -$RUNTIME_DIR = Resolve-Path .\src\runtime\bin\*\ReleaseWin\ +$CS_TESTS = ".\src\embed_tests\bin\Python.EmbeddingTest.dll" +$RUNTIME_DIR = ".\src\runtime\bin\" # Run python tests with C# coverage # why `2>&1 | %{ "$_" }`? see: http://stackoverflow.com/a/20950421/5208670 diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index 9575f521f..44d809f05 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -17,7 +17,7 @@ true - bin\x86\DebugMono\ + bin\ TRACE;DEBUG;PYTHON2 full x86 @@ -25,14 +25,14 @@ true - bin\x64\DebugMono\ + bin\ TRACE;DEBUG;PYTHON2 full x64 prompt - bin\x86\ReleaseMono\ + bin\ PYTHON2 true pdbonly @@ -40,7 +40,7 @@ prompt - bin\x64\ReleaseMono\ + bin\ PYTHON2 true pdbonly @@ -49,7 +49,7 @@ true - bin\x86\DebugWin\ + bin\ TRACE;DEBUG;PYTHON2 full x86 @@ -57,14 +57,14 @@ true - bin\x64\DebugWin\ + bin\ TRACE;DEBUG;PYTHON2 full x64 prompt - bin\x86\ReleaseWin\ + bin\ PYTHON2 true pdbonly @@ -72,7 +72,7 @@ prompt - bin\x64\ReleaseWin\ + bin\ PYTHON2 true pdbonly diff --git a/src/console/Console.csproj b/src/console/Console.csproj index a2834c7f6..1ec09736b 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -17,7 +17,7 @@ true - bin\x86\DebugMono\ + bin\ DEBUG;TRACE full x86 @@ -25,14 +25,14 @@ true - bin\x64\DebugMono\ + bin\ DEBUG;TRACE full x64 prompt - bin\x86\ReleaseMono\ + bin\ true @@ -41,7 +41,7 @@ prompt - bin\x64\ReleaseMono\ + bin\ true @@ -51,7 +51,7 @@ true - bin\x86\DebugWin\ + bin\ DEBUG;TRACE full x86 @@ -59,14 +59,14 @@ true - bin\x64\DebugWin\ + bin\ DEBUG;TRACE full x64 prompt - bin\x86\ReleaseWin\ + bin\ true @@ -75,7 +75,7 @@ prompt - bin\x64\ReleaseWin\ + bin\ true diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 264afd0ab..34724247f 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -15,7 +15,7 @@ true - bin\x86\DebugMono\ + bin\ DEBUG;TRACE full x86 @@ -23,14 +23,14 @@ true - bin\x64\DebugMono\ + bin\ DEBUG;TRACE full x64 prompt - bin\x86\ReleaseMono\ + bin\ true @@ -39,7 +39,7 @@ prompt - bin\x64\ReleaseMono\ + bin\ true @@ -49,7 +49,7 @@ true - bin\x86\DebugWin\ + bin\ DEBUG;TRACE full x86 @@ -57,14 +57,14 @@ true - bin\x64\DebugWin\ + bin\ DEBUG;TRACE full x64 prompt - bin\x86\ReleaseWin\ + bin\ true @@ -73,7 +73,7 @@ prompt - bin\x64\ReleaseWin\ + bin\ true diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 6309bf4a3..091aac643 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -12,7 +12,7 @@ $(SolutionDir) - bin\x86\ReleaseMono\ + bin\ PYTHON2;PYTHON27;UCS4 true true @@ -20,7 +20,7 @@ x86 - bin\x64\ReleaseMono\ + bin\ PYTHON2;PYTHON27;UCS4 true true @@ -28,7 +28,7 @@ x64 - bin\x86\ReleaseWin\ + bin\ PYTHON2;PYTHON27;UCS2 true true @@ -36,7 +36,7 @@ x86 - bin\x64\ReleaseWin\ + bin\ PYTHON2;PYTHON27;UCS2 true true @@ -45,7 +45,7 @@ true - bin\x86\DebugMono\ + bin\ TRACE;DEBUG;PYTHON2;PYTHON27;UCS4 true false @@ -54,7 +54,7 @@ true - bin\x64\DebugMono\ + bin\ TRACE;DEBUG;PYTHON2;PYTHON27;UCS4 true false @@ -63,7 +63,7 @@ true - bin\x86\DebugWin\ + bin\ TRACE;DEBUG;PYTHON2;PYTHON27;UCS2 true false @@ -72,7 +72,7 @@ true - bin\x64\DebugWin\ + bin\ TRACE;DEBUG;PYTHON2;PYTHON27;UCS2 true false diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index 1f0134296..fa01790fc 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -16,7 +16,7 @@ true - bin\x86\DebugMono\ + bin\ DEBUG;TRACE full x86 @@ -24,14 +24,14 @@ true - bin\x64\DebugMono\ + bin\ DEBUG;TRACE full x64 prompt - bin\x86\ReleaseMono\ + bin\ true @@ -40,7 +40,7 @@ prompt - bin\x64\ReleaseMono\ + bin\ true @@ -50,7 +50,7 @@ true - bin\x86\DebugWin\ + bin\ DEBUG;TRACE full x86 @@ -58,14 +58,14 @@ true - bin\x64\DebugWin\ + bin\ DEBUG;TRACE full x64 prompt - bin\x86\ReleaseWin\ + bin\ true @@ -74,7 +74,7 @@ prompt - bin\x64\ReleaseWin\ + bin\ true From c5f63bd2dda7fd0a4c655992614eaf05bb879828 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 11:07:48 -0700 Subject: [PATCH 066/245] Fix clrmodule config mismapping --- pythonnet.sln | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pythonnet.sln b/pythonnet.sln index 520dd9709..85f7a8303 100644 --- a/pythonnet.sln +++ b/pythonnet.sln @@ -88,14 +88,14 @@ Global {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x64.Build.0 = ReleaseWin|x64 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x86.ActiveCfg = ReleaseWin|x86 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x86.Build.0 = ReleaseWin|x86 - {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMono|x64.ActiveCfg = DebugWin|x64 - {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMono|x86.ActiveCfg = DebugWin|x86 + {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMono|x64.ActiveCfg = DebugMono|x64 + {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMono|x86.ActiveCfg = DebugMono|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWin|x64.ActiveCfg = DebugWin|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWin|x64.Build.0 = DebugWin|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWin|x86.ActiveCfg = DebugWin|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWin|x86.Build.0 = DebugWin|x86 - {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseMono|x64.ActiveCfg = ReleaseWin|x64 - {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseMono|x86.ActiveCfg = ReleaseWin|x86 + {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseMono|x64.ActiveCfg = ReleaseMono|x64 + {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseMono|x86.ActiveCfg = ReleaseMono|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWin|x64.ActiveCfg = ReleaseWin|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWin|x64.Build.0 = ReleaseWin|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWin|x86.ActiveCfg = ReleaseWin|x86 From 73b8a9d69d60501644f303e9eb49cdc9d8ce704d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 31 Jan 2017 11:12:56 -0700 Subject: [PATCH 067/245] Add PY3 project/sln configs --- pythonnet.sln | 84 +++++++++++++++++++++ src/clrmodule/clrmodule.csproj | 64 ++++++++++++++++ src/console/Console.csproj | 68 +++++++++++++++++ src/embed_tests/Python.EmbeddingTest.csproj | 68 +++++++++++++++++ src/runtime/Python.Runtime.csproj | 68 +++++++++++++++++ src/testing/Python.Test.csproj | 68 +++++++++++++++++ src/tests/tests.pyproj | 4 + 7 files changed, 424 insertions(+) diff --git a/pythonnet.sln b/pythonnet.sln index 85f7a8303..c5afd66c3 100644 --- a/pythonnet.sln +++ b/pythonnet.sln @@ -16,90 +16,174 @@ Global GlobalSection(SolutionConfigurationPlatforms) = preSolution DebugMono|x64 = DebugMono|x64 DebugMono|x86 = DebugMono|x86 + DebugMonoPY3|x64 = DebugMonoPY3|x64 + DebugMonoPY3|x86 = DebugMonoPY3|x86 DebugWin|x64 = DebugWin|x64 DebugWin|x86 = DebugWin|x86 + DebugWinPY3|x64 = DebugWinPY3|x64 + DebugWinPY3|x86 = DebugWinPY3|x86 ReleaseMono|x64 = ReleaseMono|x64 ReleaseMono|x86 = ReleaseMono|x86 + ReleaseMonoPY3|x64 = ReleaseMonoPY3|x64 + ReleaseMonoPY3|x86 = ReleaseMonoPY3|x86 ReleaseWin|x64 = ReleaseWin|x64 ReleaseWin|x86 = ReleaseWin|x86 + ReleaseWinPY3|x64 = ReleaseWinPY3|x64 + ReleaseWinPY3|x86 = ReleaseWinPY3|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugMono|x64.ActiveCfg = DebugMono|x64 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugMono|x64.Build.0 = DebugMono|x64 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugMono|x86.ActiveCfg = DebugMono|x86 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugMono|x86.Build.0 = DebugMono|x86 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugMonoPY3|x64.ActiveCfg = DebugMonoPY3|x64 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugMonoPY3|x64.Build.0 = DebugMonoPY3|x64 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugMonoPY3|x86.ActiveCfg = DebugMonoPY3|x86 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugMonoPY3|x86.Build.0 = DebugMonoPY3|x86 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugWin|x64.ActiveCfg = DebugWin|x64 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugWin|x64.Build.0 = DebugWin|x64 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugWin|x86.ActiveCfg = DebugWin|x86 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugWin|x86.Build.0 = DebugWin|x86 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugWinPY3|x64.ActiveCfg = DebugWinPY3|x64 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugWinPY3|x64.Build.0 = DebugWinPY3|x64 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugWinPY3|x86.ActiveCfg = DebugWinPY3|x86 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.DebugWinPY3|x86.Build.0 = DebugWinPY3|x86 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseMono|x64.ActiveCfg = ReleaseMono|x64 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseMono|x64.Build.0 = ReleaseMono|x64 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseMono|x86.ActiveCfg = ReleaseMono|x86 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseMono|x86.Build.0 = ReleaseMono|x86 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseMonoPY3|x64.ActiveCfg = ReleaseMonoPY3|x64 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseMonoPY3|x64.Build.0 = ReleaseMonoPY3|x64 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseMonoPY3|x86.ActiveCfg = ReleaseMonoPY3|x86 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseMonoPY3|x86.Build.0 = ReleaseMonoPY3|x86 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseWin|x64.ActiveCfg = ReleaseWin|x64 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseWin|x64.Build.0 = ReleaseWin|x64 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseWin|x86.ActiveCfg = ReleaseWin|x86 {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseWin|x86.Build.0 = ReleaseWin|x86 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseWinPY3|x64.ActiveCfg = ReleaseWinPY3|x64 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseWinPY3|x64.Build.0 = ReleaseWinPY3|x64 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseWinPY3|x86.ActiveCfg = ReleaseWinPY3|x86 + {097B4AC0-74E9-4C58-BCF8-C69746EC8271}.ReleaseWinPY3|x86.Build.0 = ReleaseWinPY3|x86 {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugMono|x64.ActiveCfg = DebugMono|x64 {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugMono|x64.Build.0 = DebugMono|x64 {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugMono|x86.ActiveCfg = DebugMono|x86 {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugMono|x86.Build.0 = DebugMono|x86 + {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugMonoPY3|x64.ActiveCfg = DebugMonoPY3|x64 + {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugMonoPY3|x64.Build.0 = DebugMonoPY3|x64 + {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugMonoPY3|x86.ActiveCfg = DebugMonoPY3|x86 + {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugMonoPY3|x86.Build.0 = DebugMonoPY3|x86 {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugWin|x64.ActiveCfg = DebugWin|x64 {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugWin|x64.Build.0 = DebugWin|x64 {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugWin|x86.ActiveCfg = DebugWin|x86 {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugWin|x86.Build.0 = DebugWin|x86 + {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugWinPY3|x64.ActiveCfg = DebugWinPY3|x64 + {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugWinPY3|x64.Build.0 = DebugWinPY3|x64 + {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugWinPY3|x86.ActiveCfg = DebugWinPY3|x86 + {6F401A34-273B-450F-9A4C-13550BE0767B}.DebugWinPY3|x86.Build.0 = DebugWinPY3|x86 {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseMono|x64.ActiveCfg = ReleaseMono|x64 {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseMono|x64.Build.0 = ReleaseMono|x64 {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseMono|x86.ActiveCfg = ReleaseMono|x86 {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseMono|x86.Build.0 = ReleaseMono|x86 + {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseMonoPY3|x64.ActiveCfg = ReleaseMonoPY3|x64 + {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseMonoPY3|x64.Build.0 = ReleaseMonoPY3|x64 + {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseMonoPY3|x86.ActiveCfg = ReleaseMonoPY3|x86 + {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseMonoPY3|x86.Build.0 = ReleaseMonoPY3|x86 {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseWin|x64.ActiveCfg = ReleaseWin|x64 {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseWin|x64.Build.0 = ReleaseWin|x64 {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseWin|x86.ActiveCfg = ReleaseWin|x86 {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseWin|x86.Build.0 = ReleaseWin|x86 + {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseWinPY3|x64.ActiveCfg = ReleaseWinPY3|x64 + {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseWinPY3|x64.Build.0 = ReleaseWinPY3|x64 + {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseWinPY3|x86.ActiveCfg = ReleaseWinPY3|x86 + {6F401A34-273B-450F-9A4C-13550BE0767B}.ReleaseWinPY3|x86.Build.0 = ReleaseWinPY3|x86 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugMono|x64.ActiveCfg = DebugMono|x64 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugMono|x64.Build.0 = DebugMono|x64 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugMono|x86.ActiveCfg = DebugMono|x86 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugMono|x86.Build.0 = DebugMono|x86 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugMonoPY3|x64.ActiveCfg = DebugMonoPY3|x64 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugMonoPY3|x64.Build.0 = DebugMonoPY3|x64 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugMonoPY3|x86.ActiveCfg = DebugMonoPY3|x86 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugMonoPY3|x86.Build.0 = DebugMonoPY3|x86 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugWin|x64.ActiveCfg = DebugWin|x64 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugWin|x64.Build.0 = DebugWin|x64 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugWin|x86.ActiveCfg = DebugWin|x86 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugWin|x86.Build.0 = DebugWin|x86 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugWinPY3|x64.ActiveCfg = DebugWinPY3|x64 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugWinPY3|x64.Build.0 = DebugWinPY3|x64 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugWinPY3|x86.ActiveCfg = DebugWinPY3|x86 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.DebugWinPY3|x86.Build.0 = DebugWinPY3|x86 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseMono|x64.ActiveCfg = ReleaseMono|x64 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseMono|x64.Build.0 = ReleaseMono|x64 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseMono|x86.ActiveCfg = ReleaseMono|x86 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseMono|x86.Build.0 = ReleaseMono|x86 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseMonoPY3|x64.ActiveCfg = ReleaseMonoPY3|x64 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseMonoPY3|x64.Build.0 = ReleaseMonoPY3|x64 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseMonoPY3|x86.ActiveCfg = ReleaseMonoPY3|x86 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseMonoPY3|x86.Build.0 = ReleaseMonoPY3|x86 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWin|x64.ActiveCfg = ReleaseWin|x64 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWin|x64.Build.0 = ReleaseWin|x64 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWin|x86.ActiveCfg = ReleaseWin|x86 {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWin|x86.Build.0 = ReleaseWin|x86 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWinPY3|x64.ActiveCfg = ReleaseWinPY3|x64 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWinPY3|x64.Build.0 = ReleaseWinPY3|x64 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWinPY3|x86.ActiveCfg = ReleaseWinPY3|x86 + {4165C59D-2822-499F-A6DB-EACA4C331EB5}.ReleaseWinPY3|x86.Build.0 = ReleaseWinPY3|x86 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x64.ActiveCfg = DebugMono|x64 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x64.Build.0 = DebugMono|x64 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x86.ActiveCfg = DebugMono|x86 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMono|x86.Build.0 = DebugMono|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMonoPY3|x64.ActiveCfg = DebugMonoPY3|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMonoPY3|x64.Build.0 = DebugMonoPY3|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMonoPY3|x86.ActiveCfg = DebugMonoPY3|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugMonoPY3|x86.Build.0 = DebugMonoPY3|x86 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x64.ActiveCfg = DebugWin|x64 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x64.Build.0 = DebugWin|x64 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x86.ActiveCfg = DebugWin|x86 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWin|x86.Build.0 = DebugWin|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWinPY3|x64.ActiveCfg = DebugWinPY3|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWinPY3|x64.Build.0 = DebugWinPY3|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWinPY3|x86.ActiveCfg = DebugWinPY3|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.DebugWinPY3|x86.Build.0 = DebugWinPY3|x86 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x64.ActiveCfg = ReleaseMono|x64 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x64.Build.0 = ReleaseMono|x64 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x86.ActiveCfg = ReleaseMono|x86 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMono|x86.Build.0 = ReleaseMono|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMonoPY3|x64.ActiveCfg = ReleaseMonoPY3|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMonoPY3|x64.Build.0 = ReleaseMonoPY3|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMonoPY3|x86.ActiveCfg = ReleaseMonoPY3|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseMonoPY3|x86.Build.0 = ReleaseMonoPY3|x86 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x64.ActiveCfg = ReleaseWin|x64 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x64.Build.0 = ReleaseWin|x64 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x86.ActiveCfg = ReleaseWin|x86 {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWin|x86.Build.0 = ReleaseWin|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWinPY3|x64.ActiveCfg = ReleaseWinPY3|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWinPY3|x64.Build.0 = ReleaseWinPY3|x64 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWinPY3|x86.ActiveCfg = ReleaseWinPY3|x86 + {E29DCF0A-5114-4A98-B1DD-71264B6EA349}.ReleaseWinPY3|x86.Build.0 = ReleaseWinPY3|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMono|x64.ActiveCfg = DebugMono|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMono|x86.ActiveCfg = DebugMono|x86 + {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMonoPY3|x64.ActiveCfg = DebugMonoPY3|x64 + {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugMonoPY3|x86.ActiveCfg = DebugMonoPY3|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWin|x64.ActiveCfg = DebugWin|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWin|x64.Build.0 = DebugWin|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWin|x86.ActiveCfg = DebugWin|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWin|x86.Build.0 = DebugWin|x86 + {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWinPY3|x64.ActiveCfg = DebugWinPY3|x64 + {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWinPY3|x64.Build.0 = DebugWinPY3|x64 + {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWinPY3|x86.ActiveCfg = DebugWinPY3|x86 + {86E834DE-1139-4511-96CC-69636A56E7AC}.DebugWinPY3|x86.Build.0 = DebugWinPY3|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseMono|x64.ActiveCfg = ReleaseMono|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseMono|x86.ActiveCfg = ReleaseMono|x86 + {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseMonoPY3|x64.ActiveCfg = ReleaseMonoPY3|x64 + {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseMonoPY3|x86.ActiveCfg = ReleaseMonoPY3|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWin|x64.ActiveCfg = ReleaseWin|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWin|x64.Build.0 = ReleaseWin|x64 {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWin|x86.ActiveCfg = ReleaseWin|x86 {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWin|x86.Build.0 = ReleaseWin|x86 + {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWinPY3|x64.ActiveCfg = ReleaseWinPY3|x64 + {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWinPY3|x64.Build.0 = ReleaseWinPY3|x64 + {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWinPY3|x86.ActiveCfg = ReleaseWinPY3|x86 + {86E834DE-1139-4511-96CC-69636A56E7AC}.ReleaseWinPY3|x86.Build.0 = ReleaseWinPY3|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index 44d809f05..8939d5ad0 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -79,6 +79,70 @@ x64 prompt + + true + bin\ + TRACE;DEBUG;PYTHON3 + full + x86 + prompt + + + true + bin\ + TRACE;DEBUG;PYTHON3 + full + x64 + prompt + + + bin\ + PYTHON3 + true + pdbonly + x86 + prompt + + + bin\ + PYTHON3 + true + pdbonly + x64 + prompt + + + true + bin\ + TRACE;DEBUG;PYTHON3 + full + x86 + prompt + + + true + bin\ + TRACE;DEBUG;PYTHON3 + full + x64 + prompt + + + bin\ + PYTHON3 + true + pdbonly + x86 + prompt + + + bin\ + PYTHON3 + true + pdbonly + x64 + prompt + ..\..\packages\UnmanagedExports.1.2.7\lib\net\RGiesecke.DllExport.Metadata.dll diff --git a/src/console/Console.csproj b/src/console/Console.csproj index 1ec09736b..49fd402dc 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -83,6 +83,74 @@ x64 prompt + + true + bin\ + DEBUG;TRACE + full + x86 + prompt + + + true + bin\ + DEBUG;TRACE + full + x64 + prompt + + + bin\ + + + true + pdbonly + x86 + prompt + + + bin\ + + + true + pdbonly + x64 + prompt + + + true + bin\ + DEBUG;TRACE + full + x86 + prompt + + + true + bin\ + DEBUG;TRACE + full + x64 + prompt + + + bin\ + + + true + pdbonly + x86 + prompt + + + bin\ + + + true + pdbonly + x64 + prompt + $(PythonManifest) diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 34724247f..7e083d5e0 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -81,6 +81,74 @@ x64 prompt + + true + bin\ + DEBUG;TRACE + full + x86 + prompt + + + true + bin\ + DEBUG;TRACE + full + x64 + prompt + + + bin\ + + + true + pdbonly + x86 + prompt + + + bin\ + + + true + pdbonly + x64 + prompt + + + true + bin\ + DEBUG;TRACE + full + x86 + prompt + + + true + bin\ + DEBUG;TRACE + full + x64 + prompt + + + bin\ + + + true + pdbonly + x86 + prompt + + + bin\ + + + true + pdbonly + x64 + prompt + ..\..\packages\NUnit.3.5.0\lib\net40\nunit.framework.dll diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 091aac643..5d4d2161b 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -79,6 +79,74 @@ full x64 + + bin\ + PYTHON3;PYTHON35;UCS4 + true + true + pdbonly + x86 + + + bin\ + PYTHON3;PYTHON35;UCS4 + true + true + pdbonly + x64 + + + bin\ + PYTHON3;PYTHON35;UCS2 + true + true + pdbonly + x86 + + + bin\ + PYTHON3;PYTHON35;UCS2 + true + true + pdbonly + x64 + + + true + bin\ + TRACE;DEBUG;PYTHON3;PYTHON35;UCS4 + true + false + full + x86 + + + true + bin\ + TRACE;DEBUG;PYTHON3;PYTHON35;UCS4 + true + false + full + x64 + + + true + bin\ + TRACE;DEBUG;PYTHON3;PYTHON35;UCS2 + true + false + full + x86 + + + true + bin\ + TRACE;DEBUG;PYTHON3;PYTHON35;UCS2 + true + false + full + x64 + diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index fa01790fc..3201cd635 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -82,6 +82,74 @@ x64 prompt + + true + bin\ + DEBUG;TRACE + full + x86 + prompt + + + true + bin\ + DEBUG;TRACE + full + x64 + prompt + + + bin\ + + + true + pdbonly + x86 + prompt + + + bin\ + + + true + pdbonly + x64 + prompt + + + true + bin\ + DEBUG;TRACE + full + x86 + prompt + + + true + bin\ + DEBUG;TRACE + full + x64 + prompt + + + bin\ + + + true + pdbonly + x86 + prompt + + + bin\ + + + true + pdbonly + x64 + prompt + diff --git a/src/tests/tests.pyproj b/src/tests/tests.pyproj index 737ec2e79..cf8f74a4a 100644 --- a/src/tests/tests.pyproj +++ b/src/tests/tests.pyproj @@ -18,6 +18,10 @@ + + + + 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets From 3f914ca98d699a7a8c693ee05601363cf2e65098 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Feb 2017 11:38:39 -0700 Subject: [PATCH 068/245] Update test PyImport path Changed when consolidate output paths --- src/embed_tests/pyimport.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index 0e4cb3806..e4ba8d546 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -22,7 +22,7 @@ public void SetUp() * using reflection to circumvent the private * modifiers placed on most Runtime methods. */ - const string s = @"../../../../tests"; + const string s = @"../../tests"; string testPath = Path.Combine(TestContext.CurrentContext.TestDirectory, s); From b8234001e43a0427aa2cc8ae379b2eb280e1ee4c Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Feb 2017 15:19:29 -0700 Subject: [PATCH 069/245] Update runtime.csproj --- src/runtime/Python.Runtime.csproj | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 5d4d2161b..4ddd312b1 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -81,7 +81,7 @@ bin\ - PYTHON3;PYTHON35;UCS4 + PYTHON3;PYTHON36;UCS4 true true pdbonly @@ -89,7 +89,7 @@ bin\ - PYTHON3;PYTHON35;UCS4 + PYTHON3;PYTHON36;UCS4 true true pdbonly @@ -97,7 +97,7 @@ bin\ - PYTHON3;PYTHON35;UCS2 + PYTHON3;PYTHON36;UCS2 true true pdbonly @@ -105,7 +105,7 @@ bin\ - PYTHON3;PYTHON35;UCS2 + PYTHON3;PYTHON36;UCS2 true true pdbonly @@ -114,7 +114,7 @@ true bin\ - TRACE;DEBUG;PYTHON3;PYTHON35;UCS4 + TRACE;DEBUG;PYTHON3;PYTHON36;UCS4 true false full @@ -123,7 +123,7 @@ true bin\ - TRACE;DEBUG;PYTHON3;PYTHON35;UCS4 + TRACE;DEBUG;PYTHON3;PYTHON36;UCS4 true false full @@ -132,7 +132,7 @@ true bin\ - TRACE;DEBUG;PYTHON3;PYTHON35;UCS2 + TRACE;DEBUG;PYTHON3;PYTHON36;UCS2 true false full @@ -141,7 +141,7 @@ true bin\ - TRACE;DEBUG;PYTHON3;PYTHON35;UCS2 + TRACE;DEBUG;PYTHON3;PYTHON36;UCS2 true false full From 6ce9b53fae6fdf8a7fe11ff71ee5d570d3e2a647 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Feb 2017 15:27:22 -0700 Subject: [PATCH 070/245] Documentation clean-up --- src/runtime/classmanager.cs | 1 - src/runtime/constructorbinding.cs | 16 +++++----- src/runtime/exceptions.cs | 10 +------ src/runtime/pyobject.cs | 50 ------------------------------- src/runtime/pythonengine.cs | 15 ---------- 5 files changed, 10 insertions(+), 82 deletions(-) diff --git a/src/runtime/classmanager.cs b/src/runtime/classmanager.cs index 2af783f12..c4a02e563 100644 --- a/src/runtime/classmanager.cs +++ b/src/runtime/classmanager.cs @@ -10,7 +10,6 @@ namespace Python.Runtime /// /// The ClassManager is responsible for creating and managing instances /// that implement the Python type objects that reflect managed classes. - /// /// Each managed type reflected to Python is represented by an instance /// of a concrete subclass of ClassBase. Each instance is associated with /// a generated Python type object, whose slots point to static methods diff --git a/src/runtime/constructorbinding.cs b/src/runtime/constructorbinding.cs index 6a929eff7..ea48f97ce 100644 --- a/src/runtime/constructorbinding.cs +++ b/src/runtime/constructorbinding.cs @@ -9,14 +9,13 @@ namespace Python.Runtime /// /// /// ClassManager stores a ConstructorBinding instance in the class's __dict__['Overloads'] - /// /// SomeType.Overloads[Type, ...] works like this: /// 1) Python retreives the Overloads attribute from this ClassObject's dictionary normally /// and finds a non-null tp_descr_get slot which is called by the interpreter /// and returns an IncRef()ed pyHandle to itself. /// 2) The ConstructorBinding object handles the [] syntax in its mp_subscript by matching /// the Type object parameters to a contructor overload using Type.GetConstructor() - /// [NOTE: I don't know why method overloads are not searched the same way.] + /// [NOTE: I don't know why method overloads are not searched the same way.] /// and creating the BoundContructor oject which contains ContructorInfo object. /// 3) In tp_call, if ctorInfo is not null, ctorBinder.InvokeRaw() is called. /// @@ -43,12 +42,15 @@ public ConstructorBinding(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBi /// selection. /// /// PyObject* to a Constructors wrapper - /// the instance that the attribute was accessed through, - /// or None when the attribute is accessed through the owner + /// + /// the instance that the attribute was accessed through, + /// or None when the attribute is accessed through the owner + /// /// always the owner class - /// a CtorMapper (that borrows a reference to this python type and the - /// ClassObject's ConstructorBinder) wrapper. - /// + /// + /// a CtorMapper (that borrows a reference to this python type and the + /// ClassObject's ConstructorBinder) wrapper. + /// /// /// Python 2.6.5 docs: /// object.__get__(self, instance, owner) diff --git a/src/runtime/exceptions.cs b/src/runtime/exceptions.cs index 448655213..33d5d2ecd 100644 --- a/src/runtime/exceptions.cs +++ b/src/runtime/exceptions.cs @@ -183,9 +183,8 @@ internal unsafe static void ErrorCheck(IntPtr pointer) } /// - /// Shortcut for (pointer == NULL or ErrorOccurred()) -> throw PythonException + /// Shortcut for (pointer == NULL or ErrorOccurred()) -> throw PythonException /// - /// Shortcut for (pointer == NULL) -> throw PythonException internal unsafe static void ErrorOccurredCheck(IntPtr pointer) { if ((pointer == IntPtr.Zero) || Exceptions.ErrorOccurred()) @@ -197,7 +196,6 @@ internal unsafe static void ErrorOccurredCheck(IntPtr pointer) /// /// ExceptionMatches Method /// - /// /// /// Returns true if the current Python exception matches the given /// Python object. This is a wrapper for PyErr_ExceptionMatches. @@ -210,7 +208,6 @@ public static bool ExceptionMatches(IntPtr ob) /// /// ExceptionMatches Method /// - /// /// /// Returns true if the given Python exception matches the given /// Python object. This is a wrapper for PyErr_GivenExceptionMatches. @@ -224,7 +221,6 @@ public static bool ExceptionMatches(IntPtr exc, IntPtr ob) /// /// SetError Method /// - /// /// /// Sets the current Python exception given a native string. /// This is a wrapper for the Python PyErr_SetString call. @@ -237,7 +233,6 @@ public static void SetError(IntPtr ob, string value) /// /// SetError Method /// - /// /// /// Sets the current Python exception given a Python object. /// This is a wrapper for the Python PyErr_SetObject call. @@ -250,7 +245,6 @@ public static void SetError(IntPtr ob, IntPtr value) /// /// SetError Method /// - /// /// /// Sets the current Python exception given a CLR exception /// object. The CLR exception instance is wrapped as a Python @@ -280,7 +274,6 @@ public static void SetError(Exception e) /// /// ErrorOccurred Method /// - /// /// /// Returns true if an exception occurred in the Python runtime. /// This is a wrapper for the Python PyErr_Occurred call. @@ -293,7 +286,6 @@ public static bool ErrorOccurred() /// /// Clear Method /// - /// /// /// Clear any exception that has been set in the Python runtime. /// diff --git a/src/runtime/pyobject.cs b/src/runtime/pyobject.cs index ccebb708e..ddc0e4c4c 100644 --- a/src/runtime/pyobject.cs +++ b/src/runtime/pyobject.cs @@ -20,7 +20,6 @@ public class PyObject : DynamicObject, IDisposable /// /// PyObject Constructor /// - /// /// /// Creates a new PyObject from an IntPtr object reference. Note that /// the PyObject instance assumes ownership of the object reference @@ -51,7 +50,6 @@ protected PyObject() /// /// Handle Property /// - /// /// /// Gets the native handle of the underlying Python object. This /// value is generally for internal use by the PythonNet runtime. @@ -65,7 +63,6 @@ public IntPtr Handle /// /// FromManagedObject Method /// - /// /// /// Given an arbitrary managed object, return a Python instance that /// reflects the managed object. @@ -86,7 +83,6 @@ public static PyObject FromManagedObject(object ob) /// /// AsManagedObject Method /// - /// /// /// Return a managed object of the given type, based on the /// value of the Python object. @@ -105,7 +101,6 @@ public object AsManagedObject(Type t) /// /// Dispose Method /// - /// /// /// The Dispose method provides a way to explicitly release the /// Python object represented by a PyObject instance. It is a good @@ -139,7 +134,6 @@ public void Dispose() /// /// GetPythonType Method /// - /// /// /// Returns the Python type of the object. This method is equivalent /// to the Python expression: type(object). @@ -154,7 +148,6 @@ public PyObject GetPythonType() /// /// TypeCheck Method /// - /// /// /// Returns true if the object o is of type typeOrClass or a subtype /// of typeOrClass. @@ -168,7 +161,6 @@ public bool TypeCheck(PyObject typeOrClass) /// /// HasAttr Method /// - /// /// /// Returns true if the object has an attribute with the given name. /// @@ -181,7 +173,6 @@ public bool HasAttr(string name) /// /// HasAttr Method /// - /// /// /// Returns true if the object has an attribute with the given name, /// where name is a PyObject wrapping a string or unicode object. @@ -195,7 +186,6 @@ public bool HasAttr(PyObject name) /// /// GetAttr Method /// - /// /// /// Returns the named attribute of the Python object, or raises a /// PythonException if the attribute access fails. @@ -214,7 +204,6 @@ public PyObject GetAttr(string name) /// /// GetAttr Method /// - /// /// /// Returns the named attribute of the Python object, or the given /// default object if the attribute access fails. @@ -234,7 +223,6 @@ public PyObject GetAttr(string name, PyObject _default) /// /// GetAttr Method /// - /// /// /// Returns the named attribute of the Python object or raises a /// PythonException if the attribute access fails. The name argument @@ -254,7 +242,6 @@ public PyObject GetAttr(PyObject name) /// /// GetAttr Method /// - /// /// /// Returns the named attribute of the Python object, or the given /// default object if the attribute access fails. The name argument @@ -275,7 +262,6 @@ public PyObject GetAttr(PyObject name, PyObject _default) /// /// SetAttr Method /// - /// /// /// Set an attribute of the object with the given name and value. This /// method throws a PythonException if the attribute set fails. @@ -293,7 +279,6 @@ public void SetAttr(string name, PyObject value) /// /// SetAttr Method /// - /// /// /// Set an attribute of the object with the given name and value, /// where the name is a Python string or unicode object. This method @@ -312,7 +297,6 @@ public void SetAttr(PyObject name, PyObject value) /// /// DelAttr Method /// - /// /// /// Delete the named attribute of the Python object. This method /// throws a PythonException if the attribute set fails. @@ -330,7 +314,6 @@ public void DelAttr(string name) /// /// DelAttr Method /// - /// /// /// Delete the named attribute of the Python object, where name is a /// PyObject wrapping a Python string or unicode object. This method @@ -349,7 +332,6 @@ public void DelAttr(PyObject name) /// /// GetItem Method /// - /// /// /// For objects that support the Python sequence or mapping protocols, /// return the item at the given object index. This method raises a @@ -369,7 +351,6 @@ public virtual PyObject GetItem(PyObject key) /// /// GetItem Method /// - /// /// /// For objects that support the Python sequence or mapping protocols, /// return the item at the given string index. This method raises a @@ -387,7 +368,6 @@ public virtual PyObject GetItem(string key) /// /// GetItem Method /// - /// /// /// For objects that support the Python sequence or mapping protocols, /// return the item at the given numeric index. This method raises a @@ -405,7 +385,6 @@ public virtual PyObject GetItem(int index) /// /// SetItem Method /// - /// /// /// For objects that support the Python sequence or mapping protocols, /// set the item at the given object index to the given value. This @@ -424,7 +403,6 @@ public virtual void SetItem(PyObject key, PyObject value) /// /// SetItem Method /// - /// /// /// For objects that support the Python sequence or mapping protocols, /// set the item at the given string index to the given value. This @@ -442,7 +420,6 @@ public virtual void SetItem(string key, PyObject value) /// /// SetItem Method /// - /// /// /// For objects that support the Python sequence or mapping protocols, /// set the item at the given numeric index to the given value. This @@ -460,7 +437,6 @@ public virtual void SetItem(int index, PyObject value) /// /// DelItem Method /// - /// /// /// For objects that support the Python sequence or mapping protocols, /// delete the item at the given object index. This method raises a @@ -479,7 +455,6 @@ public virtual void DelItem(PyObject key) /// /// DelItem Method /// - /// /// /// For objects that support the Python sequence or mapping protocols, /// delete the item at the given string index. This method raises a @@ -497,7 +472,6 @@ public virtual void DelItem(string key) /// /// DelItem Method /// - /// /// /// For objects that support the Python sequence or mapping protocols, /// delete the item at the given numeric index. This method raises a @@ -515,7 +489,6 @@ public virtual void DelItem(int index) /// /// Length Method /// - /// /// /// Returns the length for objects that support the Python sequence /// protocol, or 0 if the object does not support the protocol. @@ -535,7 +508,6 @@ public virtual int Length() /// /// String Indexer /// - /// /// /// Provides a shorthand for the string versions of the GetItem and /// SetItem methods. @@ -550,7 +522,6 @@ public virtual PyObject this[string key] /// /// PyObject Indexer /// - /// /// /// Provides a shorthand for the object versions of the GetItem and /// SetItem methods. @@ -565,7 +536,6 @@ public virtual PyObject this[PyObject key] /// /// Numeric Indexer /// - /// /// /// Provides a shorthand for the numeric versions of the GetItem and /// SetItem methods. @@ -580,7 +550,6 @@ public virtual PyObject this[int index] /// /// GetIterator Method /// - /// /// /// Return a new (Python) iterator for the object. This is equivalent /// to the Python expression "iter(object)". A PythonException will be @@ -599,7 +568,6 @@ public PyObject GetIterator() /// /// GetEnumerator Method /// - /// /// /// Return a new PyIter object for the object. This allows any iterable /// python object to be iterated over in C#. A PythonException will be @@ -614,7 +582,6 @@ public IEnumerator GetEnumerator() /// /// Invoke Method /// - /// /// /// Invoke the callable object with the given arguments, passed as a /// PyObject[]. A PythonException is raised if the invokation fails. @@ -635,7 +602,6 @@ public PyObject Invoke(params PyObject[] args) /// /// Invoke Method /// - /// /// /// Invoke the callable object with the given arguments, passed as a /// Python tuple. A PythonException is raised if the invokation fails. @@ -654,7 +620,6 @@ public PyObject Invoke(PyTuple args) /// /// Invoke Method /// - /// /// /// Invoke the callable object with the given positional and keyword /// arguments. A PythonException is raised if the invokation fails. @@ -675,7 +640,6 @@ public PyObject Invoke(PyObject[] args, PyDict kw) /// /// Invoke Method /// - /// /// /// Invoke the callable object with the given positional and keyword /// arguments. A PythonException is raised if the invokation fails. @@ -694,7 +658,6 @@ public PyObject Invoke(PyTuple args, PyDict kw) /// /// InvokeMethod Method /// - /// /// /// Invoke the named method of the object with the given arguments. /// A PythonException is raised if the invokation is unsuccessful. @@ -711,7 +674,6 @@ public PyObject InvokeMethod(string name, params PyObject[] args) /// /// InvokeMethod Method /// - /// /// /// Invoke the named method of the object with the given arguments. /// A PythonException is raised if the invokation is unsuccessful. @@ -728,7 +690,6 @@ public PyObject InvokeMethod(string name, PyTuple args) /// /// InvokeMethod Method /// - /// /// /// Invoke the named method of the object with the given arguments /// and keyword arguments. Keyword args are passed as a PyDict object. @@ -746,7 +707,6 @@ public PyObject InvokeMethod(string name, PyObject[] args, PyDict kw) /// /// InvokeMethod Method /// - /// /// /// Invoke the named method of the object with the given arguments /// and keyword arguments. Keyword args are passed as a PyDict object. @@ -764,7 +724,6 @@ public PyObject InvokeMethod(string name, PyTuple args, PyDict kw) /// /// IsInstance Method /// - /// /// /// Return true if the object is an instance of the given Python type /// or class. This method always succeeds. @@ -784,7 +743,6 @@ public bool IsInstance(PyObject typeOrClass) /// /// IsSubclass Method /// - /// /// /// Return true if the object is identical to or derived from the /// given Python type or class. This method always succeeds. @@ -804,7 +762,6 @@ public bool IsSubclass(PyObject typeOrClass) /// /// IsCallable Method /// - /// /// /// Returns true if the object is a callable object. This method /// always succeeds. @@ -818,7 +775,6 @@ public bool IsCallable() /// /// IsIterable Method /// - /// /// /// Returns true if the object is iterable object. This method /// always succeeds. @@ -832,7 +788,6 @@ public bool IsIterable() /// /// IsTrue Method /// - /// /// /// Return true if the object is true according to Python semantics. /// This method always succeeds. @@ -846,7 +801,6 @@ public bool IsTrue() /// /// Dir Method /// - /// /// /// Return a list of the names of the attributes of the object. This /// is equivalent to the Python expression "dir(object)". @@ -865,7 +819,6 @@ public PyList Dir() /// /// Repr Method /// - /// /// /// Return a string representation of the object. This method is /// the managed equivalent of the Python expression "repr(object)". @@ -882,7 +835,6 @@ public string Repr() /// /// ToString Method /// - /// /// /// Return the string representation of the object. This method is /// the managed equivalent of the Python expression "str(object)". @@ -899,7 +851,6 @@ public override string ToString() /// /// Equals Method /// - /// /// /// Return true if this object is equal to the given object. This /// method is based on Python equality semantics. @@ -926,7 +877,6 @@ public override bool Equals(object o) /// /// GetHashCode Method /// - /// /// /// Return a hashcode based on the Python object. This returns the /// hash as computed by Python, equivalent to the Python expression diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index a2eccff0d..c66ae0c47 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -132,7 +132,6 @@ public static void Initialize() /// /// Initialize Method /// - /// /// /// Initialize the Python runtime. It is safe to call this method /// more than once, though initialization will only happen on the @@ -276,7 +275,6 @@ public static void InitExt() /// /// Shutdown Method /// - /// /// /// Shutdown and release resources held by the Python runtime. The /// Python runtime can no longer be used in the current process @@ -295,17 +293,14 @@ public static void Shutdown() /// /// AcquireLock Method /// - /// /// /// Acquire the Python global interpreter lock (GIL). Managed code /// *must* call this method before using any objects or calling any /// methods on objects in the Python.Runtime namespace. The only /// exception is PythonEngine.Initialize, which may be called without /// first calling AcquireLock. - /// /// Each call to AcquireLock must be matched by a corresponding call /// to ReleaseLock, passing the token obtained from AcquireLock. - /// /// For more information, see the "Extending and Embedding" section /// of the Python documentation on www.python.org. /// @@ -318,11 +313,9 @@ public static IntPtr AcquireLock() /// /// ReleaseLock Method /// - /// /// /// Release the Python global interpreter lock using a token obtained /// from a previous call to AcquireLock. - /// /// For more information, see the "Extending and Embedding" section /// of the Python documentation on www.python.org. /// @@ -335,12 +328,10 @@ public static void ReleaseLock(IntPtr gs) /// /// BeginAllowThreads Method /// - /// /// /// Release the Python global interpreter lock to allow other threads /// to run. This is equivalent to the Py_BEGIN_ALLOW_THREADS macro /// provided by the C Python API. - /// /// For more information, see the "Extending and Embedding" section /// of the Python documentation on www.python.org. /// @@ -353,12 +344,10 @@ public static IntPtr BeginAllowThreads() /// /// EndAllowThreads Method /// - /// /// /// Re-aquire the Python global interpreter lock for the current /// thread. This is equivalent to the Py_END_ALLOW_THREADS macro /// provided by the C Python API. - /// /// For more information, see the "Extending and Embedding" section /// of the Python documentation on www.python.org. /// @@ -371,7 +360,6 @@ public static void EndAllowThreads(IntPtr ts) /// /// ImportModule Method /// - /// /// /// Given a fully-qualified module or package name, import the /// module and return the resulting module object as a PyObject @@ -388,7 +376,6 @@ public static PyObject ImportModule(string name) /// /// ReloadModule Method /// - /// /// /// Given a PyObject representing a previously loaded module, reload /// the module. @@ -404,7 +391,6 @@ public static PyObject ReloadModule(PyObject module) /// /// ModuleFromString Method /// - /// /// /// Given a string module name and a string containing Python code, /// execute the code in and return a module of the given name. @@ -422,7 +408,6 @@ public static PyObject ModuleFromString(string name, string code) /// /// RunString Method /// - /// /// /// Run a string containing Python code. Returns the result of /// executing the code string as a PyObject instance, or null if From ebbad479046363906845a250457d31653d099623 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Feb 2017 22:59:15 -0700 Subject: [PATCH 071/245] Downgrade to nunit2 --- appveyor.yml | 2 ++ ci/appveyor_run_tests.ps1 | 12 ++++++------ src/embed_tests/Python.EmbeddingTest.csproj | 5 ++--- src/embed_tests/packages.config | 4 ++-- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 2795a94f8..fd5822ac9 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -10,6 +10,7 @@ environment: PYTHONUNBUFFERED: True PYTHONWARNINGS: 'ignore:::wheel.pep425tags:' PYTHONPATH: C:\testdir + NUNIT: nunit-console CONDA_BLD: C:\conda CONDA_BLD_VERSION: 3.5 @@ -34,6 +35,7 @@ init: - set CONDA_BLD_ARCH=%PLATFORM:x=% - set PYTHON=C:\PYTHON%PYTHON_VERSION:.=% - if %PLATFORM%==x86 (set CONDA_BLD_ARCH=32) + - if %PLATFORM%==x86 (set NUNIT=%NUNIT%-x86) - if %PLATFORM%==x64 (set PYTHON=%PYTHON%-x64) # Prepend newly installed Python to the PATH of this build diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 index 3a7d25af8..78bae50b9 100644 --- a/ci/appveyor_run_tests.ps1 +++ b/ci/appveyor_run_tests.ps1 @@ -3,7 +3,7 @@ # Executable paths for OpenCover # Note if OpenCover fails, it won't affect the exit codes. $OPENCOVER = Resolve-Path .\packages\OpenCover.*\tools\OpenCover.Console.exe -$NUNIT = Resolve-Path .\packages\NUnit.ConsoleRunner*\tools\nunit3-console.exe +$NUNIT = Resolve-Path .\packages\NUnit.Runners*\tools\"$env:NUNIT".exe $PY = Get-Command python # Can't use ".\build\*\Python.EmbeddingTest.dll". Missing framework files. @@ -19,11 +19,11 @@ if ($PYTHON_STATUS -ne 0) { } # Run Embedded tests with C# coverage -# .$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:cs.coverage -target:"$NUNIT" -targetargs:"$CS_TESTS" -returntargetcode -# $NUNIT_STATUS = $LastExitCode -# if ($NUNIT_STATUS -ne 0) { -# Write-Host "Embedded tests failed" -ForegroundColor "Red" -# } +.$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:cs.coverage -target:"$NUNIT" -targetargs:"$CS_TESTS" -returntargetcode +$NUNIT_STATUS = $LastExitCode +if ($NUNIT_STATUS -ne 0) { + Write-Host "Embedded tests failed" -ForegroundColor "Red" +} # Embedded tests failing due to open issues, pass/fail only on Python exit code # if ($PYTHON_STATUS -ne 0 -or $NUNIT_STATUS -ne 0) { diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 7e083d5e0..c9586cf4a 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -150,9 +150,8 @@ prompt - - ..\..\packages\NUnit.3.5.0\lib\net40\nunit.framework.dll - True + + ..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll diff --git a/src/embed_tests/packages.config b/src/embed_tests/packages.config index 8ab5202ce..33152fe85 100644 --- a/src/embed_tests/packages.config +++ b/src/embed_tests/packages.config @@ -1,5 +1,5 @@ - - + + From 8627843e21d2acba9489a5b877cd2547622b919b Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Feb 2017 16:00:03 -0700 Subject: [PATCH 072/245] Syntax cleanup --- src/runtime/arrayobject.cs | 4 +- src/runtime/assemblyinfo.cs | 2 +- src/runtime/assemblymanager.cs | 17 +- src/runtime/classbase.cs | 15 +- src/runtime/classderived.cs | 272 ++++++++++++++++++------------ src/runtime/classmanager.cs | 70 ++++---- src/runtime/classobject.cs | 30 ++-- src/runtime/codegenerator.cs | 2 +- src/runtime/constructorbinding.cs | 52 +++--- src/runtime/converter.cs | 6 +- src/runtime/debughelper.cs | 4 +- src/runtime/delegatemanager.cs | 39 ++--- src/runtime/delegateobject.cs | 19 +-- src/runtime/eventbinding.cs | 18 +- src/runtime/eventobject.cs | 53 +++--- src/runtime/exceptions.cs | 33 ++-- src/runtime/extensiontype.cs | 4 +- src/runtime/genericutil.cs | 10 +- src/runtime/importhook.cs | 25 +-- src/runtime/indexer.cs | 23 ++- src/runtime/interfaceobject.cs | 3 +- src/runtime/metatype.cs | 41 ++--- src/runtime/methodbinder.cs | 160 +++++++++++------- src/runtime/methodbinding.cs | 55 +++--- src/runtime/methodobject.cs | 36 ++-- src/runtime/moduleobject.cs | 87 +++++----- src/runtime/nativecall.cs | 8 +- src/runtime/pynumber.cs | 6 +- src/runtime/pyobject.cs | 62 ++++--- src/runtime/pystring.cs | 2 +- src/runtime/typemanager.cs | 4 +- src/runtime/typemethod.cs | 1 - 32 files changed, 634 insertions(+), 529 deletions(-) diff --git a/src/runtime/arrayobject.cs b/src/runtime/arrayobject.cs index caf40ca50..a10688749 100644 --- a/src/runtime/arrayobject.cs +++ b/src/runtime/arrayobject.cs @@ -117,7 +117,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) try { - value = items.GetValue((int[])args); + value = items.GetValue(args); } catch (IndexOutOfRangeException) { @@ -210,7 +210,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) try { - items.SetValue(value, (int[])args); + items.SetValue(value, args); } catch (IndexOutOfRangeException) { diff --git a/src/runtime/assemblyinfo.cs b/src/runtime/assemblyinfo.cs index 1cbd1e749..a357b81d9 100644 --- a/src/runtime/assemblyinfo.cs +++ b/src/runtime/assemblyinfo.cs @@ -1,8 +1,8 @@ using System; using System.Reflection; using System.Resources; -using System.Runtime.InteropServices; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; [assembly: AssemblyProduct("Python for .NET")] [assembly: AssemblyVersion("4.0.0.1")] diff --git a/src/runtime/assemblymanager.cs b/src/runtime/assemblymanager.cs index 29851c32e..692351f11 100644 --- a/src/runtime/assemblymanager.cs +++ b/src/runtime/assemblymanager.cs @@ -158,12 +158,10 @@ internal static void UpdatePath() public static string FindAssembly(string name) { char sep = Path.DirectorySeparatorChar; - string path; - string temp; - for (var i = 0; i < pypath.Count; i++) + foreach (string head in pypath) { - string head = pypath[i]; + string path; if (head == null || head.Length == 0) { path = name; @@ -173,11 +171,12 @@ public static string FindAssembly(string name) path = head + sep + name; } - temp = path + ".dll"; + string temp = path + ".dll"; if (File.Exists(temp)) { return temp; } + temp = path + ".exe"; if (File.Exists(temp)) { @@ -233,10 +232,8 @@ public static Assembly LoadAssemblyPath(string name) /// /// Loads an assembly using full path. /// - /// - /// - /// - /// + /// + /// public static Assembly LoadAssemblyFullPath(string name) { Assembly assembly = null; @@ -252,7 +249,7 @@ public static Assembly LoadAssemblyFullPath(string name) { assembly = Assembly.LoadFrom(name); } - catch + catch (Exception) { } } diff --git a/src/runtime/classbase.cs b/src/runtime/classbase.cs index 580fcabe4..e480b309a 100644 --- a/src/runtime/classbase.cs +++ b/src/runtime/classbase.cs @@ -1,7 +1,5 @@ using System; using System.Collections; -using System.Reflection; -using System.Security; using System.Runtime.InteropServices; namespace Python.Runtime @@ -27,7 +25,7 @@ internal ClassBase(Type tp) internal virtual bool CanSubclass() { - return (!this.type.IsEnum); + return !type.IsEnum; } /// @@ -49,12 +47,12 @@ public virtual IntPtr type_subscript(IntPtr idx) return Exceptions.RaiseTypeError("type(s) expected"); } - Type target = GenericUtil.GenericForType(this.type, types.Length); + Type target = GenericUtil.GenericForType(type, types.Length); if (target != null) { Type t = target.MakeGenericType(types); - ManagedType c = (ManagedType)ClassManager.GetClass(t); + ManagedType c = ClassManager.GetClass(t); Runtime.XIncref(c.pyHandle); return c.pyHandle; } @@ -115,10 +113,15 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) co1 = GetManagedObject(ob) as CLRObject; co2 = GetManagedObject(other) as CLRObject; if (co1 == null || co2 == null) + { return Exceptions.RaiseTypeError("Cannot get managed object"); + } var co1Comp = co1.inst as IComparable; if (co1Comp == null) - return Exceptions.RaiseTypeError("Cannot convert object of type " + co1.GetType() + " to IComparable"); + { + Type co1Type = co1.GetType(); + return Exceptions.RaiseTypeError($"Cannot convert object of type {co1Type} to IComparable"); + } try { int cmp = co1Comp.CompareTo(co2.inst); diff --git a/src/runtime/classderived.cs b/src/runtime/classderived.cs index c7f60e7af..0f8f156e8 100644 --- a/src/runtime/classderived.cs +++ b/src/runtime/classderived.cs @@ -1,10 +1,8 @@ using System; -using System.IO; -using System.Reflection; -using System.Reflection.Emit; using System.Collections.Generic; -using System.Threading; using System.Linq; +using System.Reflection; +using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Threading.Tasks; @@ -16,15 +14,17 @@ namespace Python.Runtime /// Python type objects. Each of those type objects is associated with /// an instance of ClassObject, which provides its implementation. /// - // interface used to idenfity which C# types were dynamically created as python subclasses + /// + /// interface used to identify which C# types were dynamically created as python subclasses + /// public interface IPythonDerivedType { } internal class ClassDerivedObject : ClassObject { - static private Dictionary assemblyBuilders; - static private Dictionary, ModuleBuilder> moduleBuilders; + private static Dictionary assemblyBuilders; + private static Dictionary, ModuleBuilder> moduleBuilders; static ClassDerivedObject() { @@ -32,30 +32,32 @@ static ClassDerivedObject() moduleBuilders = new Dictionary, ModuleBuilder>(); } - internal ClassDerivedObject(Type tp): base(tp) + internal ClassDerivedObject(Type tp) : base(tp) { } /// /// Implements __new__ for derived classes of reflected classes. - /// - new public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) + /// + public new static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { - ClassDerivedObject cls = GetManagedObject(tp) as ClassDerivedObject; + var cls = GetManagedObject(tp) as ClassDerivedObject; // call the managed constructor - Object obj = cls.binder.InvokeRaw(IntPtr.Zero, args, kw); + object obj = cls.binder.InvokeRaw(IntPtr.Zero, args, kw); if (obj == null) + { return IntPtr.Zero; + } // return the pointer to the python object // (this indirectly calls ClassDerivedObject.ToPython) return Converter.ToPython(obj, cls.GetType()); } - new public static void tp_dealloc(IntPtr ob) + public new static void tp_dealloc(IntPtr ob) { - CLRObject self = (CLRObject)GetManagedObject(ob); + var self = (CLRObject)GetManagedObject(ob); // don't let the python GC destroy this object Runtime.PyObject_GC_UnTrack(self.pyHandle); @@ -70,14 +72,16 @@ internal ClassDerivedObject(Type tp): base(tp) self.gcHandle = gc; } - // Called from Converter.ToPython for types that are python subclasses of managed types. - // The referenced python object is returned instead of a new wrapper. + /// + /// Called from Converter.ToPython for types that are python subclasses of managed types. + /// The referenced python object is returned instead of a new wrapper. + /// internal static IntPtr ToPython(IPythonDerivedType obj) { // derived types have a __pyobj__ field that gets set to the python - // object in the overriden constructor + // object in the overridden constructor FieldInfo fi = obj.GetType().GetField("__pyobj__"); - CLRObject self = (CLRObject)fi.GetValue(obj); + var self = (CLRObject)fi.GetValue(obj); Runtime.XIncref(self.pyHandle); @@ -102,8 +106,8 @@ internal static IntPtr ToPython(IPythonDerivedType obj) /// /// Creates a new managed type derived from a base type with any virtual - /// methods overriden to call out to python if the associated python - /// object has overriden the method. + /// methods overridden to call out to python if the associated python + /// object has overridden the method. /// internal static Type CreateDerivedType(string name, Type baseType, @@ -113,31 +117,35 @@ internal static Type CreateDerivedType(string name, string moduleName = "Python.Runtime.Dynamic.dll") { if (null != namespaceStr) + { name = namespaceStr + "." + name; + } if (null == assemblyName) + { assemblyName = Assembly.GetExecutingAssembly().FullName; + } ModuleBuilder moduleBuilder = GetModuleBuilder(assemblyName, moduleName); - TypeBuilder typeBuilder; Type baseClass = baseType; - List interfaces = new List { typeof(IPythonDerivedType) }; + var interfaces = new List { typeof(IPythonDerivedType) }; // if the base type is an interface then use System.Object as the base class // and add the base type to the list of interfaces this new class will implement. if (baseType.IsInterface) { interfaces.Add(baseType); - baseClass = typeof(System.Object); + baseClass = typeof(object); } - typeBuilder = moduleBuilder.DefineType(name, + TypeBuilder typeBuilder = moduleBuilder.DefineType(name, TypeAttributes.Public | TypeAttributes.Class, baseClass, interfaces.ToArray()); // add a field for storing the python object pointer + // FIXME: fb not used FieldBuilder fb = typeBuilder.DefineField("__pyobj__", typeof(CLRObject), FieldAttributes.Public); // override any constructors @@ -147,17 +155,18 @@ internal static Type CreateDerivedType(string name, AddConstructor(ctor, baseType, typeBuilder); } - // Override any properties explicitly overriden in python - HashSet pyProperties = new HashSet(); + // Override any properties explicitly overridden in python + var pyProperties = new HashSet(); if (py_dict != IntPtr.Zero && Runtime.PyDict_Check(py_dict)) { Runtime.XIncref(py_dict); - using (PyDict dict = new PyDict(py_dict)) + using (var dict = new PyDict(py_dict)) using (PyObject keys = dict.Keys()) { foreach (PyObject pyKey in keys) { using (PyObject value = dict[pyKey]) + { if (value.HasAttr("_clr_property_type_")) { string propertyName = pyKey.ToString(); @@ -166,23 +175,28 @@ internal static Type CreateDerivedType(string name, // Add the property to the type AddPythonProperty(propertyName, value, typeBuilder); } + } } } } - // override any virtual methods not already overriden by the properties above + // override any virtual methods not already overridden by the properties above MethodInfo[] methods = baseType.GetMethods(); - HashSet virtualMethods = new HashSet(); + var virtualMethods = new HashSet(); foreach (MethodInfo method in methods) { if (!method.Attributes.HasFlag(MethodAttributes.Virtual) | method.Attributes.HasFlag(MethodAttributes.Final)) + { continue; + } - // skip if this property has already been overriden + // skip if this property has already been overridden if ((method.Name.StartsWith("get_") || method.Name.StartsWith("set_")) && pyProperties.Contains(method.Name.Substring(4))) + { continue; + } // keep track of the virtual methods redirected to the python instance virtualMethods.Add(method.Name); @@ -195,23 +209,27 @@ internal static Type CreateDerivedType(string name, if (py_dict != IntPtr.Zero && Runtime.PyDict_Check(py_dict)) { Runtime.XIncref(py_dict); - using (PyDict dict = new PyDict(py_dict)) + using (var dict = new PyDict(py_dict)) using (PyObject keys = dict.Keys()) { foreach (PyObject pyKey in keys) { using (PyObject value = dict[pyKey]) + { if (value.HasAttr("_clr_return_type_") && value.HasAttr("_clr_arg_types_")) { string methodName = pyKey.ToString(); // if this method has already been redirected to the python method skip it if (virtualMethods.Contains(methodName)) + { continue; + } // Add the method to the type AddPythonMethod(methodName, value, typeBuilder); } + } } } } @@ -237,6 +255,7 @@ internal static Type CreateDerivedType(string name, Assembly assembly = Assembly.GetAssembly(type); AssemblyManager.ScanAssembly(assembly); + // FIXME: assemblyBuilder not used AssemblyBuilder assemblyBuilder = assemblyBuilders[assemblyName]; return type; @@ -265,8 +284,10 @@ private static void AddConstructor(ConstructorInfo ctor, Type baseType, TypeBuil // emit the assembly for calling the original method using call instead of callvirt ILGenerator il = methodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); - for (int i = 0; i < parameters.Length; ++i) + for (var i = 0; i < parameters.Length; ++i) + { il.Emit(OpCodes.Ldarg, i + 1); + } il.Emit(OpCodes.Call, ctor); il.Emit(OpCodes.Ret); @@ -277,20 +298,22 @@ private static void AddConstructor(ConstructorInfo ctor, Type baseType, TypeBuil ctor.CallingConvention, parameterTypes); il = cb.GetILGenerator(); - il.DeclareLocal(typeof(Object[])); + il.DeclareLocal(typeof(object[])); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldstr, baseCtorName); il.Emit(OpCodes.Ldc_I4, parameters.Length); - il.Emit(OpCodes.Newarr, typeof(System.Object)); + il.Emit(OpCodes.Newarr, typeof(object)); il.Emit(OpCodes.Stloc_0); - for (int i = 0; i < parameters.Length; ++i) + for (var i = 0; i < parameters.Length; ++i) { il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldarg, i + 1); if (parameterTypes[i].IsValueType) + { il.Emit(OpCodes.Box, parameterTypes[i]); - il.Emit(OpCodes.Stelem, typeof(Object)); + } + il.Emit(OpCodes.Stelem, typeof(object)); } il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod("InvokeCtor")); @@ -301,7 +324,7 @@ private static void AddConstructor(ConstructorInfo ctor, Type baseType, TypeBuil /// Add a virtual method override that checks for an override on the python instance /// and calls it, otherwise fall back to the base class method. /// - /// virtual method to be overriden + /// virtual method to be overridden /// Python callable object /// TypeBuilder for the new type the method is to be added to private static void AddVirtualMethod(MethodInfo method, Type baseType, TypeBuilder typeBuilder) @@ -324,8 +347,10 @@ private static void AddVirtualMethod(MethodInfo method, Type baseType, TypeBuild // emit the assembly for calling the original method using call instead of callvirt ILGenerator baseIl = baseMethodBuilder.GetILGenerator(); baseIl.Emit(OpCodes.Ldarg_0); - for (int i = 0; i < parameters.Length; ++i) + for (var i = 0; i < parameters.Length; ++i) + { baseIl.Emit(OpCodes.Ldarg, i + 1); + } baseIl.Emit(OpCodes.Call, method); baseIl.Emit(OpCodes.Ret); } @@ -340,27 +365,33 @@ private static void AddVirtualMethod(MethodInfo method, Type baseType, TypeBuild method.ReturnType, parameterTypes); ILGenerator il = methodBuilder.GetILGenerator(); - il.DeclareLocal(typeof(Object[])); + il.DeclareLocal(typeof(object[])); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldstr, method.Name); // don't fall back to the base type's method if it's abstract if (null != baseMethodName) + { il.Emit(OpCodes.Ldstr, baseMethodName); + } else + { il.Emit(OpCodes.Ldnull); + } il.Emit(OpCodes.Ldc_I4, parameters.Length); - il.Emit(OpCodes.Newarr, typeof(System.Object)); + il.Emit(OpCodes.Newarr, typeof(object)); il.Emit(OpCodes.Stloc_0); - for (int i = 0; i < parameters.Length; ++i) + for (var i = 0; i < parameters.Length; ++i) { il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldarg, i + 1); if (parameterTypes[i].IsValueType) + { il.Emit(OpCodes.Box, parameterTypes[i]); - il.Emit(OpCodes.Stelem, typeof(Object)); + } + il.Emit(OpCodes.Stelem, typeof(object)); } il.Emit(OpCodes.Ldloc_0); if (method.ReturnType == typeof(void)) @@ -377,9 +408,9 @@ private static void AddVirtualMethod(MethodInfo method, Type baseType, TypeBuild /// /// Python method may have the following function attributes set to control how they're exposed: - /// - _clr_return_type_ - method return type (required) - /// - _clr_arg_types_ - list of method argument types (required) - /// - _clr_method_name_ - method name, if different from the python method name (optional) + /// - _clr_return_type_ - method return type (required) + /// - _clr_arg_types_ - list of method argument types (required) + /// - _clr_method_name_ - method name, if different from the python method name (optional) /// /// Method name to add to the type /// Python callable object @@ -389,25 +420,33 @@ private static void AddPythonMethod(string methodName, PyObject func, TypeBuilde if (func.HasAttr("_clr_method_name_")) { using (PyObject pyMethodName = func.GetAttr("_clr_method_name_")) + { methodName = pyMethodName.ToString(); + } } using (PyObject pyReturnType = func.GetAttr("_clr_return_type_")) using (PyObject pyArgTypes = func.GetAttr("_clr_arg_types_")) { - Type returnType = pyReturnType.AsManagedObject(typeof(Type)) as Type; + var returnType = pyReturnType.AsManagedObject(typeof(Type)) as Type; if (returnType == null) + { returnType = typeof(void); + } if (!pyArgTypes.IsIterable()) + { throw new ArgumentException("_clr_arg_types_ must be a list or tuple of CLR types"); + } - List argTypes = new List(); + var argTypes = new List(); foreach (PyObject pyArgType in pyArgTypes) { - Type argType = pyArgType.AsManagedObject(typeof(Type)) as Type; + var argType = pyArgType.AsManagedObject(typeof(Type)) as Type; if (argType == null) + { throw new ArgumentException("_clr_arg_types_ must be a list or tuple of CLR types"); + } argTypes.Add(argType); } @@ -423,21 +462,23 @@ private static void AddPythonMethod(string methodName, PyObject func, TypeBuilde argTypes.ToArray()); ILGenerator il = methodBuilder.GetILGenerator(); - il.DeclareLocal(typeof(Object[])); + il.DeclareLocal(typeof(object[])); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldstr, methodName); il.Emit(OpCodes.Ldnull); // don't fall back to the base type's method il.Emit(OpCodes.Ldc_I4, argTypes.Count); - il.Emit(OpCodes.Newarr, typeof(System.Object)); + il.Emit(OpCodes.Newarr, typeof(object)); il.Emit(OpCodes.Stloc_0); - for (int i = 0; i < argTypes.Count; ++i) + for (var i = 0; i < argTypes.Count; ++i) { il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldarg, i + 1); if (argTypes[i].IsValueType) + { il.Emit(OpCodes.Box, argTypes[i]); - il.Emit(OpCodes.Stelem, typeof(Object)); + } + il.Emit(OpCodes.Stelem, typeof(object)); } il.Emit(OpCodes.Ldloc_0); if (returnType == typeof(void)) @@ -455,7 +496,7 @@ private static void AddPythonMethod(string methodName, PyObject func, TypeBuilde /// /// Python properties may have the following function attributes set to control how they're exposed: - /// - _clr_property_type_ - property type (required) + /// - _clr_property_type_ - property type (required) /// /// Property name to add to the type /// Python property object @@ -471,9 +512,11 @@ private static void AddPythonProperty(string propertyName, PyObject func, TypeBu using (PyObject pyPropertyType = func.GetAttr("_clr_property_type_")) { - Type propertyType = pyPropertyType.AsManagedObject(typeof(Type)) as Type; + var propertyType = pyPropertyType.AsManagedObject(typeof(Type)) as Type; if (propertyType == null) + { throw new ArgumentException("_clr_property_type must be a CLR type"); + } PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, @@ -483,6 +526,7 @@ private static void AddPythonProperty(string propertyName, PyObject func, TypeBu if (func.HasAttr("fget")) { using (PyObject pyfget = func.GetAttr("fget")) + { if (pyfget.IsTrue()) { MethodBuilder methodBuilder = typeBuilder.DefineMethod("get_" + propertyName, @@ -499,17 +543,19 @@ private static void AddPythonProperty(string propertyName, PyObject func, TypeBu propertyBuilder.SetGetMethod(methodBuilder); } + } } if (func.HasAttr("fset")) { using (PyObject pyset = func.GetAttr("fset")) + { if (pyset.IsTrue()) { MethodBuilder methodBuilder = typeBuilder.DefineMethod("set_" + propertyName, methodAttribs, null, - new Type[] { propertyType }); + new[] { propertyType }); ILGenerator il = methodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); @@ -521,6 +567,7 @@ private static void AddPythonProperty(string propertyName, PyObject func, TypeBu propertyBuilder.SetSetMethod(methodBuilder); } + } } } } @@ -529,7 +576,7 @@ private static ModuleBuilder GetModuleBuilder(string assemblyName, string module { // find or create a dynamic assembly and module AppDomain domain = AppDomain.CurrentDomain; - ModuleBuilder moduleBuilder = null; + ModuleBuilder moduleBuilder; if (moduleBuilders.ContainsKey(Tuple.Create(assemblyName, moduleName))) { @@ -537,7 +584,7 @@ private static ModuleBuilder GetModuleBuilder(string assemblyName, string module } else { - AssemblyBuilder assemblyBuilder = null; + AssemblyBuilder assemblyBuilder; if (assemblyBuilders.ContainsKey(assemblyName)) { assemblyBuilder = assemblyBuilders[assemblyName]; @@ -557,53 +604,54 @@ private static ModuleBuilder GetModuleBuilder(string assemblyName, string module } } - // - // PythonDerivedType contains static methods used by the dynamically created - // derived type that allow it to call back into python from overriden virtual - // methods, and also handle the construction and destruction of the python - // object. - // - // This has to be public as it's called from methods on dynamically built classes - // potentially in other assemblies. - // + /// + /// PythonDerivedType contains static methods used by the dynamically created + /// derived type that allow it to call back into python from overridden virtual + /// methods, and also handle the construction and destruction of the python + /// object. + /// + /// + /// This has to be public as it's called from methods on dynamically built classes + /// potentially in other assemblies. + /// public class PythonDerivedType { /// - /// This is the implementaion of the overriden methods in the derived + /// This is the implementation of the overridden methods in the derived /// type. It looks for a python method with the same name as the method /// on the managed base class and if it exists and isn't the managed - /// method binding (ie it has been overriden in the derived python + /// method binding (i.e. it has been overridden in the derived python /// class) it calls it, otherwise it calls the base method. /// - public static T InvokeMethod(IPythonDerivedType obj, string methodName, string origMethodName, Object[] args) + public static T InvokeMethod(IPythonDerivedType obj, string methodName, string origMethodName, object[] args) { FieldInfo fi = obj.GetType().GetField("__pyobj__"); - CLRObject self = (CLRObject)fi.GetValue(obj); + var self = (CLRObject)fi.GetValue(obj); if (null != self) { - List disposeList = new List(); + var disposeList = new List(); IntPtr gs = Runtime.PyGILState_Ensure(); try { Runtime.XIncref(self.pyHandle); - PyObject pyself = new PyObject(self.pyHandle); + var pyself = new PyObject(self.pyHandle); disposeList.Add(pyself); Runtime.XIncref(Runtime.PyNone); - PyObject pynone = new PyObject(Runtime.PyNone); + var pynone = new PyObject(Runtime.PyNone); disposeList.Add(pynone); PyObject method = pyself.GetAttr(methodName, pynone); disposeList.Add(method); if (method.Handle != Runtime.PyNone) { - // if the method hasn't been overriden then it will be a managed object + // if the method hasn't been overridden then it will be a managed object ManagedType managedMethod = ManagedType.GetManagedObject(method.Handle); if (null == managedMethod) { - PyObject[] pyargs = new PyObject[args.Length]; - for (int i = 0; i < args.Length; ++i) + var pyargs = new PyObject[args.Length]; + for (var i = 0; i < args.Length; ++i) { pyargs[i] = new PyObject(Converter.ToPythonImplicit(args[i])); disposeList.Add(pyargs[i]); @@ -619,15 +667,16 @@ public static T InvokeMethod(IPythonDerivedType obj, string methodName, strin { foreach (PyObject x in disposeList) { - if (x != null) - x.Dispose(); + x?.Dispose(); } Runtime.PyGILState_Release(gs); } } if (origMethodName == null) + { throw new NotImplementedException("Python object does not have a '" + methodName + "' method"); + } return (T)obj.GetType().InvokeMember(origMethodName, BindingFlags.InvokeMethod, @@ -637,34 +686,34 @@ public static T InvokeMethod(IPythonDerivedType obj, string methodName, strin } public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, string origMethodName, - Object[] args) + object[] args) { FieldInfo fi = obj.GetType().GetField("__pyobj__"); - CLRObject self = (CLRObject)fi.GetValue(obj); + var self = (CLRObject)fi.GetValue(obj); if (null != self) { - List disposeList = new List(); + var disposeList = new List(); IntPtr gs = Runtime.PyGILState_Ensure(); try { Runtime.XIncref(self.pyHandle); - PyObject pyself = new PyObject(self.pyHandle); + var pyself = new PyObject(self.pyHandle); disposeList.Add(pyself); Runtime.XIncref(Runtime.PyNone); - PyObject pynone = new PyObject(Runtime.PyNone); + var pynone = new PyObject(Runtime.PyNone); disposeList.Add(pynone); PyObject method = pyself.GetAttr(methodName, pynone); disposeList.Add(method); if (method.Handle != Runtime.PyNone) { - // if the method hasn't been overriden then it will be a managed object + // if the method hasn't been overridden then it will be a managed object ManagedType managedMethod = ManagedType.GetManagedObject(method.Handle); if (null == managedMethod) { - PyObject[] pyargs = new PyObject[args.Length]; - for (int i = 0; i < args.Length; ++i) + var pyargs = new PyObject[args.Length]; + for (var i = 0; i < args.Length; ++i) { pyargs[i] = new PyObject(Converter.ToPythonImplicit(args[i])); disposeList.Add(pyargs[i]); @@ -680,15 +729,16 @@ public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, s { foreach (PyObject x in disposeList) { - if (x != null) - x.Dispose(); + x?.Dispose(); } Runtime.PyGILState_Release(gs); } } if (origMethodName == null) + { throw new NotImplementedException("Python object does not have a '" + methodName + "' method"); + } obj.GetType().InvokeMember(origMethodName, BindingFlags.InvokeMethod, @@ -700,18 +750,22 @@ public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, s public static T InvokeGetProperty(IPythonDerivedType obj, string propertyName) { FieldInfo fi = obj.GetType().GetField("__pyobj__"); - CLRObject self = (CLRObject)fi.GetValue(obj); + var self = (CLRObject)fi.GetValue(obj); if (null == self) + { throw new NullReferenceException("Instance must be specified when getting a property"); + } IntPtr gs = Runtime.PyGILState_Ensure(); try { Runtime.XIncref(self.pyHandle); - using (PyObject pyself = new PyObject(self.pyHandle)) + using (var pyself = new PyObject(self.pyHandle)) using (PyObject pyvalue = pyself.GetAttr(propertyName)) + { return (T)pyvalue.AsManagedObject(typeof(T)); + } } finally { @@ -722,18 +776,22 @@ public static T InvokeGetProperty(IPythonDerivedType obj, string propertyName public static void InvokeSetProperty(IPythonDerivedType obj, string propertyName, T value) { FieldInfo fi = obj.GetType().GetField("__pyobj__"); - CLRObject self = (CLRObject)fi.GetValue(obj); + var self = (CLRObject)fi.GetValue(obj); if (null == self) + { throw new NullReferenceException("Instance must be specified when setting a property"); + } IntPtr gs = Runtime.PyGILState_Ensure(); try { Runtime.XIncref(self.pyHandle); - using (PyObject pyself = new PyObject(self.pyHandle)) - using (PyObject pyvalue = new PyObject(Converter.ToPythonImplicit(value))) + using (var pyself = new PyObject(self.pyHandle)) + using (var pyvalue = new PyObject(Converter.ToPythonImplicit(value))) + { pyself.SetAttr(propertyName, pyvalue); + } } finally { @@ -741,7 +799,7 @@ public static void InvokeSetProperty(IPythonDerivedType obj, string propertyN } } - public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, Object[] args) + public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, object[] args) { // call the base constructor obj.GetType().InvokeMember(origCtorName, @@ -750,7 +808,7 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, Objec obj, args); - List disposeList = new List(); + var disposeList = new List(); CLRObject self = null; IntPtr gs = Runtime.PyGILState_Ensure(); try @@ -765,11 +823,11 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, Objec fi.SetValue(obj, self); Runtime.XIncref(self.pyHandle); - PyObject pyself = new PyObject(self.pyHandle); + var pyself = new PyObject(self.pyHandle); disposeList.Add(pyself); Runtime.XIncref(Runtime.PyNone); - PyObject pynone = new PyObject(Runtime.PyNone); + var pynone = new PyObject(Runtime.PyNone); disposeList.Add(pynone); // call __init__ @@ -777,12 +835,12 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, Objec disposeList.Add(init); if (init.Handle != Runtime.PyNone) { - // if __init__ hasn't been overriden then it will be a managed object + // if __init__ hasn't been overridden then it will be a managed object ManagedType managedMethod = ManagedType.GetManagedObject(init.Handle); if (null == managedMethod) { - PyObject[] pyargs = new PyObject[args.Length]; - for (int i = 0; i < args.Length; ++i) + var pyargs = new PyObject[args.Length]; + for (var i = 0; i < args.Length; ++i) { pyargs[i] = new PyObject(Converter.ToPython(args[i], args[i]?.GetType())); disposeList.Add(pyargs[i]); @@ -796,15 +854,16 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, Objec { foreach (PyObject x in disposeList) { - if (x != null) - x.Dispose(); + x?.Dispose(); } // Decrement the python object's reference count. // This doesn't actually destroy the object, it just sets the reference to this object // to be a weak reference and it will be destroyed when the C# object is destroyed. if (null != self) + { Runtime.XDecref(self.pyHandle); + } Runtime.PyGILState_Release(gs); } @@ -813,7 +872,7 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, Objec public static void Finalize(IPythonDerivedType obj) { FieldInfo fi = obj.GetType().GetField("__pyobj__"); - CLRObject self = (CLRObject)fi.GetValue(obj); + var self = (CLRObject)fi.GetValue(obj); // If python's been terminated then just free the gchandle. lock (Runtime.IsFinalizingLock) @@ -825,9 +884,10 @@ public static void Finalize(IPythonDerivedType obj) } } - // delete the python object in an asnyc task as we may not be able to acquire + // delete the python object in an async task as we may not be able to acquire // the GIL immediately and we don't want to block the GC thread. - var t = Task.Factory.StartNew(() => + // FIXME: t isn't used + Task t = Task.Factory.StartNew(() => { lock (Runtime.IsFinalizingLock) { @@ -846,7 +906,9 @@ public static void Finalize(IPythonDerivedType obj) // python object. IntPtr dict = Marshal.ReadIntPtr(self.pyHandle, ObjectOffset.DictOffset(self.pyHandle)); if (dict != IntPtr.Zero) + { Runtime.XDecref(dict); + } Runtime.PyObject_GC_Del(self.pyHandle); self.gcHandle.Free(); } diff --git a/src/runtime/classmanager.cs b/src/runtime/classmanager.cs index c4a02e563..333f3e7ce 100644 --- a/src/runtime/classmanager.cs +++ b/src/runtime/classmanager.cs @@ -1,8 +1,8 @@ using System; -using System.Runtime.InteropServices; -using System.Collections.Generic; using System.Collections; +using System.Collections.Generic; using System.Reflection; +using System.Runtime.InteropServices; using System.Security; namespace Python.Runtime @@ -27,11 +27,11 @@ private ClassManager() static ClassManager() { cache = new Dictionary(128); - // SEE: http://msdn.microsoft.com/en-us/library/96b1ayy4%28VS.90%29.aspx + // SEE: https://msdn.microsoft.com/en-us/library/96b1ayy4(v=vs.100).aspx // ""All delegates inherit from MulticastDelegate, which inherits from Delegate."" // Was Delegate, which caused a null MethodInfo returned from GetMethode("Invoke") // and crashed on Linux under Mono. - dtype = typeof(System.MulticastDelegate); + dtype = typeof(MulticastDelegate); } /// @@ -48,7 +48,8 @@ internal static ClassBase GetClass(Type type) } cb = CreateClass(type); cache.Add(type, cb); - // Initialize the object later, as this might call this GetClass method recursivly (for example when a nested class inherits its declaring class...) + // Initialize the object later, as this might call this GetClass method + // recursively (for example when a nested class inherits its declaring class...) InitClassBase(type, cb); return cb; } @@ -137,30 +138,29 @@ private static void InitClassBase(Type type, ClassBase impl) IDictionaryEnumerator iter = info.members.GetEnumerator(); while (iter.MoveNext()) { - ManagedType item = (ManagedType)iter.Value; - string name = (string)iter.Key; + var item = (ManagedType)iter.Value; + var name = (string)iter.Key; Runtime.PyDict_SetItemString(dict, name, item.pyHandle); } // If class has constructors, generate an __doc__ attribute. - IntPtr doc = IntPtr.Zero; Type marker = typeof(DocStringAttribute); - Attribute[] attrs = (Attribute[])type.GetCustomAttributes(marker, false); + var attrs = (Attribute[])type.GetCustomAttributes(marker, false); if (attrs.Length == 0) { doc = IntPtr.Zero; } else { - DocStringAttribute attr = (DocStringAttribute)attrs[0]; + var attr = (DocStringAttribute)attrs[0]; string docStr = attr.DocString; doc = Runtime.PyString_FromString(docStr); Runtime.PyDict_SetItemString(dict, "__doc__", doc); Runtime.XDecref(doc); } - ClassObject co = impl as ClassObject; + var co = impl as ClassObject; // If this is a ClassObject AND it has constructors, generate a __doc__ attribute. // required that the ClassObject.ctors be changed to internal if (co != null) @@ -170,9 +170,9 @@ private static void InitClassBase(Type type, ClassBase impl) // Implement Overloads on the class object if (!CLRModule._SuppressOverloads) { - ConstructorBinding ctors = new ConstructorBinding(type, tp, co.binder); + var ctors = new ConstructorBinding(type, tp, co.binder); // ExtensionType types are untracked, so don't Incref() them. - // XXX deprecate __overloads__ soon... + // TODO: deprecate __overloads__ soon... Runtime.PyDict_SetItemString(dict, "__overloads__", ctors.pyHandle); Runtime.PyDict_SetItemString(dict, "Overloads", ctors.pyHandle); } @@ -186,18 +186,17 @@ private static void InitClassBase(Type type, ClassBase impl) } } } - } private static ClassInfo GetClassInfo(Type type) { - ClassInfo ci = new ClassInfo(type); - Hashtable methods = new Hashtable(); + var ci = new ClassInfo(type); + var methods = new Hashtable(); ArrayList list; MethodInfo meth; ManagedType ob; - String name; - Object item; + string name; + object item; Type tp; int i, n; @@ -207,15 +206,14 @@ private static ClassInfo GetClassInfo(Type type) // method and a class B that defines two more. The name-based // descriptor Python will find needs to know about inherited // overloads as well as those declared on the sub class. - BindingFlags flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; MemberInfo[] info = type.GetMembers(flags); - Hashtable local = new Hashtable(); - ArrayList items = new ArrayList(); + var local = new Hashtable(); + var items = new ArrayList(); MemberInfo m; // Loop through once to find out which names are declared @@ -270,7 +268,7 @@ private static ClassInfo GetClassInfo(Type type) for (i = 0; i < items.Count; i++) { - MemberInfo mi = (MemberInfo)items[i]; + var mi = (MemberInfo)items[i]; switch (mi.MemberType) { @@ -278,7 +276,9 @@ private static ClassInfo GetClassInfo(Type type) meth = (MethodInfo)mi; if (!(meth.IsPublic || meth.IsFamily || meth.IsFamilyOrAssembly)) + { continue; + } name = meth.Name; item = methods[name]; if (item == null) @@ -290,7 +290,7 @@ private static ClassInfo GetClassInfo(Type type) continue; case MemberTypes.Property: - PropertyInfo pi = (PropertyInfo)mi; + var pi = (PropertyInfo)mi; MethodInfo mm = null; try @@ -314,7 +314,9 @@ private static ClassInfo GetClassInfo(Type type) } if (!(mm.IsPublic || mm.IsFamily || mm.IsFamilyOrAssembly)) + { continue; + } // Check for indexer ParameterInfo[] args = pi.GetIndexParameters(); @@ -335,18 +337,22 @@ private static ClassInfo GetClassInfo(Type type) continue; case MemberTypes.Field: - FieldInfo fi = (FieldInfo)mi; + var fi = (FieldInfo)mi; if (!(fi.IsPublic || fi.IsFamily || fi.IsFamilyOrAssembly)) + { continue; + } ob = new FieldObject(fi); ci.members[mi.Name] = ob; continue; case MemberTypes.Event: - EventInfo ei = (EventInfo)mi; + var ei = (EventInfo)mi; MethodInfo me = ei.GetAddMethod(true); if (!(me.IsPublic || me.IsFamily || me.IsFamilyOrAssembly)) + { continue; + } ob = new EventObject(ei); ci.members[ei.Name] = ob; continue; @@ -355,9 +361,11 @@ private static ClassInfo GetClassInfo(Type type) tp = (Type)mi; if (!(tp.IsNestedPublic || tp.IsNestedFamily || tp.IsNestedFamORAssem)) + { continue; + } // Note the given instance might be uninitialized - ob = ClassManager.GetClass(tp); + ob = GetClass(tp); ci.members[mi.Name] = ob; continue; } @@ -370,9 +378,7 @@ private static ClassInfo GetClassInfo(Type type) name = (string)iter.Key; list = (ArrayList)iter.Value; - MethodInfo[] mlist = (MethodInfo[])list.ToArray( - typeof(MethodInfo) - ); + var mlist = (MethodInfo[])list.ToArray(typeof(MethodInfo)); ob = new MethodObject(type, name, mlist); ci.members[name] = ob; @@ -385,13 +391,13 @@ private static ClassInfo GetClassInfo(Type type) internal class ClassInfo { + public Indexer indexer; + public Hashtable members; + internal ClassInfo(Type t) { members = new Hashtable(); indexer = null; } - - public Hashtable members; - public Indexer indexer; } } diff --git a/src/runtime/classobject.cs b/src/runtime/classobject.cs index 13eab44b0..08656aefe 100644 --- a/src/runtime/classobject.cs +++ b/src/runtime/classobject.cs @@ -19,9 +19,9 @@ internal ClassObject(Type tp) : base(tp) ctors = type.GetConstructors(); binder = new ConstructorBinder(type); - for (int i = 0; i < ctors.Length; i++) + foreach (ConstructorInfo t in ctors) { - binder.AddMethod(ctors[i]); + binder.AddMethod(t); } } @@ -33,11 +33,11 @@ internal IntPtr GetDocString() { MethodBase[] methods = binder.GetMethods(); string str = ""; - for (int i = 0; i < methods.Length; i++) + foreach (MethodBase t in methods) { if (str.Length > 0) str += Environment.NewLine; - str += methods[i].ToString(); + str += t.ToString(); } return Runtime.PyString_FromString(str); } @@ -53,7 +53,6 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) // Sanity check: this ensures a graceful error if someone does // something intentially wrong like use the managed metatype for // a class that is not really derived from a managed class. - if (self == null) { return Exceptions.RaiseTypeError("invalid object"); @@ -64,8 +63,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) // Primitive types do not have constructors, but they look like // they do from Python. If the ClassObject represents one of the // convertible primitive types, just convert the arg directly. - - if (type.IsPrimitive || type == typeof(String)) + if (type.IsPrimitive || type == typeof(string)) { if (Runtime.PyTuple_Size(args) != 1) { @@ -115,8 +113,7 @@ public override IntPtr type_subscript(IntPtr idx) { // If this type is the Array type, the [] means we need to // construct and return an array type of the given element type. - - if ((this.type) == typeof(Array)) + if (type == typeof(Array)) { if (Runtime.PyTuple_Check(idx)) { @@ -137,21 +134,19 @@ public override IntPtr type_subscript(IntPtr idx) // If there are generics in our namespace with the same base name // as the current type, then [] means the caller wants to // bind the generic type matching the given type parameters. - Type[] types = Runtime.PythonArgsToTypeArray(idx); if (types == null) { return Exceptions.RaiseTypeError("type(s) expected"); } - string gname = this.type.FullName + "`" + types.Length.ToString(); - Type gtype = AssemblyManager.LookupType(gname); + Type gtype = AssemblyManager.LookupType($"{type.FullName}`{types.Length}"); if (gtype != null) { - GenericType g = ClassManager.GetClass(gtype) as GenericType; + var g = ClassManager.GetClass(gtype) as GenericType; return g.type_subscript(idx); - /*Runtime.XIncref(g.pyHandle); - return g.pyHandle;*/ + //Runtime.XIncref(g.pyHandle); + //return g.pyHandle; } return Exceptions.RaiseTypeError("unsubscriptable object"); } @@ -175,7 +170,6 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) // Arg may be a tuple in the case of an indexer with multiple // parameters. If so, use it directly, else make a new tuple // with the index arg (method binders expect arg tuples). - IntPtr args = idx; bool free = false; @@ -187,7 +181,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) free = true; } - IntPtr value = IntPtr.Zero; + IntPtr value; try { @@ -296,7 +290,7 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) IntPtr tp = Runtime.PyObject_TYPE(ob); ClassBase cb = (ClassBase)GetManagedObject(tp); - if (cb.type != typeof(System.Delegate)) + if (cb.type != typeof(Delegate)) { Exceptions.SetError(Exceptions.TypeError, "object is not callable"); return IntPtr.Zero; diff --git a/src/runtime/codegenerator.cs b/src/runtime/codegenerator.cs index 4620b0f0c..56bed758f 100644 --- a/src/runtime/codegenerator.cs +++ b/src/runtime/codegenerator.cs @@ -1,7 +1,7 @@ using System; -using System.Threading; using System.Reflection; using System.Reflection.Emit; +using System.Threading; namespace Python.Runtime { diff --git a/src/runtime/constructorbinding.cs b/src/runtime/constructorbinding.cs index ea48f97ce..295faaa7e 100644 --- a/src/runtime/constructorbinding.cs +++ b/src/runtime/constructorbinding.cs @@ -10,13 +10,13 @@ namespace Python.Runtime /// /// ClassManager stores a ConstructorBinding instance in the class's __dict__['Overloads'] /// SomeType.Overloads[Type, ...] works like this: - /// 1) Python retreives the Overloads attribute from this ClassObject's dictionary normally + /// 1) Python retrieves the Overloads attribute from this ClassObject's dictionary normally /// and finds a non-null tp_descr_get slot which is called by the interpreter /// and returns an IncRef()ed pyHandle to itself. /// 2) The ConstructorBinding object handles the [] syntax in its mp_subscript by matching - /// the Type object parameters to a contructor overload using Type.GetConstructor() + /// the Type object parameters to a constructor overload using Type.GetConstructor() /// [NOTE: I don't know why method overloads are not searched the same way.] - /// and creating the BoundContructor oject which contains ContructorInfo object. + /// and creating the BoundContructor object which contains ContructorInfo object. /// 3) In tp_call, if ctorInfo is not null, ctorBinder.InvokeRaw() is called. /// internal class ConstructorBinding : ExtensionType @@ -26,7 +26,7 @@ internal class ConstructorBinding : ExtensionType ConstructorBinder ctorBinder; IntPtr repr; - public ConstructorBinding(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder) : base() + public ConstructorBinding(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder) { this.type = type; Runtime.XIncref(pyTypeHndl); @@ -62,7 +62,7 @@ public ConstructorBinding(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBi /// public static IntPtr tp_descr_get(IntPtr op, IntPtr instance, IntPtr owner) { - ConstructorBinding self = (ConstructorBinding)GetManagedObject(op); + var self = (ConstructorBinding)GetManagedObject(op); if (self == null) { return IntPtr.Zero; @@ -92,7 +92,7 @@ public static IntPtr tp_descr_get(IntPtr op, IntPtr instance, IntPtr owner) /// public static IntPtr mp_subscript(IntPtr op, IntPtr key) { - ConstructorBinding self = (ConstructorBinding)GetManagedObject(op); + var self = (ConstructorBinding)GetManagedObject(op); Type[] types = Runtime.PythonArgsToTypeArray(key); if (types == null) @@ -104,12 +104,12 @@ public static IntPtr mp_subscript(IntPtr op, IntPtr key) ConstructorInfo ci = self.type.GetConstructor(types); if (ci == null) { - string msg = "No match found for constructor signature"; + var msg = "No match found for constructor signature"; return Exceptions.RaiseTypeError(msg); } - BoundContructor boundCtor = new BoundContructor(self.type, self.pyTypeHndl, self.ctorBinder, ci); + var boundCtor = new BoundContructor(self.type, self.pyTypeHndl, self.ctorBinder, ci); - /* Since nothing's chached, do we need the increment??? + /* Since nothing is cached, do we need the increment??? Runtime.XIncref(boundCtor.pyHandle); // Decref'd by the interpreter??? */ return boundCtor.pyHandle; } @@ -119,7 +119,7 @@ public static IntPtr mp_subscript(IntPtr op, IntPtr key) /// public static IntPtr tp_repr(IntPtr ob) { - ConstructorBinding self = (ConstructorBinding)GetManagedObject(ob); + var self = (ConstructorBinding)GetManagedObject(ob); if (self.repr != IntPtr.Zero) { Runtime.XIncref(self.repr); @@ -127,14 +127,16 @@ public static IntPtr tp_repr(IntPtr ob) } MethodBase[] methods = self.ctorBinder.GetMethods(); string name = self.type.FullName; - string doc = ""; - for (int i = 0; i < methods.Length; i++) + var doc = ""; + foreach (MethodBase t in methods) { if (doc.Length > 0) + { doc += "\n"; - string str = methods[i].ToString(); + } + string str = t.ToString(); int idx = str.IndexOf("("); - doc += String.Format("{0}{1}", name, str.Substring(idx)); + doc += string.Format("{0}{1}", name, str.Substring(idx)); } self.repr = Runtime.PyString_FromString(doc); Runtime.XIncref(self.repr); @@ -144,9 +146,9 @@ public static IntPtr tp_repr(IntPtr ob) /// /// ConstructorBinding dealloc implementation. /// - public static new void tp_dealloc(IntPtr ob) + public new static void tp_dealloc(IntPtr ob) { - ConstructorBinding self = (ConstructorBinding)GetManagedObject(ob); + var self = (ConstructorBinding)GetManagedObject(ob); Runtime.XDecref(self.repr); Runtime.XDecref(self.pyTypeHndl); ExtensionType.FinalizeObject(self); @@ -154,7 +156,7 @@ public static IntPtr tp_repr(IntPtr ob) } /// - /// Implements a Python type that constucts the given Type given a particular ContructorInfo. + /// Implements a Python type that constructs the given Type given a particular ContructorInfo. /// /// /// Here mostly because I wanted a new __repr__ function for the selected constructor. @@ -169,7 +171,7 @@ internal class BoundContructor : ExtensionType ConstructorInfo ctorInfo; IntPtr repr; - public BoundContructor(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder, ConstructorInfo ci) : base() + public BoundContructor(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder, ConstructorInfo ci) { this.type = type; Runtime.XIncref(pyTypeHndl); @@ -188,7 +190,7 @@ public BoundContructor(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinde /// A reference to a new instance of the class by invoking the selected ctor(). public static IntPtr tp_call(IntPtr op, IntPtr args, IntPtr kw) { - BoundContructor self = (BoundContructor)GetManagedObject(op); + var self = (BoundContructor)GetManagedObject(op); // Even though a call with null ctorInfo just produces the old behavior /*if (self.ctorInfo == null) { string msg = "Usage: Class.Overloads[CLR_or_python_Type, ...]"; @@ -196,7 +198,7 @@ public static IntPtr tp_call(IntPtr op, IntPtr args, IntPtr kw) }*/ // Bind using ConstructorBinder.Bind and invoke the ctor providing a null instancePtr // which will fire self.ctorInfo using ConstructorInfo.Invoke(). - Object obj = self.ctorBinder.InvokeRaw(IntPtr.Zero, args, kw, self.ctorInfo); + object obj = self.ctorBinder.InvokeRaw(IntPtr.Zero, args, kw, self.ctorInfo); if (obj == null) { // XXX set an error @@ -212,7 +214,7 @@ public static IntPtr tp_call(IntPtr op, IntPtr args, IntPtr kw) /// public static IntPtr tp_repr(IntPtr ob) { - BoundContructor self = (BoundContructor)GetManagedObject(ob); + var self = (BoundContructor)GetManagedObject(ob); if (self.repr != IntPtr.Zero) { Runtime.XIncref(self.repr); @@ -221,7 +223,7 @@ public static IntPtr tp_repr(IntPtr ob) string name = self.type.FullName; string str = self.ctorInfo.ToString(); int idx = str.IndexOf("("); - str = String.Format("returns a new {0}{1}", name, str.Substring(idx)); + str = string.Format("returns a new {0}{1}", name, str.Substring(idx)); self.repr = Runtime.PyString_FromString(str); Runtime.XIncref(self.repr); return self.repr; @@ -230,12 +232,12 @@ public static IntPtr tp_repr(IntPtr ob) /// /// ConstructorBinding dealloc implementation. /// - public static new void tp_dealloc(IntPtr ob) + public new static void tp_dealloc(IntPtr ob) { - BoundContructor self = (BoundContructor)GetManagedObject(ob); + var self = (BoundContructor)GetManagedObject(ob); Runtime.XDecref(self.repr); Runtime.XDecref(self.pyTypeHndl); - ExtensionType.FinalizeObject(self); + FinalizeObject(self); } } } diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 697d84858..5e292e82d 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -436,7 +436,7 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setEr case TypeCode.Int32: #if PYTHON2 // Trickery to support 64-bit platforms. - if (IntPtr.Size == 4) + if (Runtime.is32bit) { op = Runtime.PyNumber_Int(value); @@ -612,14 +612,14 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setEr if (Runtime.PyUnicode_GetSize(value) == 1) { op = Runtime.PyUnicode_AS_UNICODE(value); -#if !UCS4 +#if UCS2 // 2011-01-02: Marshal as character array because the cast // result = (char)Marshal.ReadInt16(op); throws an OverflowException // on negative numbers with Check Overflow option set on the project Char[] buff = new Char[1]; Marshal.Copy(op, buff, 0, 1); result = buff[0]; -#else +#elif UCS4 // XXX this is probably NOT correct? result = (char)Marshal.ReadInt32(op); #endif diff --git a/src/runtime/debughelper.cs b/src/runtime/debughelper.cs index f42ad2e37..777a61e35 100644 --- a/src/runtime/debughelper.cs +++ b/src/runtime/debughelper.cs @@ -1,7 +1,7 @@ using System; +using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; -using System.Diagnostics; using System.Threading; namespace Python.Runtime @@ -9,7 +9,7 @@ namespace Python.Runtime /// /// Debugging helper utilities. /// The methods are only executed when the DEBUG flag is set. Otherwise - /// they are automagically hidden by the compiler and silently surpressed. + /// they are automagically hidden by the compiler and silently suppressed. /// internal class DebugUtil { diff --git a/src/runtime/delegatemanager.cs b/src/runtime/delegatemanager.cs index 0a29b8e13..ce17a2e6e 100644 --- a/src/runtime/delegatemanager.cs +++ b/src/runtime/delegatemanager.cs @@ -1,7 +1,4 @@ using System; -using System.Threading; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using System.Collections; using System.Reflection; using System.Reflection.Emit; @@ -40,9 +37,9 @@ public DelegateManager() /// public IntPtr GetPythonHandle(Delegate d) { - if ((d != null) && (d.Target is Dispatcher)) + if (d?.Target is Dispatcher) { - Dispatcher disp = d.Target as Dispatcher; + var disp = (Dispatcher)d.Target; return disp.target; } return IntPtr.Zero; @@ -61,25 +58,24 @@ private Type GetDispatcher(Type dtype) // unique signatures rather than delegate types, since multiple // delegate types with the same sig could use the same dispatcher. - Object item = cache[dtype]; + object item = cache[dtype]; if (item != null) { return (Type)item; } - string name = "__" + dtype.FullName + "Dispatcher"; + string name = $"__{dtype.FullName}Dispatcher"; name = name.Replace('.', '_'); name = name.Replace('+', '_'); TypeBuilder tb = codeGenerator.DefineType(name, basetype); // Generate a constructor for the generated type that calls the // appropriate constructor of the Dispatcher base type. - MethodAttributes ma = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; - CallingConventions cc = CallingConventions.Standard; + var cc = CallingConventions.Standard; Type[] args = { ptrtype, typetype }; ConstructorBuilder cb = tb.DefineConstructor(ma, cc, args); ConstructorInfo ci = basetype.GetConstructor(args); @@ -96,12 +92,11 @@ private Type GetDispatcher(Type dtype) // arguments and hands them to the Dispatch() method, which deals // with converting the arguments, calling the Python method and // converting the result of the call. - MethodInfo method = dtype.GetMethod("Invoke"); ParameterInfo[] pi = method.GetParameters(); - Type[] signature = new Type[pi.Length]; - for (int i = 0; i < pi.Length; i++) + var signature = new Type[pi.Length]; + for (var i = 0; i < pi.Length; i++) { signature[i] = pi[i].ParameterType; } @@ -117,7 +112,7 @@ private Type GetDispatcher(Type dtype) il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Stloc_0); - for (int c = 0; c < signature.Length; c++) + for (var c = 0; c < signature.Length; c++) { Type t = signature[c]; il.Emit(OpCodes.Ldloc_0); @@ -184,10 +179,7 @@ A possible alternate strategy would be to create custom subclasses of the required delegate type, storing the IntPtr in it directly. This would be slightly cleaner, but I'm not sure if delegates are too "special" for this to work. It would be more work, so for now - the 80/20 rule applies :) - - */ - + the 80/20 rule applies :) */ public class Dispatcher { public IntPtr target; @@ -238,7 +230,7 @@ public object TrueDispatch(ArrayList args) IntPtr pyargs = Runtime.PyTuple_New(pi.Length); Type rtype = method.ReturnType; - for (int i = 0; i < pi.Length; i++) + for (var i = 0; i < pi.Length; i++) { // Here we own the reference to the Python value, and we // give the ownership to the arg tuple. @@ -251,7 +243,7 @@ public object TrueDispatch(ArrayList args) if (op == IntPtr.Zero) { - PythonException e = new PythonException(); + var e = new PythonException(); throw e; } @@ -260,12 +252,11 @@ public object TrueDispatch(ArrayList args) return null; } - Object result = null; + object result = null; if (!Converter.ToManaged(op, rtype, out result, false)) { - string s = "could not convert Python result to " + rtype.ToString(); Runtime.XDecref(op); - throw new ConversionException(s); + throw new ConversionException($"could not convert Python result to {rtype}"); } Runtime.XDecref(op); @@ -274,9 +265,9 @@ public object TrueDispatch(ArrayList args) } - public class ConversionException : System.Exception + public class ConversionException : Exception { - public ConversionException() : base() + public ConversionException() { } diff --git a/src/runtime/delegateobject.cs b/src/runtime/delegateobject.cs index ff64ff094..bf9ddea16 100644 --- a/src/runtime/delegateobject.cs +++ b/src/runtime/delegateobject.cs @@ -1,6 +1,4 @@ using System; -using System.Reflection; -using System.Runtime.InteropServices; namespace Python.Runtime { @@ -55,8 +53,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) if (Runtime.PyTuple_Size(args) != 1) { - var message = "class takes exactly one argument"; - return Exceptions.RaiseTypeError(message); + return Exceptions.RaiseTypeError("class takes exactly one argument"); } IntPtr method = Runtime.PyTuple_GetItem(args, 0); @@ -76,7 +73,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) /// public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { - // todo: add fast type check! + // TODO: add fast type check! IntPtr pytype = Runtime.PyObject_TYPE(ob); var self = (DelegateObject)GetManagedObject(pytype); var o = GetManagedObject(ob) as CLRObject; @@ -99,8 +96,8 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) /// /// Implements __cmp__ for reflected delegate types. /// -#if PYTHON3 - public static new IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) +#if PYTHON3 // TODO: Doesn't PY2 implement tp_richcompare too? + public new static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) { if (op != Runtime.Py_EQ && op != Runtime.Py_NE) { @@ -130,15 +127,11 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) return pyfalse; } #elif PYTHON2 - public static new int tp_compare(IntPtr ob, IntPtr other) + public static int tp_compare(IntPtr ob, IntPtr other) { Delegate d1 = GetTrueDelegate(ob); Delegate d2 = GetTrueDelegate(other); - if (d1 == d2) - { - return 0; - } - return -1; + return d1 == d2 ? 0 : -1; } #endif } diff --git a/src/runtime/eventbinding.cs b/src/runtime/eventbinding.cs index b31286b4c..552472430 100644 --- a/src/runtime/eventbinding.cs +++ b/src/runtime/eventbinding.cs @@ -10,7 +10,7 @@ internal class EventBinding : ExtensionType EventObject e; IntPtr target; - public EventBinding(EventObject e, IntPtr target) : base() + public EventBinding(EventObject e, IntPtr target) { Runtime.XIncref(target); this.target = target; @@ -23,7 +23,7 @@ public EventBinding(EventObject e, IntPtr target) : base() /// public static IntPtr nb_inplace_add(IntPtr ob, IntPtr arg) { - EventBinding self = (EventBinding)GetManagedObject(ob); + var self = (EventBinding)GetManagedObject(ob); if (Runtime.PyCallable_Check(arg) < 1) { @@ -46,7 +46,7 @@ public static IntPtr nb_inplace_add(IntPtr ob, IntPtr arg) /// public static IntPtr nb_inplace_subtract(IntPtr ob, IntPtr arg) { - EventBinding self = (EventBinding)GetManagedObject(ob); + var self = (EventBinding)GetManagedObject(ob); if (Runtime.PyCallable_Check(arg) < 1) { @@ -69,7 +69,7 @@ public static IntPtr nb_inplace_subtract(IntPtr ob, IntPtr arg) /// public static IntPtr tp_hash(IntPtr ob) { - EventBinding self = (EventBinding)GetManagedObject(ob); + var self = (EventBinding)GetManagedObject(ob); long x = 0; long y = 0; @@ -104,9 +104,9 @@ public static IntPtr tp_hash(IntPtr ob) /// public static IntPtr tp_repr(IntPtr ob) { - EventBinding self = (EventBinding)GetManagedObject(ob); - string type = (self.target == IntPtr.Zero) ? "unbound" : "bound"; - string s = String.Format("<{0} event '{1}'>", type, self.e.name); + var self = (EventBinding)GetManagedObject(ob); + string type = self.target == IntPtr.Zero ? "unbound" : "bound"; + string s = string.Format("<{0} event '{1}'>", type, self.e.name); return Runtime.PyString_FromString(s); } @@ -114,9 +114,9 @@ public static IntPtr tp_repr(IntPtr ob) /// /// EventBinding dealloc implementation. /// - public static new void tp_dealloc(IntPtr ob) + public new static void tp_dealloc(IntPtr ob) { - EventBinding self = (EventBinding)GetManagedObject(ob); + var self = (EventBinding)GetManagedObject(ob); Runtime.XDecref(self.target); ExtensionType.FinalizeObject(self); } diff --git a/src/runtime/eventobject.cs b/src/runtime/eventobject.cs index 8ac0ed3ac..5f18c4609 100644 --- a/src/runtime/eventobject.cs +++ b/src/runtime/eventobject.cs @@ -14,7 +14,7 @@ internal class EventObject : ExtensionType internal EventInfo info; internal Hashtable reg; - public EventObject(EventInfo info) : base() + public EventObject(EventInfo info) { this.name = info.Name; this.info = info; @@ -26,31 +26,29 @@ public EventObject(EventInfo info) : base() /// internal bool AddEventHandler(IntPtr target, IntPtr handler) { - Object obj = null; + object obj = null; if (target != IntPtr.Zero) { - CLRObject co = (CLRObject)ManagedType.GetManagedObject(target); + var co = (CLRObject)GetManagedObject(target); obj = co.inst; } // Create a true delegate instance of the appropriate type to // wrap the Python handler. Note that wrapper delegate creation // always succeeds, though calling the wrapper may fail. - - Type type = this.info.EventHandlerType; + Type type = info.EventHandlerType; Delegate d = PythonEngine.DelegateManager.GetDelegate(type, handler); // Now register the handler in a mapping from instance to pairs // of (handler hash, delegate) so we can lookup to remove later. // All this is done lazily to avoid overhead until an event is // actually subscribed to by a Python event handler. - if (reg == null) { reg = new Hashtable(); } - object key = (obj != null) ? obj : this.info.ReflectedType; - ArrayList list = reg[key] as ArrayList; + object key = obj ?? info.ReflectedType; + var list = reg[key] as ArrayList; if (list == null) { list = new ArrayList(); @@ -60,9 +58,8 @@ internal bool AddEventHandler(IntPtr target, IntPtr handler) // Note that AddEventHandler helper only works for public events, // so we have to get the underlying add method explicitly. - object[] args = { d }; - MethodInfo mi = this.info.GetAddMethod(true); + MethodInfo mi = info.GetAddMethod(true); mi.Invoke(obj, BindingFlags.Default, null, args, null); return true; @@ -74,22 +71,22 @@ internal bool AddEventHandler(IntPtr target, IntPtr handler) /// internal bool RemoveEventHandler(IntPtr target, IntPtr handler) { - Object obj = null; + object obj = null; if (target != IntPtr.Zero) { - CLRObject co = (CLRObject)ManagedType.GetManagedObject(target); + var co = (CLRObject)GetManagedObject(target); obj = co.inst; } IntPtr hash = Runtime.PyObject_Hash(handler); - if (Exceptions.ErrorOccurred() || (reg == null)) + if (Exceptions.ErrorOccurred() || reg == null) { Exceptions.SetError(Exceptions.ValueError, "unknown event handler"); return false; } - object key = (obj != null) ? obj : this.info.ReflectedType; - ArrayList list = reg[key] as ArrayList; + object key = obj ?? info.ReflectedType; + var list = reg[key] as ArrayList; if (list == null) { @@ -98,11 +95,11 @@ internal bool RemoveEventHandler(IntPtr target, IntPtr handler) } object[] args = { null }; - MethodInfo mi = this.info.GetRemoveMethod(true); + MethodInfo mi = info.GetRemoveMethod(true); - for (int i = 0; i < list.Count; i++) + for (var i = 0; i < list.Count; i++) { - Handler item = (Handler)list[i]; + var item = (Handler)list[i]; if (item.hash != hash) { continue; @@ -131,7 +128,7 @@ internal bool RemoveEventHandler(IntPtr target, IntPtr handler) /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { - EventObject self = GetManagedObject(ds) as EventObject; + var self = GetManagedObject(ds) as EventObject; EventBinding binding; if (self == null) @@ -171,17 +168,16 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// 'ob.SomeEvent += method', Python will attempt to set the attribute /// SomeEvent on ob to the result of the '+=' operation. /// - public static new int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) + public new static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { - EventBinding e = GetManagedObject(val) as EventBinding; + var e = GetManagedObject(val) as EventBinding; if (e != null) { return 0; } - string message = "cannot set event attributes"; - Exceptions.RaiseTypeError(message); + Exceptions.RaiseTypeError("cannot set event attributes"); return -1; } @@ -191,23 +187,22 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// public static IntPtr tp_repr(IntPtr ob) { - EventObject self = (EventObject)GetManagedObject(ob); - string s = String.Format("", self.name); - return Runtime.PyString_FromString(s); + var self = (EventObject)GetManagedObject(ob); + return Runtime.PyString_FromString($""); } /// /// Descriptor dealloc implementation. /// - public static new void tp_dealloc(IntPtr ob) + public new static void tp_dealloc(IntPtr ob) { - EventObject self = (EventObject)GetManagedObject(ob); + var self = (EventObject)GetManagedObject(ob); if (self.unbound != null) { Runtime.XDecref(self.unbound.pyHandle); } - ExtensionType.FinalizeObject(self); + FinalizeObject(self); } } diff --git a/src/runtime/exceptions.cs b/src/runtime/exceptions.cs index 33d5d2ecd..dbdd9a67b 100644 --- a/src/runtime/exceptions.cs +++ b/src/runtime/exceptions.cs @@ -1,6 +1,5 @@ using System; using System.Reflection; -using System.Collections; using System.Runtime.InteropServices; @@ -25,12 +24,12 @@ internal ExceptionClassObject(Type tp) : base(tp) internal static Exception ToException(IntPtr ob) { - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { return null; } - Exception e = co.inst as Exception; + var e = co.inst as Exception; if (e == null) { return null; @@ -49,8 +48,8 @@ internal static Exception ToException(IntPtr ob) return Exceptions.RaiseTypeError("invalid object"); } - string message = String.Empty; - if (e.Message != String.Empty) + string message = string.Empty; + if (e.Message != string.Empty) { message = e.Message; } @@ -102,7 +101,7 @@ internal static void Initialize() else { fi.SetValue(type, IntPtr.Zero); - DebugUtil.Print("Unknown exception: " + fi.Name); + DebugUtil.Print($"Unknown exception: {fi.Name}"); } } Runtime.PyErr_Clear(); @@ -114,13 +113,13 @@ internal static void Initialize() /// internal static void Shutdown() { - if (0 != Runtime.Py_IsInitialized()) + if (Runtime.Py_IsInitialized() != 0) { Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { - IntPtr op = (IntPtr)fi.GetValue(type); + var op = (IntPtr)fi.GetValue(type); if (op != IntPtr.Zero) { Runtime.XDecref(op); @@ -143,15 +142,17 @@ internal static void Shutdown() /// The python object wrapping internal static void SetArgsAndCause(IntPtr ob) { - var e = ExceptionClassObject.ToException(ob); + Exception e = ExceptionClassObject.ToException(ob); if (e == null) + { return; + } IntPtr args; if (!string.IsNullOrEmpty(e.Message)) { args = Runtime.PyTuple_New(1); - var msg = Runtime.PyUnicode_FromString(e.Message); + IntPtr msg = Runtime.PyUnicode_FromString(e.Message); Runtime.PyTuple_SetItem(args, 0, msg); } else @@ -171,7 +172,7 @@ internal static void SetArgsAndCause(IntPtr ob) } /// - /// Shortcut for (pointer == NULL) -> throw PythonException + /// Shortcut for (pointer == NULL) -> throw PythonException /// /// Pointer to a Python object internal unsafe static void ErrorCheck(IntPtr pointer) @@ -187,7 +188,7 @@ internal unsafe static void ErrorCheck(IntPtr pointer) /// internal unsafe static void ErrorOccurredCheck(IntPtr pointer) { - if ((pointer == IntPtr.Zero) || Exceptions.ErrorOccurred()) + if (pointer == IntPtr.Zero || ErrorOccurred()) { throw new PythonException(); } @@ -215,7 +216,7 @@ public static bool ExceptionMatches(IntPtr ob) public static bool ExceptionMatches(IntPtr exc, IntPtr ob) { int i = Runtime.PyErr_GivenExceptionMatches(exc, ob); - return (i != 0); + return i != 0; } /// @@ -252,12 +253,12 @@ public static void SetError(IntPtr ob, IntPtr value) /// public static void SetError(Exception e) { - // Because delegates allow arbitrary nestings of Python calling + // Because delegates allow arbitrary nesting of Python calling // managed calling Python calling... etc. it is possible that we // might get a managed exception raised that is a wrapper for a // Python exception. In that case we'd rather have the real thing. - PythonException pe = e as PythonException; + var pe = e as PythonException; if (pe != null) { Runtime.PyErr_SetObject(pe.PyType, pe.PyValue); @@ -303,7 +304,7 @@ public static void Clear() /// public static void warn(string message, IntPtr exception, int stacklevel) { - if ((exception == IntPtr.Zero) || + if (exception == IntPtr.Zero || (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1)) { Exceptions.RaiseTypeError("Invalid exception"); diff --git a/src/runtime/extensiontype.cs b/src/runtime/extensiontype.cs index 37ab11239..9569b0485 100644 --- a/src/runtime/extensiontype.cs +++ b/src/runtime/extensiontype.cs @@ -6,14 +6,14 @@ namespace Python.Runtime /// /// Base class for extensions whose instances *share* a single Python /// type object, such as the types that represent CLR methods, fields, - /// etc. Instances implemented by this class do not support subtyping. + /// etc. Instances implemented by this class do not support sub-typing. /// internal abstract class ExtensionType : ManagedType { public ExtensionType() { // Create a new PyObject whose type is a generated type that is - // implemented by the particuar concrete ExtensionType subclass. + // implemented by the particular concrete ExtensionType subclass. // The Python instance object is related to an instance of a // particular concrete subclass with a hidden CLR gchandle. diff --git a/src/runtime/genericutil.cs b/src/runtime/genericutil.cs index d1de1c374..57f28cdc0 100644 --- a/src/runtime/genericutil.cs +++ b/src/runtime/genericutil.cs @@ -1,9 +1,5 @@ using System; -using System.Runtime.InteropServices; using System.Collections.Generic; -using System.Collections; -using System.Reflection; -using System.Security; namespace Python.Runtime { @@ -150,11 +146,7 @@ public static string GenericNameForBaseName(string ns, string name) } List gnames = null; nsmap.TryGetValue(name, out gnames); - if (gnames == null) - { - return null; - } - if (gnames.Count > 0) + if (gnames?.Count > 0) { return gnames[0]; } diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index 96a343773..df3877c29 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Runtime.InteropServices; namespace Python.Runtime @@ -20,7 +19,9 @@ internal class ImportHook internal static void InitializeModuleDef() { if (module_def == IntPtr.Zero) + { module_def = ModuleDefOffset.AllocModuleDef("clr"); + } } #endif @@ -100,26 +101,32 @@ public static IntPtr GetCLRModule(IntPtr? fromList = null) if (Runtime.PyTuple_Check(fromList.GetValueOrDefault())) { Runtime.XIncref(py_mod_dict); - using (PyDict mod_dict = new PyDict(py_mod_dict)) + using (var mod_dict = new PyDict(py_mod_dict)) { Runtime.XIncref(fromList.GetValueOrDefault()); - using (PyTuple from = new PyTuple(fromList.GetValueOrDefault())) + using (var from = new PyTuple(fromList.GetValueOrDefault())) { foreach (PyObject item in from) { if (mod_dict.HasKey(item)) + { continue; + } - string s = item.AsManagedObject(typeof(string)) as string; + var s = item.AsManagedObject(typeof(string)) as string; if (s == null) + { continue; + } ManagedType attr = root.GetAttribute(s, true); if (attr == null) + { continue; + } Runtime.XIncref(attr.pyHandle); - using (PyObject obj = new PyObject(attr.pyHandle)) + using (var obj = new PyObject(attr.pyHandle)) { mod_dict.SetItem(s, obj); } @@ -208,8 +215,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) { clr_prefix = "CLR."; // prepend when adding the module to sys.modules realname = mod_name.Substring(4); - string msg = string.Format("Importing from the CLR.* namespace " + - "is deprecated. Please import '{0}' directly.", realname); + string msg = $"Importing from the CLR.* namespace is deprecated. Please import '{realname}' directly."; Exceptions.deprecation(msg); } else @@ -270,7 +276,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) } // See if sys.modules for this interpreter already has the - // requested module. If so, just return the exising module. + // requested module. If so, just return the existing module. IntPtr modules = Runtime.PyImport_GetModuleDict(); IntPtr module = Runtime.PyDict_GetItem(modules, py_mod_name); @@ -310,8 +316,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) ManagedType mt = tail.GetAttribute(name, true); if (!(mt is ModuleObject)) { - string error = string.Format("No module named {0}", name); - Exceptions.SetError(Exceptions.ImportError, error); + Exceptions.SetError(Exceptions.ImportError, $"No module named {name}"); return IntPtr.Zero; } if (head == null) diff --git a/src/runtime/indexer.cs b/src/runtime/indexer.cs index 7f0b6fe10..7b6d90ca8 100644 --- a/src/runtime/indexer.cs +++ b/src/runtime/indexer.cs @@ -1,7 +1,5 @@ using System; -using System.Collections; using System.Reflection; -using System.Security.Permissions; namespace Python.Runtime { @@ -59,21 +57,27 @@ internal void SetItem(IntPtr inst, IntPtr args) internal bool NeedsDefaultArgs(IntPtr args) { int pynargs = Runtime.PyTuple_Size(args); - var methods = SetterBinder.GetMethods(); + MethodBase[] methods = SetterBinder.GetMethods(); if (methods.Length == 0) + { return false; + } MethodBase mi = methods[0]; ParameterInfo[] pi = mi.GetParameters(); // need to subtract one for the value int clrnargs = pi.Length - 1; if (pynargs == clrnargs || pynargs > clrnargs) + { return false; + } for (int v = pynargs; v < clrnargs; v++) { if (pi[v].DefaultValue == DBNull.Value) + { return false; + } } return true; } @@ -88,24 +92,25 @@ internal IntPtr GetDefaultArgs(IntPtr args) { // if we don't need default args return empty tuple if (!NeedsDefaultArgs(args)) + { return Runtime.PyTuple_New(0); + } int pynargs = Runtime.PyTuple_Size(args); // Get the default arg tuple - var methods = SetterBinder.GetMethods(); + MethodBase[] methods = SetterBinder.GetMethods(); MethodBase mi = methods[0]; ParameterInfo[] pi = mi.GetParameters(); int clrnargs = pi.Length - 1; IntPtr defaultArgs = Runtime.PyTuple_New(clrnargs - pynargs); - for (int i = 0; i < (clrnargs - pynargs); i++) + for (var i = 0; i < clrnargs - pynargs; i++) { if (pi[i + pynargs].DefaultValue == DBNull.Value) - continue; - else { - IntPtr arg = Converter.ToPython(pi[i + pynargs].DefaultValue, pi[i + pynargs].ParameterType); - Runtime.PyTuple_SetItem(defaultArgs, i, arg); + continue; } + IntPtr arg = Converter.ToPython(pi[i + pynargs].DefaultValue, pi[i + pynargs].ParameterType); + Runtime.PyTuple_SetItem(defaultArgs, i, arg); } return defaultArgs; } diff --git a/src/runtime/interfaceobject.cs b/src/runtime/interfaceobject.cs index e1c816f01..2085feac8 100644 --- a/src/runtime/interfaceobject.cs +++ b/src/runtime/interfaceobject.cs @@ -47,8 +47,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) if (co == null || !type.IsInstanceOfType(co.inst)) { - string msg = "object does not implement " + type.Name; - Exceptions.SetError(Exceptions.TypeError, msg); + Exceptions.SetError(Exceptions.TypeError, $"object does not implement {type.Name}"); return IntPtr.Zero; } diff --git a/src/runtime/metatype.cs b/src/runtime/metatype.cs index 6701a2a07..64c47b63e 100644 --- a/src/runtime/metatype.cs +++ b/src/runtime/metatype.cs @@ -1,7 +1,5 @@ using System; using System.Runtime.InteropServices; -using System.Collections; -using System.Reflection; namespace Python.Runtime { @@ -54,7 +52,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) IntPtr base_type = Runtime.PyTuple_GetItem(bases, 0); IntPtr mt = Runtime.PyObject_TYPE(base_type); - if (!((mt == PyCLRMetaType) || (mt == Runtime.PyTypeType))) + if (!(mt == PyCLRMetaType || mt == Runtime.PyTypeType)) { return Exceptions.RaiseTypeError("invalid metatype"); } @@ -62,7 +60,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) // Ensure that the reflected type is appropriate for subclassing, // disallowing subclassing of delegates, enums and array types. - ClassBase cb = GetManagedObject(base_type) as ClassBase; + var cb = GetManagedObject(base_type) as ClassBase; if (cb != null) { if (!cb.CanSubclass()) @@ -84,10 +82,12 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) if (IntPtr.Zero != dict) { Runtime.XIncref(dict); - using (PyDict clsDict = new PyDict(dict)) + using (var clsDict = new PyDict(dict)) { if (clsDict.HasKey("__assembly__") || clsDict.HasKey("__namespace__")) + { return TypeManager.CreateSubType(name, base_type, dict); + } } } @@ -141,7 +141,7 @@ public static void tp_free(IntPtr tp) /// /// Metatype __call__ implementation. This is needed to ensure correct /// initialization (__init__ support), because the tp_call we inherit - /// from PyType_Type won't call __init__ for metatypes it doesnt know. + /// from PyType_Type won't call __init__ for metatypes it doesn't know. /// public static IntPtr tp_call(IntPtr tp, IntPtr args, IntPtr kw) { @@ -206,22 +206,19 @@ public static int tp_setattro(IntPtr tp, IntPtr name, IntPtr value) if (dt == Runtime.PyWrapperDescriptorType || dt == Runtime.PyMethodType || typeof(ExtensionType).IsInstanceOfType(GetManagedObject(descr)) - ) + ) { IntPtr fp = Marshal.ReadIntPtr(dt, TypeOffset.tp_descr_set); if (fp != IntPtr.Zero) { return NativeCall.Impl.Int_Call_3(fp, descr, name, value); } - else - { - Exceptions.SetError(Exceptions.AttributeError, "attribute is read-only"); - return -1; - } + Exceptions.SetError(Exceptions.AttributeError, "attribute is read-only"); + return -1; } } - var res = Runtime.PyObject_GenericSetAttr(tp, name, value); + int res = Runtime.PyObject_GenericSetAttr(tp, name, value); Runtime.PyType_Modified(tp); return res; @@ -234,7 +231,7 @@ public static int tp_setattro(IntPtr tp, IntPtr name, IntPtr value) /// public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) { - ClassBase cb = GetManagedObject(tp) as ClassBase; + var cb = GetManagedObject(tp) as ClassBase; if (cb != null) { return cb.type_subscript(idx); @@ -250,7 +247,7 @@ public static void tp_dealloc(IntPtr tp) { // Fix this when we dont cheat on the handle for subclasses! - int flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); + var flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Subclass) == 0) { IntPtr gc = Marshal.ReadIntPtr(tp, TypeOffset.magic()); @@ -267,13 +264,11 @@ public static void tp_dealloc(IntPtr tp) op = Marshal.ReadIntPtr(Runtime.PyTypeType, TypeOffset.tp_dealloc); NativeCall.Void_Call_1(op, tp); - - return; } static IntPtr DoInstanceCheck(IntPtr tp, IntPtr args, bool checkType) { - ClassBase cb = GetManagedObject(tp) as ClassBase; + var cb = GetManagedObject(tp) as ClassBase; if (cb == null) { @@ -281,17 +276,23 @@ static IntPtr DoInstanceCheck(IntPtr tp, IntPtr args, bool checkType) return Runtime.PyFalse; } - using (PyList argsObj = new PyList(args)) + using (var argsObj = new PyList(args)) { if (argsObj.Length() != 1) + { return Exceptions.RaiseTypeError("Invalid parameter count"); + } PyObject arg = argsObj[0]; PyObject otherType; if (checkType) + { otherType = arg; + } else + { otherType = arg.GetPythonType(); + } if (Runtime.PyObject_TYPE(otherType.Handle) != PyCLRMetaType) { @@ -299,7 +300,7 @@ static IntPtr DoInstanceCheck(IntPtr tp, IntPtr args, bool checkType) return Runtime.PyFalse; } - ClassBase otherCb = GetManagedObject(otherType.Handle) as ClassBase; + var otherCb = GetManagedObject(otherType.Handle) as ClassBase; if (otherCb == null) { Runtime.XIncref(Runtime.PyFalse); diff --git a/src/runtime/methodbinder.cs b/src/runtime/methodbinder.cs index 651791599..86a76dd82 100644 --- a/src/runtime/methodbinder.cs +++ b/src/runtime/methodbinder.cs @@ -19,23 +19,22 @@ internal class MethodBinder internal MethodBinder() { - this.list = new ArrayList(); + list = new ArrayList(); } - internal MethodBinder(MethodInfo mi) : base() + internal MethodBinder(MethodInfo mi) { - this.list = new ArrayList(); - this.list.Add(mi); + list = new ArrayList { mi }; } public int Count { - get { return this.list.Count; } + get { return list.Count; } } internal void AddMethod(MethodBase m) { - this.list.Add(m); + list.Add(m); } /// @@ -49,22 +48,22 @@ internal static MethodInfo MatchSignature(MethodInfo[] mi, Type[] tp) return null; } int count = tp.Length; - for (int i = 0; i < mi.Length; i++) + foreach (MethodInfo t in mi) { - ParameterInfo[] pi = mi[i].GetParameters(); + ParameterInfo[] pi = t.GetParameters(); if (pi.Length != count) { continue; } - for (int n = 0; n < pi.Length; n++) + for (var n = 0; n < pi.Length; n++) { if (tp[n] != pi[n].ParameterType) { break; } - if (n == (pi.Length - 1)) + if (n == pi.Length - 1) { - return mi[i]; + return t; } } } @@ -82,18 +81,18 @@ internal static MethodInfo MatchParameters(MethodInfo[] mi, Type[] tp) return null; } int count = tp.Length; - for (int i = 0; i < mi.Length; i++) + foreach (MethodInfo t in mi) { - if (!mi[i].IsGenericMethodDefinition) + if (!t.IsGenericMethodDefinition) { continue; } - Type[] args = mi[i].GetGenericArguments(); + Type[] args = t.GetGenericArguments(); if (args.Length != count) { continue; } - return mi[i].MakeGenericMethod(tp); + return t.MakeGenericMethod(tp); } return null; } @@ -105,39 +104,40 @@ internal static MethodInfo MatchParameters(MethodInfo[] mi, Type[] tp) /// internal static MethodInfo MatchSignatureAndParameters(MethodInfo[] mi, Type[] genericTp, Type[] sigTp) { - if ((genericTp == null) || (sigTp == null)) + if (genericTp == null || sigTp == null) { return null; } int genericCount = genericTp.Length; int signatureCount = sigTp.Length; - for (int i = 0; i < mi.Length; i++) + foreach (MethodInfo t in mi) { - if (!mi[i].IsGenericMethodDefinition) + if (!t.IsGenericMethodDefinition) { continue; } - Type[] genericArgs = mi[i].GetGenericArguments(); + Type[] genericArgs = t.GetGenericArguments(); if (genericArgs.Length != genericCount) { continue; } - ParameterInfo[] pi = mi[i].GetParameters(); + ParameterInfo[] pi = t.GetParameters(); if (pi.Length != signatureCount) { continue; } - for (int n = 0; n < pi.Length; n++) + for (var n = 0; n < pi.Length; n++) { if (sigTp[n] != pi[n].ParameterType) { break; } - if (n == (pi.Length - 1)) + if (n == pi.Length - 1) { - MethodInfo match = mi[i]; + MethodInfo match = t; if (match.IsGenericMethodDefinition) { + // FIXME: typeArgs not used Type[] typeArgs = match.GetGenericArguments(); return match.MakeGenericMethod(genericTp); } @@ -151,7 +151,7 @@ internal static MethodInfo MatchSignatureAndParameters(MethodInfo[] mi, Type[] g /// /// Return the array of MethodInfo for this method. The result array - /// is arranged in order of precendence (done lazily to avoid doing it + /// is arranged in order of precedence (done lazily to avoid doing it /// at all for methods that are never called). /// internal MethodBase[] GetMethods() @@ -176,8 +176,8 @@ internal static int GetPrecedence(MethodBase mi) int val = mi.IsStatic ? 3000 : 0; int num = pi.Length; - val += (mi.IsGenericMethod ? 1 : 0); - for (int i = 0; i < num; i++) + val += mi.IsGenericMethod ? 1 : 0; + for (var i = 0; i < num; i++) { val += ArgPrecedence(pi[i].ParameterType); } @@ -190,45 +190,78 @@ internal static int GetPrecedence(MethodBase mi) /// internal static int ArgPrecedence(Type t) { - Type objectType = typeof(Object); + Type objectType = typeof(object); if (t == objectType) + { return 3000; + } TypeCode tc = Type.GetTypeCode(t); + // TODO: Clean up if (tc == TypeCode.Object) + { return 1; + } if (tc == TypeCode.UInt64) + { return 10; + } if (tc == TypeCode.UInt32) + { return 11; + } if (tc == TypeCode.UInt16) + { return 12; + } if (tc == TypeCode.Int64) + { return 13; + } if (tc == TypeCode.Int32) + { return 14; + } if (tc == TypeCode.Int16) + { return 15; + } if (tc == TypeCode.Char) + { return 16; + } if (tc == TypeCode.SByte) + { return 17; + } if (tc == TypeCode.Byte) + { return 18; + } if (tc == TypeCode.Single) + { return 20; + } if (tc == TypeCode.Double) + { return 21; + } if (tc == TypeCode.String) + { return 30; + } if (tc == TypeCode.Boolean) + { return 40; + } if (t.IsArray) { Type e = t.GetElementType(); if (e == objectType) + { return 2500; + } return 100 + ArgPrecedence(e); } @@ -242,12 +275,12 @@ internal static int ArgPrecedence(Type t) /// internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw) { - return this.Bind(inst, args, kw, null, null); + return Bind(inst, args, kw, null, null); } internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) { - return this.Bind(inst, args, kw, info, null); + return Bind(inst, args, kw, info, null); } internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo) @@ -256,11 +289,11 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth MethodBase[] _methods = null; int pynargs = Runtime.PyTuple_Size(args); object arg; - bool isGeneric = false; + var isGeneric = false; ArrayList defaultArgList = null; if (info != null) { - _methods = (MethodBase[])Array.CreateInstance(typeof(MethodBase), 1); + _methods = new MethodBase[1]; _methods.SetValue(info, 0); } else @@ -268,19 +301,18 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth _methods = GetMethods(); } Type clrtype; - for (int i = 0; i < _methods.Length; i++) + // TODO: Clean up + foreach (MethodBase mi in _methods) { - MethodBase mi = _methods[i]; - if (mi.IsGenericMethod) { isGeneric = true; } ParameterInfo[] pi = mi.GetParameters(); int clrnargs = pi.Length; - bool match = false; + var match = false; int arrayStart = -1; - int outs = 0; + var outs = 0; if (pynargs == clrnargs) { @@ -293,12 +325,16 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth for (int v = pynargs; v < clrnargs; v++) { if (pi[v].DefaultValue == DBNull.Value) + { match = false; + } else - defaultArgList.Add((object)pi[v].DefaultValue); + { + defaultArgList.Add(pi[v].DefaultValue); + } } } - else if ((pynargs > clrnargs) && (clrnargs > 0) && + else if (pynargs > clrnargs && clrnargs > 0 && Attribute.IsDefined(pi[clrnargs - 1], typeof(ParamArrayAttribute))) { // This is a spam(params object[] egg) style method @@ -308,9 +344,9 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth if (match) { - Object[] margs = new Object[clrnargs]; + var margs = new object[clrnargs]; - for (int n = 0; n < clrnargs; n++) + for (var n = 0; n < clrnargs; n++) { IntPtr op; if (n < pynargs) @@ -346,7 +382,7 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth if (clrtype != null) { - bool typematch = false; + var typematch = false; if (pi[n].ParameterType != clrtype) { IntPtr pytype = Converter.GetPythonTypeByAlias(pi[n].ParameterType); @@ -415,7 +451,9 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth else { if (defaultArgList != null) + { margs[n] = defaultArgList[n - pynargs]; + } } } @@ -424,13 +462,13 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth continue; } - Object target = null; - if ((!mi.IsStatic) && (inst != IntPtr.Zero)) + object target = null; + if (!mi.IsStatic && inst != IntPtr.Zero) { //CLRObject co = (CLRObject)ManagedType.GetManagedObject(inst); // InvalidCastException: Unable to cast object of type // 'Python.Runtime.ClassObject' to type 'Python.Runtime.CLRObject' - CLRObject co = ManagedType.GetManagedObject(inst) as CLRObject; + var co = ManagedType.GetManagedObject(inst) as CLRObject; // Sanity check: this ensures a graceful exit if someone does // something intentionally wrong like call a non-static method @@ -450,10 +488,10 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth // is a generic method and info is null. That happens when a generic // method was not called using the [] syntax. Let's introspect the // type of the arguments and use it to construct the correct method. - if (isGeneric && (info == null) && (methodinfo != null)) + if (isGeneric && info == null && methodinfo != null) { Type[] types = Runtime.PythonArgsToTypeArray(args, true); - MethodInfo mi = MethodBinder.MatchParameters(methodinfo, types); + MethodInfo mi = MatchParameters(methodinfo, types); return Bind(inst, args, kw, mi, null); } return null; @@ -461,18 +499,18 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw) { - return this.Invoke(inst, args, kw, null, null); + return Invoke(inst, args, kw, null, null); } internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) { - return this.Invoke(inst, args, kw, info, null); + return Invoke(inst, args, kw, info, null); } internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo) { - Binding binding = this.Bind(inst, args, kw, info, methodinfo); - Object result; + Binding binding = Bind(inst, args, kw, info, methodinfo); + object result; IntPtr ts = IntPtr.Zero; if (binding == null) @@ -515,9 +553,9 @@ internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase i // we return the out parameter as the result to Python (for // code compatibility with ironpython). - MethodInfo mi = (MethodInfo)binding.info; + var mi = (MethodInfo)binding.info; - if ((binding.outs == 1) && (mi.ReturnType == typeof(void))) + if (binding.outs == 1 && mi.ReturnType == typeof(void)) { } @@ -525,14 +563,14 @@ internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase i { ParameterInfo[] pi = mi.GetParameters(); int c = pi.Length; - int n = 0; + var n = 0; IntPtr t = Runtime.PyTuple_New(binding.outs + 1); IntPtr v = Converter.ToPython(result, mi.ReturnType); Runtime.PyTuple_SetItem(t, n, v); n++; - for (int i = 0; i < c; i++) + for (var i = 0; i < c; i++) { Type pt = pi[i].ParameterType; if (pi[i].IsOut || pt.IsByRef) @@ -543,7 +581,7 @@ internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase i } } - if ((binding.outs == 1) && (mi.ReturnType == typeof(void))) + if (binding.outs == 1 && mi.ReturnType == typeof(void)) { v = Runtime.PyTuple_GetItem(t, 1); Runtime.XIncref(v); @@ -564,14 +602,18 @@ internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase i /// internal class MethodSorter : IComparer { - int IComparer.Compare(Object m1, Object m2) + int IComparer.Compare(object m1, object m2) { int p1 = MethodBinder.GetPrecedence((MethodBase)m1); int p2 = MethodBinder.GetPrecedence((MethodBase)m2); if (p1 < p2) + { return -1; + } if (p1 > p2) + { return 1; + } return 0; } } @@ -585,11 +627,11 @@ int IComparer.Compare(Object m1, Object m2) internal class Binding { public MethodBase info; - public Object[] args; - public Object inst; + public object[] args; + public object inst; public int outs; - internal Binding(MethodBase info, Object inst, Object[] args, int outs) + internal Binding(MethodBase info, object inst, object[] args, int outs) { this.info = info; this.inst = inst; diff --git a/src/runtime/methodbinding.cs b/src/runtime/methodbinding.cs index 878779989..22b883186 100644 --- a/src/runtime/methodbinding.cs +++ b/src/runtime/methodbinding.cs @@ -1,6 +1,6 @@ using System; -using System.Reflection; using System.Collections.Generic; +using System.Reflection; namespace Python.Runtime { @@ -16,14 +16,16 @@ internal class MethodBinding : ExtensionType internal IntPtr target; internal IntPtr targetType; - public MethodBinding(MethodObject m, IntPtr target, IntPtr targetType) : base() + public MethodBinding(MethodObject m, IntPtr target, IntPtr targetType) { Runtime.XIncref(target); this.target = target; Runtime.XIncref(targetType); if (targetType == IntPtr.Zero) + { targetType = Runtime.PyObject_Type(target); + } this.targetType = targetType; this.info = null; @@ -39,7 +41,7 @@ public MethodBinding(MethodObject m, IntPtr target) : this(m, target, IntPtr.Zer /// public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) { - MethodBinding self = (MethodBinding)GetManagedObject(tp); + var self = (MethodBinding)GetManagedObject(tp); Type[] types = Runtime.PythonArgsToTypeArray(idx); if (types == null) @@ -50,11 +52,10 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) MethodInfo mi = MethodBinder.MatchParameters(self.m.info, types); if (mi == null) { - string e = "No match found for given type params"; - return Exceptions.RaiseTypeError(e); + return Exceptions.RaiseTypeError("No match found for given type params"); } - MethodBinding mb = new MethodBinding(self.m, self.target); + var mb = new MethodBinding(self.m, self.target); mb.info = mi; Runtime.XIncref(mb.pyHandle); return mb.pyHandle; @@ -66,7 +67,7 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) /// public static IntPtr tp_getattro(IntPtr ob, IntPtr key) { - MethodBinding self = (MethodBinding)GetManagedObject(ob); + var self = (MethodBinding)GetManagedObject(ob); if (!Runtime.PyString_Check(key)) { @@ -82,10 +83,10 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key) return doc; } - // XXX deprecate __overloads__ soon... + // FIXME: deprecate __overloads__ soon... if (name == "__overloads__" || name == "Overloads") { - OverloadMapper om = new OverloadMapper(self.m, self.target); + var om = new OverloadMapper(self.m, self.target); Runtime.XIncref(om.pyHandle); return om.pyHandle; } @@ -99,7 +100,7 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key) /// public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { - MethodBinding self = (MethodBinding)GetManagedObject(ob); + var self = (MethodBinding)GetManagedObject(ob); // This works around a situation where the wrong generic method is picked, // for example this method in the tests: string Overloaded(int arg1, int arg2, string arg3) @@ -107,14 +108,16 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { if (self.info.IsGenericMethod) { - int len = Runtime.PyTuple_Size(args); + int len = Runtime.PyTuple_Size(args); //FIXME: Never used Type[] sigTp = Runtime.PythonArgsToTypeArray(args, true); if (sigTp != null) { Type[] genericTp = self.info.GetGenericArguments(); MethodInfo betterMatch = MethodBinder.MatchSignatureAndParameters(self.m.info, genericTp, sigTp); if (betterMatch != null) + { self.info = betterMatch; + } } } } @@ -123,12 +126,12 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) // as the first argument. Note that this is not supported if any // of the overloads are static since we can't know if the intent // was to call the static method or the unbound instance method. - List disposeList = new List(); + var disposeList = new List(); try { IntPtr target = self.target; - if ((target == IntPtr.Zero) && (!self.m.IsStatic())) + if (target == IntPtr.Zero && !self.m.IsStatic()) { int len = Runtime.PyTuple_Size(args); if (len < 1) @@ -150,19 +153,21 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) IntPtr superType = IntPtr.Zero; if (Runtime.PyObject_TYPE(target) != self.targetType) { - CLRObject inst = CLRObject.GetManagedObject(target) as CLRObject; - if (inst != null && (inst.inst as IPythonDerivedType) != null) + var inst = GetManagedObject(target) as CLRObject; + if (inst?.inst is IPythonDerivedType) { - ClassBase baseType = GetManagedObject(self.targetType) as ClassBase; + var baseType = GetManagedObject(self.targetType) as ClassBase; if (baseType != null) { string baseMethodName = "_" + baseType.type.Name + "__" + self.m.name; IntPtr baseMethod = Runtime.PyObject_GetAttrString(target, baseMethodName); if (baseMethod != IntPtr.Zero) { - MethodBinding baseSelf = GetManagedObject(baseMethod) as MethodBinding; + var baseSelf = GetManagedObject(baseMethod) as MethodBinding; if (baseSelf != null) + { self = baseSelf; + } Runtime.XDecref(baseMethod); } else @@ -178,7 +183,9 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) finally { foreach (IntPtr ptr in disposeList) + { Runtime.XDecref(ptr); + } } } @@ -188,7 +195,7 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) /// public static IntPtr tp_hash(IntPtr ob) { - MethodBinding self = (MethodBinding)GetManagedObject(ob); + var self = (MethodBinding)GetManagedObject(ob); long x = 0; long y = 0; @@ -222,21 +229,21 @@ public static IntPtr tp_hash(IntPtr ob) /// public static IntPtr tp_repr(IntPtr ob) { - MethodBinding self = (MethodBinding)GetManagedObject(ob); - string type = (self.target == IntPtr.Zero) ? "unbound" : "bound"; - string s = String.Format("<{0} method '{1}'>", type, self.m.name); + var self = (MethodBinding)GetManagedObject(ob); + string type = self.target == IntPtr.Zero ? "unbound" : "bound"; + string s = string.Format("<{0} method '{1}'>", type, self.m.name); return Runtime.PyString_FromStringAndSize(s, s.Length); } /// /// MethodBinding dealloc implementation. /// - public static new void tp_dealloc(IntPtr ob) + public new static void tp_dealloc(IntPtr ob) { - MethodBinding self = (MethodBinding)GetManagedObject(ob); + var self = (MethodBinding)GetManagedObject(ob); Runtime.XDecref(self.target); Runtime.XDecref(self.targetType); - ExtensionType.FinalizeObject(self); + FinalizeObject(self); } } } diff --git a/src/runtime/methodobject.cs b/src/runtime/methodobject.cs index d30188d44..d2d821eb5 100644 --- a/src/runtime/methodobject.cs +++ b/src/runtime/methodobject.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Reflection; namespace Python.Runtime @@ -21,12 +20,12 @@ internal class MethodObject : ExtensionType internal IntPtr doc; internal Type type; - public MethodObject(Type type, string name, MethodInfo[] info) : base() + public MethodObject(Type type, string name, MethodInfo[] info) { _MethodObject(type, name, info); } - public MethodObject(Type type, string name, MethodInfo[] info, bool allow_threads) : base() + public MethodObject(Type type, string name, MethodInfo[] info, bool allow_threads) { _MethodObject(type, name, info); binder.allow_threads = allow_threads; @@ -38,9 +37,8 @@ private void _MethodObject(Type type, string name, MethodInfo[] info) this.name = name; this.info = info; binder = new MethodBinder(); - for (int i = 0; i < info.Length; i++) + foreach (MethodInfo item in info) { - MethodInfo item = (MethodInfo)info[i]; binder.AddMethod(item); if (item.IsStatic) { @@ -51,7 +49,7 @@ private void _MethodObject(Type type, string name, MethodInfo[] info) public virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw) { - return this.Invoke(inst, args, kw, null); + return Invoke(inst, args, kw, null); } public virtual IntPtr Invoke(IntPtr target, IntPtr args, IntPtr kw, MethodBase info) @@ -68,21 +66,23 @@ internal IntPtr GetDocString() { return doc; } - string str = ""; + var str = ""; Type marker = typeof(DocStringAttribute); MethodBase[] methods = binder.GetMethods(); foreach (MethodBase method in methods) { if (str.Length > 0) + { str += Environment.NewLine; - Attribute[] attrs = (Attribute[])method.GetCustomAttributes(marker, false); + } + var attrs = (Attribute[])method.GetCustomAttributes(marker, false); if (attrs.Length == 0) { str += method.ToString(); } else { - DocStringAttribute attr = (DocStringAttribute)attrs[0]; + var attr = (DocStringAttribute)attrs[0]; str += attr.DocString; } } @@ -106,7 +106,7 @@ internal IntPtr GetDocString() /// internal bool IsStatic() { - return this.is_static; + return is_static; } /// @@ -114,7 +114,7 @@ internal bool IsStatic() /// public static IntPtr tp_getattro(IntPtr ob, IntPtr key) { - MethodObject self = (MethodObject)GetManagedObject(ob); + var self = (MethodObject)GetManagedObject(ob); if (!Runtime.PyString_Check(key)) { @@ -138,7 +138,7 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key) /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { - MethodObject self = (MethodObject)GetManagedObject(ds); + var self = (MethodObject)GetManagedObject(ds); MethodBinding binding; // If the method is accessed through its type (rather than via @@ -166,11 +166,11 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) // this descriptor was defined on then it will be because the base class method // is being called via super(Derived, self).method(...). // In which case create a MethodBinding bound to the base class. - CLRObject obj = GetManagedObject(ob) as CLRObject; + var obj = GetManagedObject(ob) as CLRObject; if (obj != null && obj.inst.GetType() != self.type && obj.inst is IPythonDerivedType - && self.type.IsAssignableFrom(obj.inst.GetType())) + && self.type.IsInstanceOfType(obj.inst)) { ClassBase basecls = ClassManager.GetClass(self.type); binding = new MethodBinding(self, ob, basecls.pyHandle); @@ -186,17 +186,17 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// public static IntPtr tp_repr(IntPtr ob) { - MethodObject self = (MethodObject)GetManagedObject(ob); - string s = String.Format("", self.name); + var self = (MethodObject)GetManagedObject(ob); + string s = string.Format("", self.name); return Runtime.PyString_FromStringAndSize(s, s.Length); } /// /// Descriptor dealloc implementation. /// - public static new void tp_dealloc(IntPtr ob) + public new static void tp_dealloc(IntPtr ob) { - MethodObject self = (MethodObject)GetManagedObject(ob); + var self = (MethodObject)GetManagedObject(ob); Runtime.XDecref(self.doc); if (self.unbound != null) { diff --git a/src/runtime/moduleobject.cs b/src/runtime/moduleobject.cs index 3b9ad94a9..c18a2cdf9 100644 --- a/src/runtime/moduleobject.cs +++ b/src/runtime/moduleobject.cs @@ -1,9 +1,7 @@ using System; -using System.Collections.Specialized; -using System.Runtime.InteropServices; using System.Collections.Generic; -using System.Collections; using System.Reflection; +using System.Runtime.InteropServices; namespace Python.Runtime { @@ -18,9 +16,9 @@ internal class ModuleObject : ExtensionType internal IntPtr dict; protected string _namespace; - public ModuleObject(string name) : base() + public ModuleObject(string name) { - if (name == String.Empty) + if (name == string.Empty) { throw new ArgumentException("Name must not be empty!"); } @@ -30,8 +28,8 @@ public ModuleObject(string name) : base() // Use the filename from any of the assemblies just so there's something for // anything that expects __file__ to be set. - string filename = "unknown"; - string docstring = "Namespace containing types from the following assemblies:\n\n"; + var filename = "unknown"; + var docstring = "Namespace containing types from the following assemblies:\n\n"; foreach (Assembly a in AssemblyManager.GetAssemblies(name)) { if (!a.IsDynamic && a.Location != null) @@ -54,7 +52,7 @@ public ModuleObject(string name) : base() Runtime.XDecref(pyfilename); Runtime.XDecref(pydocstring); - Marshal.WriteIntPtr(this.pyHandle, ObjectOffset.DictOffset(this.pyHandle), dict); + Marshal.WriteIntPtr(pyHandle, ObjectOffset.DictOffset(pyHandle), dict); InitializeModuleMembers(); } @@ -69,7 +67,7 @@ public ModuleObject(string name) : base() public ManagedType GetAttribute(string name, bool guess) { ManagedType cached = null; - this.cache.TryGetValue(name, out cached); + cache.TryGetValue(name, out cached); if (cached != null) { return cached; @@ -89,25 +87,23 @@ public ManagedType GetAttribute(string name, bool guess) // return null; //} - string qname = (_namespace == String.Empty) + string qname = _namespace == string.Empty ? name : _namespace + "." + name; // If the fully-qualified name of the requested attribute is // a namespace exported by a currently loaded assembly, return // a new ModuleObject representing that namespace. - if (AssemblyManager.IsValidNamespace(qname)) { m = new ModuleObject(qname); StoreAttribute(name, m); - return (ManagedType)m; + return m; } // Look for a type in the current namespace. Note that this // includes types, delegates, enums, interfaces and structs. // Only public namespace members are exposed to Python. - type = AssemblyManager.LookupType(qname); if (type != null) { @@ -117,7 +113,7 @@ public ManagedType GetAttribute(string name, bool guess) } c = ClassManager.GetClass(type); StoreAttribute(name, c); - return (ManagedType)c; + return c; } // This is a little repetitive, but it ensures that the right @@ -131,7 +127,7 @@ public ManagedType GetAttribute(string name, bool guess) { m = new ModuleObject(qname); StoreAttribute(name, m); - return (ManagedType)m; + return m; } type = AssemblyManager.LookupType(qname); @@ -143,7 +139,7 @@ public ManagedType GetAttribute(string name, bool guess) } c = ClassManager.GetClass(type); StoreAttribute(name, c); - return (ManagedType)c; + return c; } } @@ -154,7 +150,6 @@ public ManagedType GetAttribute(string name, bool guess) // future assembly load could contribute a non-generic type to // the current namespace with the given basename, but unlikely // enough to complicate the implementation for now. - if (guess) { string gname = GenericUtil.GenericNameForBaseName(_namespace, name); @@ -193,10 +188,10 @@ public void LoadNames() ManagedType m = null; foreach (string name in AssemblyManager.GetNames(_namespace)) { - this.cache.TryGetValue(name, out m); + cache.TryGetValue(name, out m); if (m == null) { - ManagedType attr = this.GetAttribute(name, true); + ManagedType attr = GetAttribute(name, true); } } } @@ -209,38 +204,36 @@ internal void InitializeModuleMembers() Type funcmarker = typeof(ModuleFunctionAttribute); Type propmarker = typeof(ModulePropertyAttribute); Type ftmarker = typeof(ForbidPythonThreadsAttribute); - Type type = this.GetType(); + Type type = GetType(); BindingFlags flags = BindingFlags.Public | BindingFlags.Static; while (type != null) { MethodInfo[] methods = type.GetMethods(flags); - for (int i = 0; i < methods.Length; i++) + foreach (MethodInfo method in methods) { - MethodInfo method = methods[i]; object[] attrs = method.GetCustomAttributes(funcmarker, false); object[] forbid = method.GetCustomAttributes(ftmarker, false); - bool allow_threads = (forbid.Length == 0); + bool allow_threads = forbid.Length == 0; if (attrs.Length > 0) { string name = method.Name; - MethodInfo[] mi = new MethodInfo[1]; + var mi = new MethodInfo[1]; mi[0] = method; - ModuleFunctionObject m = new ModuleFunctionObject(type, name, mi, allow_threads); + var m = new ModuleFunctionObject(type, name, mi, allow_threads); StoreAttribute(name, m); } } PropertyInfo[] properties = type.GetProperties(); - for (int i = 0; i < properties.Length; i++) + foreach (PropertyInfo property in properties) { - PropertyInfo property = properties[i]; object[] attrs = property.GetCustomAttributes(propmarker, false); if (attrs.Length > 0) { string name = property.Name; - ModulePropertyObject p = new ModulePropertyObject(property); + var p = new ModulePropertyObject(property); StoreAttribute(name, p); } } @@ -257,7 +250,7 @@ internal void InitializeModuleMembers() /// public static IntPtr tp_getattro(IntPtr ob, IntPtr key) { - ModuleObject self = (ModuleObject)GetManagedObject(ob); + var self = (ModuleObject)GetManagedObject(ob); if (!Runtime.PyString_Check(key)) { @@ -296,9 +289,8 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key) /// public static IntPtr tp_repr(IntPtr ob) { - ModuleObject self = (ModuleObject)GetManagedObject(ob); - string s = String.Format("", self.moduleName); - return Runtime.PyString_FromString(s); + var self = (ModuleObject)GetManagedObject(ob); + return Runtime.PyString_FromString($""); } } @@ -318,7 +310,7 @@ internal class CLRModule : ModuleObject public CLRModule() : base("clr") { - _namespace = String.Empty; + _namespace = string.Empty; // This hackery is required in order to allow a plain Python to // import the managed runtime via the CLR bootstrapper module. @@ -357,13 +349,13 @@ internal void InitializePreload() } } - [ModuleFunctionAttribute()] + [ModuleFunctionAttribute] public static bool getPreload() { return preload; } - [ModuleFunctionAttribute()] + [ModuleFunctionAttribute] public static void setPreload(bool preloadFlag) { preload = preloadFlag; @@ -383,8 +375,8 @@ public static bool SuppressOverloads set { _SuppressOverloads = value; } } - [ModuleFunctionAttribute()] - [ForbidPythonThreadsAttribute()] + [ModuleFunctionAttribute] + [ForbidPythonThreadsAttribute] public static Assembly AddReference(string name) { AssemblyManager.UpdatePath(); @@ -404,37 +396,40 @@ public static Assembly AddReference(string name) } if (assembly == null) { - string msg = String.Format("Unable to find assembly '{0}'.", name); - throw new System.IO.FileNotFoundException(msg); + throw new System.IO.FileNotFoundException($"Unable to find assembly '{name}'."); } return assembly; } - [ModuleFunctionAttribute()] - [ForbidPythonThreadsAttribute()] + [ModuleFunctionAttribute] + [ForbidPythonThreadsAttribute] public static string FindAssembly(string name) { AssemblyManager.UpdatePath(); return AssemblyManager.FindAssembly(name); } - [ModuleFunctionAttribute()] - public static String[] ListAssemblies(bool verbose) + [ModuleFunctionAttribute] + public static string[] ListAssemblies(bool verbose) { AssemblyName[] assnames = AssemblyManager.ListAssemblies(); - String[] names = new String[assnames.Length]; - for (int i = 0; i < assnames.Length; i++) + var names = new string[assnames.Length]; + for (var i = 0; i < assnames.Length; i++) { if (verbose) + { names[i] = assnames[i].FullName; + } else + { names[i] = assnames[i].Name; + } } return names; } - [ModuleFunctionAttribute()] + [ModuleFunctionAttribute] public static int _AtExit() { return Runtime.AtExit(); diff --git a/src/runtime/nativecall.cs b/src/runtime/nativecall.cs index f49f08e7b..e81b34dde 100644 --- a/src/runtime/nativecall.cs +++ b/src/runtime/nativecall.cs @@ -1,9 +1,8 @@ using System; -using System.Threading; -using System.Runtime.InteropServices; -using System.Collections; using System.Reflection; using System.Reflection.Emit; +using System.Runtime.InteropServices; +using System.Threading; namespace Python.Runtime { @@ -38,8 +37,7 @@ static NativeCall() // interface (defined below) and generate the required thunk // code based on the method signatures. - var aname = new AssemblyName(); - aname.Name = "e__NativeCall_Assembly"; + var aname = new AssemblyName { Name = "e__NativeCall_Assembly" }; var aa = AssemblyBuilderAccess.Run; aBuilder = Thread.GetDomain().DefineDynamicAssembly(aname, aa); diff --git a/src/runtime/pynumber.cs b/src/runtime/pynumber.cs index 371d9f4f6..4f7373a8c 100644 --- a/src/runtime/pynumber.cs +++ b/src/runtime/pynumber.cs @@ -9,6 +9,9 @@ namespace Python.Runtime /// PY3: https://docs.python.org/3/c-api/number.html /// for details. /// + /// + /// TODO: add all of the PyNumber_XXX methods. + /// public class PyNumber : PyObject { protected PyNumber(IntPtr ptr) : base(ptr) @@ -30,8 +33,5 @@ public static bool IsNumberType(PyObject value) { return Runtime.PyNumber_Check(value.obj); } - - - // TODO: add all of the PyNumber_XXX methods. } } diff --git a/src/runtime/pyobject.cs b/src/runtime/pyobject.cs index ddc0e4c4c..837c2d312 100644 --- a/src/runtime/pyobject.cs +++ b/src/runtime/pyobject.cs @@ -1,7 +1,7 @@ using System; +using System.Collections; using System.Dynamic; using System.Linq.Expressions; -using System.Collections; namespace Python.Runtime { @@ -89,8 +89,8 @@ public static PyObject FromManagedObject(object ob) /// public object AsManagedObject(Type t) { - Object result; - if (!Converter.ToManaged(this.obj, t, out result, false)) + object result; + if (!Converter.ToManaged(obj, t, out result, false)) { throw new InvalidCastException("cannot convert object to target type"); } @@ -166,7 +166,7 @@ public bool TypeCheck(PyObject typeOrClass) /// public bool HasAttr(string name) { - return (Runtime.PyObject_HasAttrString(obj, name) != 0); + return Runtime.PyObject_HasAttrString(obj, name) != 0; } @@ -179,7 +179,7 @@ public bool HasAttr(string name) /// public bool HasAttr(PyObject name) { - return (Runtime.PyObject_HasAttr(obj, name.obj) != 0); + return Runtime.PyObject_HasAttr(obj, name.obj) != 0; } @@ -358,7 +358,7 @@ public virtual PyObject GetItem(PyObject key) /// public virtual PyObject GetItem(string key) { - using (PyString pyKey = new PyString(key)) + using (var pyKey = new PyString(key)) { return GetItem(pyKey); } @@ -375,9 +375,9 @@ public virtual PyObject GetItem(string key) /// public virtual PyObject GetItem(int index) { - using (PyInt key = new PyInt(index)) + using (var key = new PyInt(index)) { - return GetItem((PyObject)key); + return GetItem(key); } } @@ -410,7 +410,7 @@ public virtual void SetItem(PyObject key, PyObject value) /// public virtual void SetItem(string key, PyObject value) { - using (PyString pyKey = new PyString(key)) + using (var pyKey = new PyString(key)) { SetItem(pyKey, value); } @@ -427,7 +427,7 @@ public virtual void SetItem(string key, PyObject value) /// public virtual void SetItem(int index, PyObject value) { - using (PyInt pyindex = new PyInt(index)) + using (var pyindex = new PyInt(index)) { SetItem(pyindex, value); } @@ -462,7 +462,7 @@ public virtual void DelItem(PyObject key) /// public virtual void DelItem(string key) { - using (PyString pyKey = new PyString(key)) + using (var pyKey = new PyString(key)) { DelItem(pyKey); } @@ -479,7 +479,7 @@ public virtual void DelItem(string key) /// public virtual void DelItem(int index) { - using (PyInt pyindex = new PyInt(index)) + using (var pyindex = new PyInt(index)) { DelItem(pyindex); } @@ -588,7 +588,7 @@ public IEnumerator GetEnumerator() /// public PyObject Invoke(params PyObject[] args) { - PyTuple t = new PyTuple(args); + var t = new PyTuple(args); IntPtr r = Runtime.PyObject_Call(obj, t.obj, IntPtr.Zero); t.Dispose(); if (r == IntPtr.Zero) @@ -626,7 +626,7 @@ public PyObject Invoke(PyTuple args) /// public PyObject Invoke(PyObject[] args, PyDict kw) { - PyTuple t = new PyTuple(args); + var t = new PyTuple(args); IntPtr r = Runtime.PyObject_Call(obj, t.obj, kw != null ? kw.obj : IntPtr.Zero); t.Dispose(); if (r == IntPtr.Zero) @@ -736,7 +736,7 @@ public bool IsInstance(PyObject typeOrClass) Runtime.PyErr_Clear(); return false; } - return (r != 0); + return r != 0; } @@ -755,7 +755,7 @@ public bool IsSubclass(PyObject typeOrClass) Runtime.PyErr_Clear(); return false; } - return (r != 0); + return r != 0; } @@ -768,7 +768,7 @@ public bool IsSubclass(PyObject typeOrClass) /// public bool IsCallable() { - return (Runtime.PyCallable_Check(obj) != 0); + return Runtime.PyCallable_Check(obj) != 0; } @@ -794,7 +794,7 @@ public bool IsIterable() /// public bool IsTrue() { - return (Runtime.PyObject_IsTrue(obj) != 0); + return Runtime.PyObject_IsTrue(obj) != 0; } @@ -870,7 +870,7 @@ public override bool Equals(object o) { throw new PythonException(); } - return (r == 0); + return r == 0; } @@ -914,7 +914,7 @@ private void GetArgs(object[] inargs, out PyTuple args, out PyDict kwargs) int arg_count; for (arg_count = 0; arg_count < inargs.Length && !(inargs[arg_count] is Py.KeywordArguments); ++arg_count) ; IntPtr argtuple = Runtime.PyTuple_New(arg_count); - for (int i = 0; i < arg_count; i++) + for (var i = 0; i < arg_count; i++) { IntPtr ptr; if (inargs[i] is PyObject) @@ -927,18 +927,26 @@ private void GetArgs(object[] inargs, out PyTuple args, out PyDict kwargs) ptr = Converter.ToPython(inargs[i], inargs[i]?.GetType()); } if (Runtime.PyTuple_SetItem(argtuple, i, ptr) < 0) + { throw new PythonException(); + } } args = new PyTuple(argtuple); kwargs = null; for (int i = arg_count; i < inargs.Length; i++) { if (!(inargs[i] is Py.KeywordArguments)) + { throw new ArgumentException("Keyword arguments must come after normal arguments."); + } if (kwargs == null) + { kwargs = (Py.KeywordArguments)inargs[i]; + } else + { kwargs.Update((Py.KeywordArguments)inargs[i]); + } } } @@ -956,9 +964,13 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o finally { if (null != pyargs) + { pyargs.Dispose(); + } if (null != kwargs) + { kwargs.Dispose(); + } } return true; } @@ -980,9 +992,13 @@ public override bool TryInvoke(InvokeBinder binder, object[] args, out object re finally { if (null != pyargs) + { pyargs.Dispose(); + } if (null != kwargs) + { kwargs.Dispose(); + } } return true; } @@ -995,11 +1011,13 @@ public override bool TryConvert(ConvertBinder binder, out object result) return Converter.ToManaged(this.obj, binder.Type, out result, false); } - public override bool TryBinaryOperation(BinaryOperationBinder binder, Object arg, out Object result) + public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result) { IntPtr res; if (!(arg is PyObject)) + { arg = arg.ToPython(); + } switch (binder.Operation) { @@ -1104,7 +1122,7 @@ private static object CheckNone(PyObject pyObj) return pyObj; } - public override bool TryUnaryOperation(UnaryOperationBinder binder, out Object result) + public override bool TryUnaryOperation(UnaryOperationBinder binder, out object result) { int r; IntPtr res; diff --git a/src/runtime/pystring.cs b/src/runtime/pystring.cs index 3bd99b87c..624de80eb 100644 --- a/src/runtime/pystring.cs +++ b/src/runtime/pystring.cs @@ -3,7 +3,7 @@ namespace Python.Runtime { /// - /// Represents a Python (ansi) string object. See the documentation at + /// Represents a Python (ANSI) string object. See the documentation at /// PY2: https://docs.python.org/2/c-api/string.html /// PY3: No Equivalent /// for details. diff --git a/src/runtime/typemanager.cs b/src/runtime/typemanager.cs index 49c931183..930030a71 100644 --- a/src/runtime/typemanager.cs +++ b/src/runtime/typemanager.cs @@ -1,8 +1,8 @@ using System; -using System.Runtime.InteropServices; -using System.Collections.Generic; using System.Collections; +using System.Collections.Generic; using System.Reflection; +using System.Runtime.InteropServices; namespace Python.Runtime { diff --git a/src/runtime/typemethod.cs b/src/runtime/typemethod.cs index 946c769b2..4da92613c 100644 --- a/src/runtime/typemethod.cs +++ b/src/runtime/typemethod.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Reflection; namespace Python.Runtime From 073d7e8d62f70263f8222391cedc036151c84b64 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Feb 2017 15:18:55 -0700 Subject: [PATCH 073/245] Update CHANGELOG --- CHANGELOG.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b547712fa..36f3ecfeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,15 +10,18 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. ### Added - Code Coverage (#345) -- Add `pysetargv` (#347) +- Added `pysetargv` (#347) +- Added XML Documentation (#349) +- Added PY3 settings to configuration-manager (#346) ### Changed - Refactored `setup.py` (#337) -- Upgraded NUnit framework to 3.5 (#341) +- Upgraded NUnit framework to 2.6.4 (#353) - Completed refactor of Build Directives on `Runtime.cs` (#339) - Refactor tests and removed dependency on `six` (#329) - Unfroze Mono version on Travis (#345) +- Enabled Embedded tests on Appveyor (#353) ### Fixed From eb9465a5121bde9927f57468b89da44c04c4abb0 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Feb 2017 17:47:55 -0700 Subject: [PATCH 074/245] Clarify pynetinit.c, runtime build directives pynetinit.c: Clarifiy its intent is for PY3 runtime.cs Remove unnecessary check for System.Text Simplifies import section --- src/monoclr/pynetinit.c | 4 ++-- src/runtime/runtime.cs | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/monoclr/pynetinit.c b/src/monoclr/pynetinit.c index ed09d45d7..8b49ddae3 100644 --- a/src/monoclr/pynetinit.c +++ b/src/monoclr/pynetinit.c @@ -135,7 +135,7 @@ void main_thread_handler(gpointer user_data) int ii = 0; for (ii = 0; ii < PyList_Size(syspath); ++ii) { -#if PY_MAJOR_VERSION > 2 +#if PY_MAJOR_VERSION >= 3 Py_ssize_t wlen; wchar_t *wstr = PyUnicode_AsWideCharString(PyList_GetItem(syspath, ii), &wlen); char *pydir = (char*)malloc(wlen + 1); @@ -150,7 +150,7 @@ void main_thread_handler(gpointer user_data) strncpy(curdir, strlen(pydir) > 0 ? pydir : ".", 1024); strncat(curdir, slash, 1024); -#if PY_MAJOR_VERSION > 2 +#if PY_MAJOR_VERSION >= 3 free(pydir); #endif diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 3757ce6aa..9debe766b 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1,11 +1,10 @@ using System; using System.Runtime.InteropServices; using System.Security; -#if UCS4 using System.Text; + +#if UCS4 using Mono.Unix; -#elif UCS2 && PYTHON3 -using System.Text; #endif namespace Python.Runtime From 3dde7849d7d6aa0fc5f4f57c1e47ab9ce349ff08 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Feb 2017 17:48:27 -0700 Subject: [PATCH 075/245] Whitespace converter.cs --- src/runtime/converter.cs | 41 ++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 5e292e82d..52637c3d5 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -85,7 +85,8 @@ internal static IntPtr GetPythonTypeByAlias(Type op) #if PYTHON3 else if ((op == int16Type) || (op == int32Type) || - (op == int64Type)) { + (op == int64Type)) + { return Runtime.PyIntType; } #endif @@ -465,29 +466,29 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setEr #elif PYTHON3 // When using Python3 always use the PyLong API { #endif - op = Runtime.PyNumber_Long(value); - if (op == IntPtr.Zero) - { - Exceptions.Clear(); - if (Exceptions.ExceptionMatches(overflow)) + op = Runtime.PyNumber_Long(value); + if (op == IntPtr.Zero) + { + Exceptions.Clear(); + if (Exceptions.ExceptionMatches(overflow)) + { + goto overflow; + } + goto type_error; + } + long ll = (long)Runtime.PyLong_AsLongLong(op); + Runtime.XDecref(op); + if ((ll == -1) && Exceptions.ErrorOccurred()) { goto overflow; } - goto type_error; - } - long ll = (long)Runtime.PyLong_AsLongLong(op); - Runtime.XDecref(op); - if ((ll == -1) && Exceptions.ErrorOccurred()) - { - goto overflow; - } - if (ll > Int32.MaxValue || ll < Int32.MinValue) - { - goto overflow; + if (ll > Int32.MaxValue || ll < Int32.MinValue) + { + goto overflow; + } + result = (int)ll; + return true; } - result = (int)ll; - return true; - } case TypeCode.Boolean: result = (Runtime.PyObject_IsTrue(value) != 0); From de3d2ef3452867498e69840117c47c8ec526d019 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Feb 2017 19:30:00 -0700 Subject: [PATCH 076/245] Propercase AssemblyInfo --- src/clrmodule/clrmodule.csproj | 2 +- src/console/{assemblyinfo.cs => AssemblyInfo.cs} | 0 src/console/Console.csproj | 2 +- src/runtime/{assemblyinfo.cs => AssemblyInfo.cs} | 0 src/runtime/Python.Runtime.csproj | 2 +- 5 files changed, 3 insertions(+), 3 deletions(-) rename src/console/{assemblyinfo.cs => AssemblyInfo.cs} (100%) rename src/runtime/{assemblyinfo.cs => AssemblyInfo.cs} (100%) diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index 8939d5ad0..c3d6ec7dc 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -151,8 +151,8 @@ - + diff --git a/src/console/assemblyinfo.cs b/src/console/AssemblyInfo.cs similarity index 100% rename from src/console/assemblyinfo.cs rename to src/console/AssemblyInfo.cs diff --git a/src/console/Console.csproj b/src/console/Console.csproj index 49fd402dc..ed591af21 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -161,7 +161,7 @@ - + diff --git a/src/runtime/assemblyinfo.cs b/src/runtime/AssemblyInfo.cs similarity index 100% rename from src/runtime/assemblyinfo.cs rename to src/runtime/AssemblyInfo.cs diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 4ddd312b1..f630ab25d 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -169,8 +169,8 @@ + - From edada03ab51e02f6fc491232204c1b4229a073a5 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Feb 2017 21:11:09 -0700 Subject: [PATCH 077/245] Refactor nativemethods --- src/runtime/runtime.cs | 68 ++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 39 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 9debe766b..8fe435428 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -9,30 +9,42 @@ namespace Python.Runtime { - [SuppressUnmanagedCodeSecurityAttribute()] + [SuppressUnmanagedCodeSecurity()] static class NativeMethods { #if MONO_LINUX || MONO_OSX - static public IntPtr LoadLibrary(string fileName) + private static int RTLD_NOW = 0x2; + private static int RTLD_SHARED = 0x20; +#if MONO_OSX + private static IntPtr RTLD_DEFAULT = new IntPtr(-2); + private const string NativeDll = "__Internal"; +#elif MONO_LINUX + private static IntPtr RTLD_DEFAULT = IntPtr.Zero; + private const string NativeDll = "libdl.so"; +#endif + + public static IntPtr LoadLibrary(string fileName) { return dlopen(fileName, RTLD_NOW | RTLD_SHARED); } - static public void FreeLibrary(IntPtr handle) + public static void FreeLibrary(IntPtr handle) { dlclose(handle); } - static public IntPtr GetProcAddress(IntPtr dllHandle, string name) + public static IntPtr GetProcAddress(IntPtr dllHandle, string name) { // look in the exe if dllHandle is NULL - if (IntPtr.Zero == dllHandle) + if (dllHandle == IntPtr.Zero) + { dllHandle = RTLD_DEFAULT; + } // clear previous errors if any dlerror(); - var res = dlsym(dllHandle, name); - var errPtr = dlerror(); + IntPtr res = dlsym(dllHandle, name); + IntPtr errPtr = dlerror(); if (errPtr != IntPtr.Zero) { throw new Exception("dlsym: " + Marshal.PtrToStringAnsi(errPtr)); @@ -40,49 +52,27 @@ static public IntPtr GetProcAddress(IntPtr dllHandle, string name) return res; } -#if MONO_OSX - static int RTLD_NOW = 0x2; - static int RTLD_SHARED = 0x20; - static IntPtr RTLD_DEFAULT = new IntPtr(-2); - - [DllImport("__Internal")] + [DllImport(NativeDll)] private static extern IntPtr dlopen(String fileName, int flags); - [DllImport("__Internal")] + [DllImport(NativeDll)] private static extern IntPtr dlsym(IntPtr handle, String symbol); - [DllImport("__Internal")] + [DllImport(NativeDll)] private static extern int dlclose(IntPtr handle); - [DllImport("__Internal")] + [DllImport(NativeDll)] private static extern IntPtr dlerror(); -#elif MONO_LINUX - static int RTLD_NOW = 0x2; - static int RTLD_SHARED = 0x20; - static IntPtr RTLD_DEFAULT = IntPtr.Zero; - - [DllImport("libdl.so")] - private static extern IntPtr dlopen(String fileName, int flags); - - [DllImport("libdl.so")] - private static extern IntPtr dlsym(IntPtr handle, String symbol); - - [DllImport("libdl.so")] - private static extern int dlclose(IntPtr handle); - - [DllImport("libdl.so")] - private static extern IntPtr dlerror(); -#endif - #else // Windows + private const string NativeDll = "kernel32.dll"; - [DllImport("kernel32.dll")] + [DllImport(NativeDll)] public static extern IntPtr LoadLibrary(string dllToLoad); - [DllImport("kernel32.dll")] + [DllImport(NativeDll)] public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); - [DllImport("kernel32.dll")] + [DllImport(NativeDll)] public static extern bool FreeLibrary(IntPtr hModule); #endif } @@ -189,12 +179,12 @@ internal static void Initialize() { is32bit = IntPtr.Size == 4; - if (0 == Runtime.Py_IsInitialized()) + if (Runtime.Py_IsInitialized() == 0) { Runtime.Py_Initialize(); } - if (0 == Runtime.PyEval_ThreadsInitialized()) + if (Runtime.PyEval_ThreadsInitialized() == 0) { Runtime.PyEval_InitThreads(); } From d98e2434170d0c8b94d69fcdbba457af5aa5a08b Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Feb 2017 16:07:06 -0700 Subject: [PATCH 078/245] Rename `is32bit` to `Is32Bit` for naming consistency --- src/runtime/converter.cs | 2 +- src/runtime/runtime.cs | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 52637c3d5..0399a42d6 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -437,7 +437,7 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setEr case TypeCode.Int32: #if PYTHON2 // Trickery to support 64-bit platforms. - if (Runtime.is32bit) + if (Runtime.Is32Bit) { op = Runtime.PyNumber_Int(value); diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 8fe435428..509192c26 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -170,14 +170,14 @@ public class Runtime internal static Object IsFinalizingLock = new Object(); internal static bool IsFinalizing = false; - internal static bool is32bit; + internal static bool Is32Bit; /// /// Initialize the runtime... /// internal static void Initialize() { - is32bit = IntPtr.Size == 4; + Is32Bit = IntPtr.Size == 4; if (Runtime.Py_IsInitialized() == 0) { @@ -501,7 +501,7 @@ internal unsafe static void XIncref(IntPtr op) void* p = (void*)op; if ((void*)0 != p) { - if (is32bit) + if (Is32Bit) { (*(int*)p)++; } @@ -524,7 +524,7 @@ internal static unsafe void XDecref(IntPtr op) void* p = (void*)op; if ((void*)0 != p) { - if (is32bit) + if (Is32Bit) { --(*(int*)p); } @@ -535,11 +535,11 @@ internal static unsafe void XDecref(IntPtr op) if ((*(int*)p) == 0) { // PyObject_HEAD: struct _typeobject *ob_type - void* t = is32bit + void* t = Is32Bit ? (void*)(*((uint*)p + 1)) : (void*)(*((ulong*)p + 1)); // PyTypeObject: destructor tp_dealloc - void* f = is32bit + void* f = Is32Bit ? (void*)(*((uint*)t + 6)) : (void*)(*((ulong*)t + 6)); if ((void*)0 == f) @@ -558,7 +558,7 @@ internal unsafe static long Refcount(IntPtr op) void* p = (void*)op; if ((void*)0 != p) { - if (is32bit) + if (Is32Bit) { return (*(int*)p); } @@ -887,7 +887,7 @@ internal unsafe static IntPtr #else int n = 1; #endif - if (is32bit) + if (Is32Bit) { return new IntPtr((void*)(*((uint*)p + n))); } From ea77ab0ab55fead179fa3a34776a35770152c1a1 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Feb 2017 16:45:56 -0700 Subject: [PATCH 079/245] Replace UCS2/UCS4 build directive with Runtime.UCS --- src/runtime/converter.cs | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 0399a42d6..f7cbf27be 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -613,17 +613,20 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setEr if (Runtime.PyUnicode_GetSize(value) == 1) { op = Runtime.PyUnicode_AS_UNICODE(value); -#if UCS2 - // 2011-01-02: Marshal as character array because the cast - // result = (char)Marshal.ReadInt16(op); throws an OverflowException - // on negative numbers with Check Overflow option set on the project - Char[] buff = new Char[1]; - Marshal.Copy(op, buff, 0, 1); - result = buff[0]; -#elif UCS4 - // XXX this is probably NOT correct? - result = (char)Marshal.ReadInt32(op); -#endif + if (Runtime.UCS == 2) // Don't trust linter, statement not always true. + { + // 2011-01-02: Marshal as character array because the cast + // result = (char)Marshal.ReadInt16(op); throws an OverflowException + // on negative numbers with Check Overflow option set on the project + Char[] buff = new Char[1]; + Marshal.Copy(op, buff, 0, 1); + result = buff[0]; + } + else // UCS4 + { + // XXX this is probably NOT correct? + result = (char)Marshal.ReadInt32(op); + } return true; } goto type_error; From 587f318136427b9174820fec8418f3ae4f9dcfae Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Feb 2017 17:06:20 -0700 Subject: [PATCH 080/245] Add IsPython2 and IsPython3 --- src/runtime/converter.cs | 20 ++++++++------------ src/runtime/exceptions.cs | 14 +++++--------- src/runtime/importhook.cs | 20 +++++++++++++------- src/runtime/runtime.cs | 24 +++++++++++++++++------- 4 files changed, 43 insertions(+), 35 deletions(-) diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index f7cbf27be..392e02ae8 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -82,14 +82,14 @@ internal static IntPtr GetPythonTypeByAlias(Type op) { return Runtime.PyUnicodeType; } -#if PYTHON3 - else if ((op == int16Type) || - (op == int32Type) || - (op == int64Type)) + + else if (Runtime.IsPython3 && ((op == int16Type) || + (op == int32Type) || + (op == int64Type))) { return Runtime.PyIntType; } -#endif + else if ((op == int16Type) || (op == int32Type)) { @@ -435,9 +435,8 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setEr return true; case TypeCode.Int32: -#if PYTHON2 // Trickery to support 64-bit platforms. - - if (Runtime.Is32Bit) + // Trickery to support 64-bit platforms. + if (Runtime.IsPython2 && Runtime.Is32Bit) { op = Runtime.PyNumber_Int(value); @@ -461,11 +460,8 @@ static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setEr result = ival; return true; } - else + else // Python3 always use PyLong API { -#elif PYTHON3 // When using Python3 always use the PyLong API - { -#endif op = Runtime.PyNumber_Long(value); if (op == IntPtr.Zero) { diff --git a/src/runtime/exceptions.cs b/src/runtime/exceptions.cs index dbdd9a67b..01a8ab585 100644 --- a/src/runtime/exceptions.cs +++ b/src/runtime/exceptions.cs @@ -81,17 +81,14 @@ private Exceptions() /// internal static void Initialize() { -#if PYTHON3 - exceptions_module = Runtime.PyImport_ImportModule("builtins"); -#elif PYTHON2 - exceptions_module = Runtime.PyImport_ImportModule("exceptions"); -#endif + string exceptionsModuleName = Runtime.IsPython3 ? "builtins" : "exceptions"; + exceptions_module = Runtime.PyImport_ImportModule(exceptionsModuleName); + Exceptions.ErrorCheck(exceptions_module); warnings_module = Runtime.PyImport_ImportModule("warnings"); Exceptions.ErrorCheck(warnings_module); Type type = typeof(Exceptions); - foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | - BindingFlags.Static)) + foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { IntPtr op = Runtime.PyObject_GetAttrString(exceptions_module, fi.Name); if (op != IntPtr.Zero) @@ -116,8 +113,7 @@ internal static void Shutdown() if (Runtime.Py_IsInitialized() != 0) { Type type = typeof(Exceptions); - foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | - BindingFlags.Static)) + foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { var op = (IntPtr)fi.GetValue(type); if (op != IntPtr.Zero) diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index df3877c29..bb70a6167 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -35,11 +35,11 @@ internal static void Initialize() // but it provides the most "Pythonic" way of dealing with CLR // modules (Python doesn't provide a way to emulate packages). IntPtr dict = Runtime.PyImport_GetModuleDict(); -#if PYTHON3 - IntPtr mod = Runtime.PyImport_ImportModule("builtins"); -#elif PYTHON2 - IntPtr mod = Runtime.PyDict_GetItemString(dict, "__builtin__"); -#endif + + IntPtr mod = Runtime.IsPython3 + ? Runtime.PyImport_ImportModule("builtins") + : Runtime.PyDict_GetItemString(dict, "__builtin__"); + py_import = Runtime.PyObject_GetAttrString(mod, "__import__"); hook = new MethodWrapper(typeof(ImportHook), "__import__", "TernaryFunc"); Runtime.PyObject_SetAttrString(mod, "__import__", hook.ptr); @@ -86,7 +86,14 @@ internal static void Shutdown() public static IntPtr GetCLRModule(IntPtr? fromList = null) { root.InitializePreload(); -#if PYTHON3 + + if (Runtime.IsPython2) + { + Runtime.XIncref(py_clr_module); + return py_clr_module; + } + + // Python 3 // update the module dictionary with the contents of the root dictionary root.LoadNames(); IntPtr py_mod_dict = Runtime.PyModule_GetDict(py_clr_module); @@ -135,7 +142,6 @@ public static IntPtr GetCLRModule(IntPtr? fromList = null) } } } -#endif Runtime.XIncref(py_clr_module); return py_clr_module; } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 509192c26..c6f3551df 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -171,6 +171,8 @@ public class Runtime internal static bool IsFinalizing = false; internal static bool Is32Bit; + internal static bool IsPython2; + internal static bool IsPython3; /// /// Initialize the runtime... @@ -178,6 +180,8 @@ public class Runtime internal static void Initialize() { Is32Bit = IntPtr.Size == 4; + IsPython2 = pyversionnumber < 30; + IsPython3 = pyversionnumber >= 30; if (Runtime.Py_IsInitialized() == 0) { @@ -189,13 +193,19 @@ internal static void Initialize() Runtime.PyEval_InitThreads(); } -#if PYTHON3 - IntPtr op = Runtime.PyImport_ImportModule("builtins"); - IntPtr dict = Runtime.PyObject_GetAttrString(op, "__dict__"); -#elif PYTHON2 - IntPtr dict = Runtime.PyImport_GetModuleDict(); - IntPtr op = Runtime.PyDict_GetItemString(dict, "__builtin__"); -#endif + IntPtr op; + IntPtr dict; + if (IsPython3) + { + op = Runtime.PyImport_ImportModule("builtins"); + dict = Runtime.PyObject_GetAttrString(op, "__dict__"); + + } + else // Python2 + { + dict = Runtime.PyImport_GetModuleDict(); + op = Runtime.PyDict_GetItemString(dict, "__builtin__"); + } PyNotImplemented = Runtime.PyObject_GetAttrString(op, "NotImplemented"); PyBaseObjectType = Runtime.PyObject_GetAttrString(op, "object"); From b9815e4d300e3993e9d3e325599c6995fc44d748 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 4 Feb 2017 12:03:37 -0700 Subject: [PATCH 081/245] Cleanup runtime config --- Python.Runtime.dll.config | 30 ++++++++++++++---------------- src/clrmodule/packages.config | 1 - 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/Python.Runtime.dll.config b/Python.Runtime.dll.config index 228c1417a..8591f58fe 100644 --- a/Python.Runtime.dll.config +++ b/Python.Runtime.dll.config @@ -1,22 +1,20 @@ - - + - - - + + + + - - - + + + + + diff --git a/src/clrmodule/packages.config b/src/clrmodule/packages.config index 01dd53f14..2a95dc54d 100644 --- a/src/clrmodule/packages.config +++ b/src/clrmodule/packages.config @@ -1,5 +1,4 @@ - From 5844beeb2967a289983bad3de8e7288ae9587883 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 4 Feb 2017 12:10:27 -0700 Subject: [PATCH 082/245] Remove extra properties/Organize properties --- src/clrmodule/clrmodule.csproj | 30 ++++---------- src/console/Console.csproj | 37 ++++------------- src/console/app.config | 7 ---- src/embed_tests/Python.EmbeddingTest.csproj | 30 +++----------- src/runtime/Python.Runtime.csproj | 46 ++++----------------- src/testing/Python.Test.csproj | 29 +++---------- 6 files changed, 35 insertions(+), 144 deletions(-) delete mode 100644 src/console/app.config diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index c3d6ec7dc..aca9e46cf 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -1,23 +1,24 @@ - + Debug - x86 - 8.0.30703 - 2.0 + AnyCPU {86E834DE-1139-4511-96CC-69636A56E7AC} Library - clrmodule clrmodule + clrmodule + bin\clrmodule.xml + bin\ v4.0 - 512 + + 1591 ..\..\ $(SolutionDir) + true true - bin\ TRACE;DEBUG;PYTHON2 full x86 @@ -25,14 +26,12 @@ true - bin\ TRACE;DEBUG;PYTHON2 full x64 prompt - bin\ PYTHON2 true pdbonly @@ -40,7 +39,6 @@ prompt - bin\ PYTHON2 true pdbonly @@ -49,7 +47,6 @@ true - bin\ TRACE;DEBUG;PYTHON2 full x86 @@ -57,14 +54,12 @@ true - bin\ TRACE;DEBUG;PYTHON2 full x64 prompt - bin\ PYTHON2 true pdbonly @@ -72,7 +67,6 @@ prompt - bin\ PYTHON2 true pdbonly @@ -81,7 +75,6 @@ true - bin\ TRACE;DEBUG;PYTHON3 full x86 @@ -89,14 +82,12 @@ true - bin\ TRACE;DEBUG;PYTHON3 full x64 prompt - bin\ PYTHON3 true pdbonly @@ -104,7 +95,6 @@ prompt - bin\ PYTHON3 true pdbonly @@ -113,7 +103,6 @@ true - bin\ TRACE;DEBUG;PYTHON3 full x86 @@ -121,14 +110,12 @@ true - bin\ TRACE;DEBUG;PYTHON3 full x64 prompt - bin\ PYTHON3 true pdbonly @@ -136,7 +123,6 @@ prompt - bin\ PYTHON3 true pdbonly diff --git a/src/console/Console.csproj b/src/console/Console.csproj index ed591af21..fa6878246 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -5,19 +5,20 @@ AnyCPU {E29DCF0A-5114-4A98-B1DD-71264B6EA349} Exe - false nPython Python.Runtime - OnBuildSuccess - python-clear.ico - 10.0.0 - 2.0 + bin\nPython.xml + bin\ + v4.0 + + 1591 ..\..\ $(SolutionDir) + + python-clear.ico true - bin\ DEBUG;TRACE full x86 @@ -25,14 +26,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -41,7 +40,6 @@ prompt - bin\ true @@ -51,7 +49,6 @@ true - bin\ DEBUG;TRACE full x86 @@ -59,14 +56,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -75,7 +70,6 @@ prompt - bin\ true @@ -85,7 +79,6 @@ true - bin\ DEBUG;TRACE full x86 @@ -93,14 +86,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -109,7 +100,6 @@ prompt - bin\ true @@ -119,7 +109,6 @@ true - bin\ DEBUG;TRACE full x86 @@ -127,14 +116,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -143,7 +130,6 @@ prompt - bin\ true @@ -156,9 +142,6 @@ - - 3.5 - @@ -170,9 +153,6 @@ Python.Runtime.dll - - - {097b4ac0-74e9-4c58-bcf8-c69746ec8271} @@ -180,9 +160,6 @@ - - - diff --git a/src/console/app.config b/src/console/app.config deleted file mode 100644 index e7368c65b..000000000 --- a/src/console/app.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index c9586cf4a..a274177f8 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -5,17 +5,20 @@ AnyCPU {4165C59D-2822-499F-A6DB-EACA4C331EB5} Library - false Python.EmbeddingTest Python.EmbeddingTest - OnBuildSuccess + bin\Python.EmbeddingTest.xml + bin\ + v4.0 + + 1591 ..\..\ $(SolutionDir) + true true - bin\ DEBUG;TRACE full x86 @@ -23,14 +26,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -39,7 +40,6 @@ prompt - bin\ true @@ -49,7 +49,6 @@ true - bin\ DEBUG;TRACE full x86 @@ -57,14 +56,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -73,7 +70,6 @@ prompt - bin\ true @@ -83,7 +79,6 @@ true - bin\ DEBUG;TRACE full x86 @@ -91,14 +86,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -107,7 +100,6 @@ prompt - bin\ true @@ -117,7 +109,6 @@ true - bin\ DEBUG;TRACE full x86 @@ -125,14 +116,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -141,7 +130,6 @@ prompt - bin\ true @@ -154,9 +142,6 @@ ..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll - - 3.5 - @@ -179,9 +164,6 @@ - - - $(TargetPath) $(TargetDir)$(TargetName).pdb diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index f630ab25d..9afa57f41 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -2,147 +2,122 @@ Debug - x86 + AnyCPU {097B4AC0-74E9-4C58-BCF8-C69746EC8271} Library - false Python.Runtime Python.Runtime + bin\Python.Runtime.xml + bin\ + v4.0 + + 1591 ..\..\ $(SolutionDir) + + true + true - bin\ PYTHON2;PYTHON27;UCS4 - true true pdbonly x86 - bin\ PYTHON2;PYTHON27;UCS4 - true true pdbonly x64 - bin\ PYTHON2;PYTHON27;UCS2 - true true pdbonly x86 - bin\ PYTHON2;PYTHON27;UCS2 - true true pdbonly x64 true - bin\ TRACE;DEBUG;PYTHON2;PYTHON27;UCS4 - true false full x86 true - bin\ TRACE;DEBUG;PYTHON2;PYTHON27;UCS4 - true false full x64 true - bin\ TRACE;DEBUG;PYTHON2;PYTHON27;UCS2 - true false full x86 true - bin\ TRACE;DEBUG;PYTHON2;PYTHON27;UCS2 - true false full x64 - bin\ PYTHON3;PYTHON36;UCS4 - true true pdbonly x86 - bin\ PYTHON3;PYTHON36;UCS4 - true true pdbonly x64 - bin\ PYTHON3;PYTHON36;UCS2 - true true pdbonly x86 - bin\ PYTHON3;PYTHON36;UCS2 - true true pdbonly x64 true - bin\ TRACE;DEBUG;PYTHON3;PYTHON36;UCS4 - true false full x86 true - bin\ TRACE;DEBUG;PYTHON3;PYTHON36;UCS4 - true false full x64 true - bin\ TRACE;DEBUG;PYTHON3;PYTHON36;UCS2 - true false full x86 true - bin\ TRACE;DEBUG;PYTHON3;PYTHON36;UCS2 - true false full x64 @@ -249,9 +224,6 @@ - - - $(TargetPath) $(TargetDir)$(TargetName).pdb diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index 3201cd635..1aa04ab30 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -5,18 +5,20 @@ AnyCPU {6F401A34-273B-450F-9A4C-13550BE0767B} Library - false Python.Test Python.Test - OnBuildSuccess + bin\Python.Test.xml + bin\ v4.0 + 1591 ..\..\ $(SolutionDir) + + true true - bin\ DEBUG;TRACE full x86 @@ -24,14 +26,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -40,7 +40,6 @@ prompt - bin\ true @@ -50,7 +49,6 @@ true - bin\ DEBUG;TRACE full x86 @@ -58,14 +56,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -74,7 +70,6 @@ prompt - bin\ true @@ -84,7 +79,6 @@ true - bin\ DEBUG;TRACE full x86 @@ -92,14 +86,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -108,7 +100,6 @@ prompt - bin\ true @@ -118,7 +109,6 @@ true - bin\ DEBUG;TRACE full x86 @@ -126,14 +116,12 @@ true - bin\ DEBUG;TRACE full x64 prompt - bin\ true @@ -142,7 +130,6 @@ prompt - bin\ true @@ -175,9 +162,6 @@ - - 3.5 - @@ -186,9 +170,6 @@ - - - $(SolutionDir) $(TargetPath) From 15cd373341c4ae849602df57293b8d07f34c9908 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 4 Feb 2017 13:40:20 -0700 Subject: [PATCH 083/245] Refactor property conditions --- src/clrmodule/clrmodule.csproj | 90 ++++--------------- src/console/Console.csproj | 98 ++++----------------- src/embed_tests/Python.EmbeddingTest.csproj | 98 ++++----------------- src/runtime/Python.Runtime.csproj | 76 +++------------- src/testing/Python.Test.csproj | 98 ++++----------------- 5 files changed, 75 insertions(+), 385 deletions(-) diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index aca9e46cf..9a9cf22f5 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -17,116 +17,58 @@ true - - true - TRACE;DEBUG;PYTHON2 - full + x86 - prompt - - true - TRACE;DEBUG;PYTHON2 - full + x64 - prompt - - PYTHON2 - true - pdbonly - x86 + + true + PYTHON2;TRACE;DEBUG + full prompt - + PYTHON2 true pdbonly - x64 prompt - + true - TRACE;DEBUG;PYTHON2 + PYTHON2;TRACE;DEBUG full - x86 prompt - - true - TRACE;DEBUG;PYTHON2 - full - x64 - prompt - - + PYTHON2 true pdbonly - x86 - prompt - - - PYTHON2 - true - pdbonly - x64 prompt - + true - TRACE;DEBUG;PYTHON3 + PYTHON3;TRACE;DEBUG full - x86 prompt - - true - TRACE;DEBUG;PYTHON3 - full - x64 - prompt - - + PYTHON3 true pdbonly - x86 - prompt - - - PYTHON3 - true - pdbonly - x64 prompt - + true - TRACE;DEBUG;PYTHON3 + PYTHON3;TRACE;DEBUG full - x86 prompt - - true - TRACE;DEBUG;PYTHON3 - full - x64 - prompt - - + PYTHON3 true pdbonly - x86 - prompt - - - PYTHON3 - true - pdbonly - x64 prompt diff --git a/src/console/Console.csproj b/src/console/Console.csproj index fa6878246..16e541c5c 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -17,124 +17,58 @@ python-clear.ico - - true - DEBUG;TRACE - full + x86 - prompt - + + x64 + + true DEBUG;TRACE full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt - + true DEBUG;TRACE full - x86 - prompt - - - true - DEBUG;TRACE - full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt - + true DEBUG;TRACE full - x86 - prompt - - - true - DEBUG;TRACE - full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt - + true DEBUG;TRACE full - x86 - prompt - - - true - DEBUG;TRACE - full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index a274177f8..7b3f80989 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -17,124 +17,58 @@ true - - true - DEBUG;TRACE - full + x86 - prompt - + + x64 + + true DEBUG;TRACE full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt - + true DEBUG;TRACE full - x86 - prompt - - - true - DEBUG;TRACE - full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt - + true DEBUG;TRACE full - x86 - prompt - - - true - DEBUG;TRACE - full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt - + true DEBUG;TRACE full - x86 - prompt - - - true - DEBUG;TRACE - full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 9afa57f41..65a1ef527 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -18,109 +18,55 @@ true true - - PYTHON2;PYTHON27;UCS4 - true - pdbonly + x86 - - PYTHON2;PYTHON27;UCS4 - true - pdbonly + x64 - - PYTHON2;PYTHON27;UCS2 + + PYTHON2;PYTHON27;UCS4 true pdbonly - x86 - + PYTHON2;PYTHON27;UCS2 true pdbonly - x64 - + true TRACE;DEBUG;PYTHON2;PYTHON27;UCS4 false full - x86 - - true - TRACE;DEBUG;PYTHON2;PYTHON27;UCS4 - false - full - x64 - - - true - TRACE;DEBUG;PYTHON2;PYTHON27;UCS2 - false - full - x86 - - + true TRACE;DEBUG;PYTHON2;PYTHON27;UCS2 false full - x64 - - - PYTHON3;PYTHON36;UCS4 - true - pdbonly - x86 - + PYTHON3;PYTHON36;UCS4 true pdbonly - x64 - + PYTHON3;PYTHON36;UCS2 true pdbonly - x86 - - PYTHON3;PYTHON36;UCS2 - true - pdbonly - x64 - - + true TRACE;DEBUG;PYTHON3;PYTHON36;UCS4 false full - x86 - - true - TRACE;DEBUG;PYTHON3;PYTHON36;UCS4 - false - full - x64 - - - true - TRACE;DEBUG;PYTHON3;PYTHON36;UCS2 - false - full - x86 - - + true TRACE;DEBUG;PYTHON3;PYTHON36;UCS2 false full - x64 diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index 1aa04ab30..0a5f94e8c 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -17,124 +17,58 @@ true - - true - DEBUG;TRACE - full + x86 - prompt - + + x64 + + true DEBUG;TRACE full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt - + true DEBUG;TRACE full - x86 - prompt - - - true - DEBUG;TRACE - full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt - + true DEBUG;TRACE full - x86 - prompt - - - true - DEBUG;TRACE - full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt - + true DEBUG;TRACE full - x86 - prompt - - - true - DEBUG;TRACE - full - x64 prompt - - - + + true pdbonly - x86 - prompt - - - - - true - pdbonly - x64 prompt From 24c61e6c9d96b154d1c3e45388ea0fd66b557e28 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 4 Feb 2017 14:09:18 -0700 Subject: [PATCH 084/245] Order Runtime.csproj configuration To make it easier to verify everything is setup correctly Simplified the Mono.Unix include condition --- src/clrmodule/clrmodule.csproj | 9 +---- src/console/Console.csproj | 9 +---- src/embed_tests/Python.EmbeddingTest.csproj | 9 +---- src/runtime/Python.Runtime.csproj | 44 ++++++++------------- src/testing/Python.Test.csproj | 9 +---- 5 files changed, 20 insertions(+), 60 deletions(-) diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index 9a9cf22f5..435630d0e 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -16,6 +16,7 @@ $(SolutionDir) true + prompt x86 @@ -27,49 +28,41 @@ true PYTHON2;TRACE;DEBUG full - prompt PYTHON2 true pdbonly - prompt true PYTHON2;TRACE;DEBUG full - prompt PYTHON2 true pdbonly - prompt true PYTHON3;TRACE;DEBUG full - prompt PYTHON3 true pdbonly - prompt true PYTHON3;TRACE;DEBUG full - prompt PYTHON3 true pdbonly - prompt diff --git a/src/console/Console.csproj b/src/console/Console.csproj index 16e541c5c..cdee6893b 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -16,6 +16,7 @@ $(SolutionDir) python-clear.ico + prompt x86 @@ -27,49 +28,41 @@ true DEBUG;TRACE full - prompt true pdbonly - prompt true DEBUG;TRACE full - prompt true pdbonly - prompt true DEBUG;TRACE full - prompt true pdbonly - prompt true DEBUG;TRACE full - prompt true pdbonly - prompt $(PythonManifest) diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 7b3f80989..743c9dabe 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -16,6 +16,7 @@ $(SolutionDir) true + prompt x86 @@ -27,49 +28,41 @@ true DEBUG;TRACE full - prompt true pdbonly - prompt true DEBUG;TRACE full - prompt true pdbonly - prompt true DEBUG;TRACE full - prompt true pdbonly - prompt true DEBUG;TRACE full - prompt true pdbonly - prompt diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 65a1ef527..977721708 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -29,25 +29,25 @@ true pdbonly - - PYTHON2;PYTHON27;UCS2 + + PYTHON3;PYTHON36;UCS4 true pdbonly true - TRACE;DEBUG;PYTHON2;PYTHON27;UCS4 + PYTHON2;PYTHON27;UCS4;TRACE;DEBUG false full - + true - TRACE;DEBUG;PYTHON2;PYTHON27;UCS2 + PYTHON3;PYTHON36;UCS4;TRACE;DEBUG false full - - PYTHON3;PYTHON36;UCS4 + + PYTHON2;PYTHON27;UCS2 true pdbonly @@ -56,36 +56,24 @@ true pdbonly - + true - TRACE;DEBUG;PYTHON3;PYTHON36;UCS4 + PYTHON2;PYTHON27;UCS2;TRACE;DEBUG false full true - TRACE;DEBUG;PYTHON3;PYTHON36;UCS2 + PYTHON3;PYTHON36;UCS2;TRACE;DEBUG false full - - - - - False - ..\..\packages\MonoGAC\Mono.Posix\4.0.0.0__0738eb9f132ed756\Mono.Posix.dll - - - - - - - False - ..\..\packages\MonoGAC\Mono.Posix\4.0.0.0__0738eb9f132ed756\Mono.Posix.dll - - - - + + + False + ..\..\packages\MonoGAC\Mono.Posix\4.0.0.0__0738eb9f132ed756\Mono.Posix.dll + + diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index 0a5f94e8c..5faca36b2 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -16,6 +16,7 @@ $(SolutionDir) true + prompt x86 @@ -27,49 +28,41 @@ true DEBUG;TRACE full - prompt true pdbonly - prompt true DEBUG;TRACE full - prompt true pdbonly - prompt true DEBUG;TRACE full - prompt true pdbonly - prompt true DEBUG;TRACE full - prompt true pdbonly - prompt From 01fe9798dee23370f7dd622d63cbaf2800cc2965 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 4 Feb 2017 21:13:31 -0700 Subject: [PATCH 085/245] Add pylong lost unit test Wasn't being referenced in the project --- src/embed_tests/Python.EmbeddingTest.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 743c9dabe..48fe2554e 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -78,6 +78,7 @@ + From 2e5fab62722e8292d43a7ff9653cb751be9d4a9b Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 5 Feb 2017 18:01:33 -0700 Subject: [PATCH 086/245] Replace #if DEBUG with conditional attribute --- src/clrmodule/ClrModule.cs | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/clrmodule/ClrModule.cs b/src/clrmodule/ClrModule.cs index eca411b30..9e55f0b31 100644 --- a/src/clrmodule/ClrModule.cs +++ b/src/clrmodule/ClrModule.cs @@ -21,6 +21,7 @@ // calls are made to indicate what's going on during the load... //============================================================================ using System; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; @@ -37,9 +38,7 @@ public static IntPtr PyInit_clr() public static void initclr() #endif { -#if DEBUG - Console.WriteLine("Attempting to load Python.Runtime using standard binding rules... "); -#endif + debugPrint("Attempting to load 'Python.Runtime' using standard binding rules."); #if USE_PYTHON_RUNTIME_PUBLIC_KEY_TOKEN var pythonRuntimePublicKeyTokenData = new byte[] { 0x50, 0x00, 0xfe, 0xa6, 0xcb, 0xa7, 0x02, 0xdd }; #endif @@ -65,12 +64,11 @@ public static void initclr() try { pythonRuntime = Assembly.Load(pythonRuntimeName); -#if DEBUG - Console.WriteLine("Success!"); -#endif + debugPrint("Success loading 'Python.Runtime' using standard binding rules."); } catch (IOException) { + debugPrint("'Python.Runtime' not found using standard binding rules."); try { // If the above fails for any reason, we fallback to attempting to load "Python.Runtime.dll" @@ -89,16 +87,13 @@ public static void initclr() throw new InvalidOperationException(executingAssembly.Location); } string pythonRuntimeDllPath = Path.Combine(assemblyDirectory, "Python.Runtime.dll"); -#if DEBUG - Console.WriteLine("Attempting to load Python.Runtime from: '{0}'...", pythonRuntimeDllPath); -#endif + debugPrint($"Attempting to load Python.Runtime from: '{pythonRuntimeDllPath}.'"); pythonRuntime = Assembly.LoadFrom(pythonRuntimeDllPath); + debugPrint($"Success loading 'Python.Runtime' from: '{pythonRuntimeDllPath}'."); } catch (InvalidOperationException) { -#if DEBUG - Console.WriteLine("Could not load Python.Runtime"); -#endif + debugPrint("Could not load 'Python.Runtime'."); #if PYTHON3 return IntPtr.Zero; #elif PYTHON2 @@ -117,4 +112,14 @@ public static void initclr() pythonEngineType.InvokeMember("InitExt", BindingFlags.InvokeMethod, null, null, null); #endif } + + /// + /// Substitute for Debug.Writeline(...). Ideally we would use Debug.Writeline + /// but haven't been able to configure the TRACE from within Python. + /// + [Conditional("DEBUG")] + private static void debugPrint(string str) + { + Console.WriteLine(str); + } } From 56aee3503700773479eaf4ebaccc4abfd714e0f9 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 5 Feb 2017 19:44:22 -0700 Subject: [PATCH 087/245] Fix and disable StrongNameSigning It works better if they key is in the right folder and its being referenced when signing. It breaks InternalsVisibleTo though, disabling till have time to look into it. (not that it was actually enabled) --- setup.py | 4 ++-- pythonnet.snk => src/pythonnet.snk | Bin src/runtime/Python.Runtime.csproj | 3 ++- src/testing/Python.Test.csproj | 3 ++- 4 files changed, 6 insertions(+), 4 deletions(-) rename pythonnet.snk => src/pythonnet.snk (100%) diff --git a/setup.py b/setup.py index 3ef19afd7..dc72f3794 100644 --- a/setup.py +++ b/setup.py @@ -104,12 +104,12 @@ def _get_interop_filename(): def _get_source_files(): """Walk project and collect the files needed for ext_module""" - for ext in (".sln", ".snk", ".config"): + for ext in (".sln", ".config"): for path in glob.glob("*" + ext): yield path for root, dirnames, filenames in os.walk("src"): - for ext in (".cs", ".csproj", ".sln", ".snk", ".config", ".il", + for ext in (".cs", ".csproj", ".snk", ".config", ".il", ".py", ".c", ".h", ".ico"): for filename in fnmatch.filter(filenames, "*" + ext): yield os.path.join(root, filename) diff --git a/pythonnet.snk b/src/pythonnet.snk similarity index 100% rename from pythonnet.snk rename to src/pythonnet.snk diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 977721708..86b6c0ca9 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -16,7 +16,8 @@ $(SolutionDir) true - true + false + ..\pythonnet.snk x86 diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index 5faca36b2..4b9d4e80c 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -15,7 +15,8 @@ ..\..\ $(SolutionDir) - true + false + ..\pythonnet.snk prompt From 4fe44c4873a6d37c434498f8ec1f0bfef17f59aa Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 6 Feb 2017 11:02:01 -0700 Subject: [PATCH 088/245] Fix debug statement & rename debugprint --- src/clrmodule/ClrModule.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/clrmodule/ClrModule.cs b/src/clrmodule/ClrModule.cs index 9e55f0b31..413b952eb 100644 --- a/src/clrmodule/ClrModule.cs +++ b/src/clrmodule/ClrModule.cs @@ -38,7 +38,7 @@ public static IntPtr PyInit_clr() public static void initclr() #endif { - debugPrint("Attempting to load 'Python.Runtime' using standard binding rules."); + DebugPrint("Attempting to load 'Python.Runtime' using standard binding rules."); #if USE_PYTHON_RUNTIME_PUBLIC_KEY_TOKEN var pythonRuntimePublicKeyTokenData = new byte[] { 0x50, 0x00, 0xfe, 0xa6, 0xcb, 0xa7, 0x02, 0xdd }; #endif @@ -64,11 +64,11 @@ public static void initclr() try { pythonRuntime = Assembly.Load(pythonRuntimeName); - debugPrint("Success loading 'Python.Runtime' using standard binding rules."); + DebugPrint("Success loading 'Python.Runtime' using standard binding rules."); } catch (IOException) { - debugPrint("'Python.Runtime' not found using standard binding rules."); + DebugPrint("'Python.Runtime' not found using standard binding rules."); try { // If the above fails for any reason, we fallback to attempting to load "Python.Runtime.dll" @@ -87,13 +87,13 @@ public static void initclr() throw new InvalidOperationException(executingAssembly.Location); } string pythonRuntimeDllPath = Path.Combine(assemblyDirectory, "Python.Runtime.dll"); - debugPrint($"Attempting to load Python.Runtime from: '{pythonRuntimeDllPath}.'"); + DebugPrint($"Attempting to load Python.Runtime from: '{pythonRuntimeDllPath}'."); pythonRuntime = Assembly.LoadFrom(pythonRuntimeDllPath); - debugPrint($"Success loading 'Python.Runtime' from: '{pythonRuntimeDllPath}'."); + DebugPrint($"Success loading 'Python.Runtime' from: '{pythonRuntimeDllPath}'."); } catch (InvalidOperationException) { - debugPrint("Could not load 'Python.Runtime'."); + DebugPrint("Could not load 'Python.Runtime'."); #if PYTHON3 return IntPtr.Zero; #elif PYTHON2 @@ -118,7 +118,7 @@ public static void initclr() /// but haven't been able to configure the TRACE from within Python. /// [Conditional("DEBUG")] - private static void debugPrint(string str) + private static void DebugPrint(string str) { Console.WriteLine(str); } From a1b913676dc759640a6d80fa935b12105e828584 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 6 Feb 2017 11:05:23 -0700 Subject: [PATCH 089/245] Document nPython/Console usage Closes #358 --- src/console/pythonconsole.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/console/pythonconsole.cs b/src/console/pythonconsole.cs index a696f62f6..c1c960290 100644 --- a/src/console/pythonconsole.cs +++ b/src/console/pythonconsole.cs @@ -5,6 +5,14 @@ namespace Python.Runtime { + /// + /// Example of Embedding Python inside of a .NET program. + /// + /// + /// It has similar functionality to doing `import clr` from within Python, but this does it + /// the other way around; That is, it loads Python inside of .NET program. + /// See https://github.com/pythonnet/pythonnet/issues/358 for more info. + /// public sealed class PythonConsole { private static AssemblyLoader assemblyLoader = new AssemblyLoader(); @@ -41,7 +49,7 @@ public AssemblyLoader() AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { string shortName = args.Name.Split(',')[0]; - string resourceName = string.Format("{0}.dll", shortName); + string resourceName = $"{shortName}.dll"; if (loadedAssemblies.ContainsKey(resourceName)) { @@ -60,7 +68,6 @@ public AssemblyLoader() return assembly; } } - return null; }; } From 4f71a94945fc5642bb66533c090f668210212835 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 6 Feb 2017 11:07:58 -0700 Subject: [PATCH 090/245] Quiet Test Fixture build warnings about unused events. They will be used (or attempted to be used) from Python. --- src/testing/Python.Test.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index 4b9d4e80c..be6148f65 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -11,7 +11,7 @@ bin\ v4.0 - 1591 + 1591,0067 ..\..\ $(SolutionDir) From 50e7915fb0dd793f364d3002fcc29d0c2138d9c9 Mon Sep 17 00:00:00 2001 From: dse Date: Sat, 7 Jan 2017 13:36:27 +0400 Subject: [PATCH 091/245] Mono dependency removed from Linux build. --- src/runtime/monosupport.cs | 44 -------------------------------------- src/runtime/runtime.cs | 30 ++++++++++++++++++++------ 2 files changed, 24 insertions(+), 50 deletions(-) delete mode 100644 src/runtime/monosupport.cs diff --git a/src/runtime/monosupport.cs b/src/runtime/monosupport.cs deleted file mode 100644 index fc39f9065..000000000 --- a/src/runtime/monosupport.cs +++ /dev/null @@ -1,44 +0,0 @@ -#if UCS4 -using System; -using System.Runtime.InteropServices; -using System.Text; -using Mono.Unix; - -namespace Python.Runtime -{ - public class Utf32Marshaler : ICustomMarshaler - { - private static Utf32Marshaler instance = new Utf32Marshaler(); - - public static ICustomMarshaler GetInstance(string s) - { - return instance; - } - - public void CleanUpManagedData(object o) - { - } - - public void CleanUpNativeData(IntPtr pNativeData) - { - UnixMarshal.FreeHeap(pNativeData); - } - - public int GetNativeDataSize() - { - return IntPtr.Size; - } - - public IntPtr MarshalManagedToNative(object obj) - { - var s = obj as string; - return s == null ? IntPtr.Zero : UnixMarshal.StringToHeap(s, Encoding.UTF32); - } - - public object MarshalNativeToManaged(IntPtr pNativeData) - { - return UnixMarshal.PtrToString(pNativeData, Encoding.UTF32); - } - } -} -#endif diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index c6f3551df..b5ac02031 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -3,10 +3,6 @@ using System.Security; using System.Text; -#if UCS4 -using Mono.Unix; -#endif - namespace Python.Runtime { [SuppressUnmanagedCodeSecurity()] @@ -1656,10 +1652,32 @@ internal unsafe static extern IntPtr ExactSpelling = true)] internal unsafe static extern IntPtr PyUnicode_FromKindAndString(int kind, - [MarshalAs(UnmanagedType.CustomMarshaler, - MarshalTypeRef = typeof(Utf32Marshaler))] string s, + IntPtr s, int size); + internal static unsafe IntPtr PyUnicode_FromKindAndString(int kind, + string s, + int size) + { + var bufLength = Math.Max(s.Length, size) * 4; + + IntPtr mem = Marshal.AllocHGlobal(bufLength); + try + { + fixed (char* ps = s) + { + Encoding.UTF32.GetBytes(ps, s.Length, (byte*)mem, bufLength); + } + + var result = PyUnicode_FromKindAndString(kind, mem, bufLength); + return result; + } + finally + { + Marshal.FreeHGlobal(mem); + } + } + internal static IntPtr PyUnicode_FromUnicode(string s, int size) { return PyUnicode_FromKindAndString(4, s, size); From 198f6545f5ed4c718fb818679df220e049751f84 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 5 Feb 2017 11:37:37 -0700 Subject: [PATCH 092/245] Remove mono dependency from PY2 as well. --- src/runtime/Python.Runtime.csproj | 1 - src/runtime/runtime.cs | 25 ++++++++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 86b6c0ca9..01cbcb35f 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -116,7 +116,6 @@ - diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index b5ac02031..25a1ea6c1 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1720,9 +1720,28 @@ internal unsafe static extern IntPtr EntryPoint = "PyUnicodeUCS4_FromUnicode", ExactSpelling = true)] internal unsafe static extern IntPtr - PyUnicode_FromUnicode( - [MarshalAs(UnmanagedType.CustomMarshaler, - MarshalTypeRef = typeof(Utf32Marshaler))] string s, int size); + PyUnicode_FromUnicode(IntPtr s, int size); + + internal static unsafe IntPtr PyUnicode_FromUnicode(string s, int size) + { + var bufLength = Math.Max(s.Length, size) * 4; + + IntPtr mem = Marshal.AllocHGlobal(bufLength); + try + { + fixed (char* ps = s) + { + Encoding.UTF32.GetBytes(ps, s.Length, (byte*)mem, bufLength); + } + + var result = PyUnicode_FromUnicode(mem, bufLength); + return result; + } + finally + { + Marshal.FreeHGlobal(mem); + } + } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS4_GetSize", From d2ba88a10b2a747fc36b502c3a75478909d38df7 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 6 Feb 2017 11:30:25 -0700 Subject: [PATCH 093/245] Replace bufLength with size --- src/runtime/runtime.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 25a1ea6c1..a4bb60815 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1669,7 +1669,7 @@ internal static unsafe IntPtr PyUnicode_FromKindAndString(int kind, Encoding.UTF32.GetBytes(ps, s.Length, (byte*)mem, bufLength); } - var result = PyUnicode_FromKindAndString(kind, mem, bufLength); + var result = PyUnicode_FromKindAndString(kind, mem, size); return result; } finally @@ -1734,7 +1734,7 @@ internal static unsafe IntPtr PyUnicode_FromUnicode(string s, int size) Encoding.UTF32.GetBytes(ps, s.Length, (byte*)mem, bufLength); } - var result = PyUnicode_FromUnicode(mem, bufLength); + var result = PyUnicode_FromUnicode(mem, size); return result; } finally From 77c7eb60dab88d399de3deb80cf5d7f5bae442ce Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 6 Feb 2017 00:32:37 -0700 Subject: [PATCH 094/245] Remove arch .il files --- setup.py | 2 +- src/runtime/Python.Runtime.csproj | 2 -- src/runtime/x64/clrmodule-platform.il | 3 --- src/runtime/x86/clrmodule-platform.il | 3 --- 4 files changed, 1 insertion(+), 9 deletions(-) delete mode 100644 src/runtime/x64/clrmodule-platform.il delete mode 100644 src/runtime/x86/clrmodule-platform.il diff --git a/setup.py b/setup.py index dc72f3794..a7c2910ac 100644 --- a/setup.py +++ b/setup.py @@ -109,7 +109,7 @@ def _get_source_files(): yield path for root, dirnames, filenames in os.walk("src"): - for ext in (".cs", ".csproj", ".snk", ".config", ".il", + for ext in (".cs", ".csproj", ".snk", ".config", ".py", ".c", ".h", ".ico"): for filename in fnmatch.filter(filenames, "*" + ext): yield os.path.join(root, filename) diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 01cbcb35f..8ccab4988 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -149,8 +149,6 @@ - - diff --git a/src/runtime/x64/clrmodule-platform.il b/src/runtime/x64/clrmodule-platform.il deleted file mode 100644 index bb188df52..000000000 --- a/src/runtime/x64/clrmodule-platform.il +++ /dev/null @@ -1,3 +0,0 @@ - -.vtfixup [1] int64 fromunmanaged at VT_01 -.data VT_01 = int64(0) diff --git a/src/runtime/x86/clrmodule-platform.il b/src/runtime/x86/clrmodule-platform.il deleted file mode 100644 index f4855c5e2..000000000 --- a/src/runtime/x86/clrmodule-platform.il +++ /dev/null @@ -1,3 +0,0 @@ - -.vtfixup [1] int32 fromunmanaged at VT_01 -.data VT_01 = int32(0) From f9d913ed1526b10418bbc37e629e3bb8d413e6bf Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 6 Feb 2017 12:19:15 -0700 Subject: [PATCH 095/245] Update CHANGELOG --- CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36f3ecfeb..05b8126ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Refactored `setup.py` (#337) - Upgraded NUnit framework to 2.6.4 (#353) - Completed refactor of Build Directives on `Runtime.cs` (#339) -- Refactor tests and removed dependency on `six` (#329) +- Refactor python unittests (#329) - Unfroze Mono version on Travis (#345) - Enabled Embedded tests on Appveyor (#353) @@ -27,6 +27,11 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Fixed crash during Shutdown (#343) +### Removed + +- Removed `six` dependency for unittests (#329) +- Removed `Mono.Unix` dependency for `UCS4` (#360) + ## [2.2.2][] - 2017-01-29 ### Fixed From b4710fc8ac9bbfada9b37407682147ee43f91bdb Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 6 Feb 2017 16:13:32 -0700 Subject: [PATCH 096/245] Remove Mono.Unix reference from project Remove duplicate property in Python.Test --- src/runtime/Python.Runtime.csproj | 6 ------ src/testing/Python.Test.csproj | 1 - 2 files changed, 7 deletions(-) diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 8ccab4988..f1616dcd6 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -69,12 +69,6 @@ false full - - - False - ..\..\packages\MonoGAC\Mono.Posix\4.0.0.0__0738eb9f132ed756\Mono.Posix.dll - - diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index be6148f65..4ed9db680 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -99,7 +99,6 @@ - $(SolutionDir) $(TargetPath) $(TargetDir)$(TargetName).pdb From 049a61f5dc563d549541d78ac7d6d1ae53d3035b Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 12:50:39 -0700 Subject: [PATCH 097/245] Clean-up deprWarning --- src/runtime/assemblymanager.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/runtime/assemblymanager.cs b/src/runtime/assemblymanager.cs index 692351f11..60c02cea6 100644 --- a/src/runtime/assemblymanager.cs +++ b/src/runtime/assemblymanager.cs @@ -322,10 +322,10 @@ public static bool LoadImplicit(string name, bool warn = true) // Deprecation warning if (warn && loaded) { - string deprWarning = string.Format( - "\nThe module was found, but not in a referenced namespace.\n" + - "Implicit loading is deprecated. Please use clr.AddReference(\"{0}\").", - Path.GetFileNameWithoutExtension(lastAssembly.Location)); + string location = Path.GetFileNameWithoutExtension(lastAssembly.Location); + string deprWarning = $@" +The module was found, but not in a referenced namespace. +Implicit loading is deprecated. Please use clr.AddReference(""{location}"")."; Exceptions.deprecation(deprWarning); } From d1241f8afd54e05b565fa0c7353c2565309ea95c Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 13:04:21 -0700 Subject: [PATCH 098/245] Clean-up attribute names and paranthesis --- src/runtime/converter.cs | 2 +- src/runtime/interop.cs | 10 +++++----- src/runtime/moduleobject.cs | 20 ++++++++++---------- src/runtime/runtime.cs | 2 +- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 392e02ae8..97c08bce2 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -10,7 +10,7 @@ namespace Python.Runtime /// /// Performs data conversions between managed types and Python types. /// - [SuppressUnmanagedCodeSecurityAttribute()] + [SuppressUnmanagedCodeSecurity] internal class Converter { private Converter() diff --git a/src/runtime/interop.cs b/src/runtime/interop.cs index 148ca2d2c..dad5cb941 100644 --- a/src/runtime/interop.cs +++ b/src/runtime/interop.cs @@ -12,7 +12,7 @@ namespace Python.Runtime /// runtime. Generally, the definitions here need to be kept up to date /// when moving to new Python versions. /// - [Serializable()] + [Serializable] [AttributeUsage(AttributeTargets.All)] public class DocStringAttribute : Attribute { @@ -30,7 +30,7 @@ public string DocString private string docStr; } - [Serializable()] + [Serializable] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Delegate)] internal class PythonMethodAttribute : Attribute { @@ -39,7 +39,7 @@ public PythonMethodAttribute() } } - [Serializable()] + [Serializable] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Delegate)] internal class ModuleFunctionAttribute : Attribute { @@ -48,7 +48,7 @@ public ModuleFunctionAttribute() } } - [Serializable()] + [Serializable] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Delegate)] internal class ForbidPythonThreadsAttribute : Attribute { @@ -58,7 +58,7 @@ public ForbidPythonThreadsAttribute() } - [Serializable()] + [Serializable] [AttributeUsage(AttributeTargets.Property)] internal class ModulePropertyAttribute : Attribute { diff --git a/src/runtime/moduleobject.cs b/src/runtime/moduleobject.cs index c18a2cdf9..1d8581b1b 100644 --- a/src/runtime/moduleobject.cs +++ b/src/runtime/moduleobject.cs @@ -349,34 +349,34 @@ internal void InitializePreload() } } - [ModuleFunctionAttribute] + [ModuleFunction] public static bool getPreload() { return preload; } - [ModuleFunctionAttribute] + [ModuleFunction] public static void setPreload(bool preloadFlag) { preload = preloadFlag; } - //[ModulePropertyAttribute] + //[ModuleProperty] public static bool SuppressDocs { get { return _SuppressDocs; } set { _SuppressDocs = value; } } - //[ModulePropertyAttribute] + //[ModuleProperty] public static bool SuppressOverloads { get { return _SuppressOverloads; } set { _SuppressOverloads = value; } } - [ModuleFunctionAttribute] - [ForbidPythonThreadsAttribute] + [ModuleFunction] + [ForbidPythonThreads] public static Assembly AddReference(string name) { AssemblyManager.UpdatePath(); @@ -402,15 +402,15 @@ public static Assembly AddReference(string name) return assembly; } - [ModuleFunctionAttribute] - [ForbidPythonThreadsAttribute] + [ModuleFunction] + [ForbidPythonThreads] public static string FindAssembly(string name) { AssemblyManager.UpdatePath(); return AssemblyManager.FindAssembly(name); } - [ModuleFunctionAttribute] + [ModuleFunction] public static string[] ListAssemblies(bool verbose) { AssemblyName[] assnames = AssemblyManager.ListAssemblies(); @@ -429,7 +429,7 @@ public static string[] ListAssemblies(bool verbose) return names; } - [ModuleFunctionAttribute] + [ModuleFunction] public static int _AtExit() { return Runtime.AtExit(); diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index a4bb60815..0d122764f 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -5,7 +5,7 @@ namespace Python.Runtime { - [SuppressUnmanagedCodeSecurity()] + [SuppressUnmanagedCodeSecurity] static class NativeMethods { #if MONO_LINUX || MONO_OSX From 61536f35ed8dd14b39ff78b0430b1a95b891a651 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 13:56:16 -0700 Subject: [PATCH 099/245] Use explicit accessors --- src/console/pythonconsole.cs | 5 +++-- src/embed_tests/pylong.cs | 2 +- src/runtime/assemblymanager.cs | 12 ++++++------ src/runtime/classmanager.cs | 4 ++-- src/runtime/codegenerator.cs | 4 ++-- src/runtime/constructorbinding.cs | 18 +++++++++--------- src/runtime/converter.cs | 30 +++++++++++++++--------------- src/runtime/delegatemanager.cs | 15 ++++++++------- src/runtime/delegateobject.cs | 2 +- src/runtime/eventbinding.cs | 4 ++-- src/runtime/exceptions.cs | 4 ++-- src/runtime/fieldobject.cs | 2 +- src/runtime/genericutil.cs | 2 +- src/runtime/importhook.cs | 14 +++++++------- src/runtime/interfaceobject.cs | 2 +- src/runtime/interop.cs | 4 ++-- src/runtime/iterator.cs | 2 +- src/runtime/metatype.cs | 4 ++-- src/runtime/moduleobject.cs | 2 +- src/runtime/nativecall.cs | 4 ++-- src/runtime/overload.cs | 4 ++-- src/runtime/propertyobject.cs | 6 +++--- src/runtime/runtime.cs | 2 +- src/runtime/typemanager.cs | 4 ++-- src/testing/conversiontest.cs | 2 +- src/testing/propertytest.cs | 18 +++++++++--------- 26 files changed, 87 insertions(+), 85 deletions(-) diff --git a/src/console/pythonconsole.cs b/src/console/pythonconsole.cs index c1c960290..e9bb31e69 100644 --- a/src/console/pythonconsole.cs +++ b/src/console/pythonconsole.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Reflection; using Python.Runtime; @@ -40,7 +41,7 @@ public static int Main(string[] args) // (Python.Runtime.dll is included as a resource) private sealed class AssemblyLoader { - Dictionary loadedAssemblies; + private Dictionary loadedAssemblies; public AssemblyLoader() { @@ -57,7 +58,7 @@ public AssemblyLoader() } // looks for the assembly from the resources and load it - using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) + using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { if (stream != null) { diff --git a/src/embed_tests/pylong.cs b/src/embed_tests/pylong.cs index 1b5ffdb66..3a7365a61 100644 --- a/src/embed_tests/pylong.cs +++ b/src/embed_tests/pylong.cs @@ -27,7 +27,7 @@ public void TearDown() public void TestToInt64() { long largeNumber = 8L * 1024L * 1024L * 1024L; // 8 GB - PyLong pyLargeNumber = new PyLong(largeNumber); + var pyLargeNumber = new PyLong(largeNumber); Assert.AreEqual(largeNumber, pyLargeNumber.ToInt64()); } } diff --git a/src/runtime/assemblymanager.cs b/src/runtime/assemblymanager.cs index 60c02cea6..c86e7a473 100644 --- a/src/runtime/assemblymanager.cs +++ b/src/runtime/assemblymanager.cs @@ -17,16 +17,16 @@ internal class AssemblyManager { // modified from event handlers below, potentially triggered from different .NET threads // therefore this should be a ConcurrentDictionary - static ConcurrentDictionary> namespaces; - //static Dictionary> generics; - static AssemblyLoadEventHandler lhandler; - static ResolveEventHandler rhandler; + private static ConcurrentDictionary> namespaces; + //private static Dictionary> generics; + private static AssemblyLoadEventHandler lhandler; + private static ResolveEventHandler rhandler; // updated only under GIL? - static Dictionary probed; + private static Dictionary probed; // modified from event handlers below, potentially triggered from different .NET threads - static AssemblyList assemblies; + private static AssemblyList assemblies; internal static List pypath; private AssemblyManager() diff --git a/src/runtime/classmanager.cs b/src/runtime/classmanager.cs index 333f3e7ce..6a9d40ebd 100644 --- a/src/runtime/classmanager.cs +++ b/src/runtime/classmanager.cs @@ -17,8 +17,8 @@ namespace Python.Runtime /// internal class ClassManager { - static Dictionary cache; - static Type dtype; + private static Dictionary cache; + private static Type dtype; private ClassManager() { diff --git a/src/runtime/codegenerator.cs b/src/runtime/codegenerator.cs index 56bed758f..dc466bafb 100644 --- a/src/runtime/codegenerator.cs +++ b/src/runtime/codegenerator.cs @@ -13,8 +13,8 @@ namespace Python.Runtime /// internal class CodeGenerator { - AssemblyBuilder aBuilder; - ModuleBuilder mBuilder; + private AssemblyBuilder aBuilder; + private ModuleBuilder mBuilder; internal CodeGenerator() { diff --git a/src/runtime/constructorbinding.cs b/src/runtime/constructorbinding.cs index 295faaa7e..d17d6ac96 100644 --- a/src/runtime/constructorbinding.cs +++ b/src/runtime/constructorbinding.cs @@ -21,10 +21,10 @@ namespace Python.Runtime /// internal class ConstructorBinding : ExtensionType { - Type type; // The managed Type being wrapped in a ClassObject - IntPtr pyTypeHndl; // The python type tells GetInstHandle which Type to create. - ConstructorBinder ctorBinder; - IntPtr repr; + private Type type; // The managed Type being wrapped in a ClassObject + private IntPtr pyTypeHndl; // The python type tells GetInstHandle which Type to create. + private ConstructorBinder ctorBinder; + private IntPtr repr; public ConstructorBinding(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder) { @@ -165,11 +165,11 @@ public static IntPtr tp_repr(IntPtr ob) /// internal class BoundContructor : ExtensionType { - Type type; // The managed Type being wrapped in a ClassObject - IntPtr pyTypeHndl; // The python type tells GetInstHandle which Type to create. - ConstructorBinder ctorBinder; - ConstructorInfo ctorInfo; - IntPtr repr; + private Type type; // The managed Type being wrapped in a ClassObject + private IntPtr pyTypeHndl; // The python type tells GetInstHandle which Type to create. + private ConstructorBinder ctorBinder; + private ConstructorInfo ctorInfo; + private IntPtr repr; public BoundContructor(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinder, ConstructorInfo ci) { diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 97c08bce2..38fec1256 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -17,18 +17,18 @@ private Converter() { } - static NumberFormatInfo nfi; - static Type objectType; - static Type stringType; - static Type singleType; - static Type doubleType; - static Type decimalType; - static Type int16Type; - static Type int32Type; - static Type int64Type; - static Type flagsType; - static Type boolType; - static Type typeType; + private static NumberFormatInfo nfi; + private static Type objectType; + private static Type stringType; + private static Type singleType; + private static Type doubleType; + private static Type decimalType; + private static Type int16Type; + private static Type int32Type; + private static Type int64Type; + private static Type flagsType; + private static Type boolType; + private static Type typeType; static Converter() { @@ -415,7 +415,7 @@ internal static bool ToManagedValue(IntPtr value, Type obType, /// /// Convert a Python value to an instance of a primitive managed type. /// - static bool ToPrimitive(IntPtr value, Type obType, out Object result, bool setError) + private static bool ToPrimitive(IntPtr value, Type obType, out object result, bool setError) { IntPtr overflow = Exceptions.OverflowError; TypeCode tc = Type.GetTypeCode(obType); @@ -826,7 +826,7 @@ static void SetConversionError(IntPtr value, Type target) /// The Python value must support the Python sequence protocol and the /// items in the sequence must be convertible to the target array type. /// - static bool ToArray(IntPtr value, Type obType, out Object result, bool setError) + private static bool ToArray(IntPtr value, Type obType, out object result, bool setError) { Type elementType = obType.GetElementType(); int size = Runtime.PySequence_Size(value); @@ -875,7 +875,7 @@ static bool ToArray(IntPtr value, Type obType, out Object result, bool setError) /// /// Convert a Python value to a correctly typed managed enum instance. /// - static bool ToEnum(IntPtr value, Type obType, out Object result, bool setError) + private static bool ToEnum(IntPtr value, Type obType, out object result, bool setError) { Type etype = Enum.GetUnderlyingType(obType); result = null; diff --git a/src/runtime/delegatemanager.cs b/src/runtime/delegatemanager.cs index ce17a2e6e..df5eec427 100644 --- a/src/runtime/delegatemanager.cs +++ b/src/runtime/delegatemanager.cs @@ -11,13 +11,13 @@ namespace Python.Runtime /// internal class DelegateManager { - Hashtable cache; - Type basetype; - Type listtype; - Type voidtype; - Type typetype; - Type ptrtype; - CodeGenerator codeGenerator; + private Hashtable cache; + private Type basetype; + private Type listtype; + private Type voidtype; + private Type typetype; + private Type ptrtype; + private CodeGenerator codeGenerator; public DelegateManager() { @@ -180,6 +180,7 @@ A possible alternate strategy would be to create custom subclasses This would be slightly cleaner, but I'm not sure if delegates are too "special" for this to work. It would be more work, so for now the 80/20 rule applies :) */ + public class Dispatcher { public IntPtr target; diff --git a/src/runtime/delegateobject.cs b/src/runtime/delegateobject.cs index bf9ddea16..e1103cbc7 100644 --- a/src/runtime/delegateobject.cs +++ b/src/runtime/delegateobject.cs @@ -10,7 +10,7 @@ namespace Python.Runtime /// internal class DelegateObject : ClassBase { - MethodBinder binder; + private MethodBinder binder; internal DelegateObject(Type tp) : base(tp) { diff --git a/src/runtime/eventbinding.cs b/src/runtime/eventbinding.cs index 552472430..b8b4c82ad 100644 --- a/src/runtime/eventbinding.cs +++ b/src/runtime/eventbinding.cs @@ -7,8 +7,8 @@ namespace Python.Runtime /// internal class EventBinding : ExtensionType { - EventObject e; - IntPtr target; + private EventObject e; + private IntPtr target; public EventBinding(EventObject e, IntPtr target) { diff --git a/src/runtime/exceptions.cs b/src/runtime/exceptions.cs index 01a8ab585..b18cd7d69 100644 --- a/src/runtime/exceptions.cs +++ b/src/runtime/exceptions.cs @@ -171,7 +171,7 @@ internal static void SetArgsAndCause(IntPtr ob) /// Shortcut for (pointer == NULL) -> throw PythonException /// /// Pointer to a Python object - internal unsafe static void ErrorCheck(IntPtr pointer) + internal static unsafe void ErrorCheck(IntPtr pointer) { if (pointer == IntPtr.Zero) { @@ -182,7 +182,7 @@ internal unsafe static void ErrorCheck(IntPtr pointer) /// /// Shortcut for (pointer == NULL or ErrorOccurred()) -> throw PythonException /// - internal unsafe static void ErrorOccurredCheck(IntPtr pointer) + internal static unsafe void ErrorOccurredCheck(IntPtr pointer) { if (pointer == IntPtr.Zero || ErrorOccurred()) { diff --git a/src/runtime/fieldobject.cs b/src/runtime/fieldobject.cs index 6eefb5b0a..96572e5a5 100644 --- a/src/runtime/fieldobject.cs +++ b/src/runtime/fieldobject.cs @@ -8,7 +8,7 @@ namespace Python.Runtime /// internal class FieldObject : ExtensionType { - FieldInfo info; + private FieldInfo info; public FieldObject(FieldInfo info) { diff --git a/src/runtime/genericutil.cs b/src/runtime/genericutil.cs index 57f28cdc0..9772d082f 100644 --- a/src/runtime/genericutil.cs +++ b/src/runtime/genericutil.cs @@ -9,7 +9,7 @@ namespace Python.Runtime /// internal class GenericUtil { - static Dictionary>> mapping; + private static Dictionary>> mapping; private GenericUtil() { diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index bb70a6167..bc9ac5eee 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -8,13 +8,13 @@ namespace Python.Runtime /// internal class ImportHook { - static IntPtr py_import; - static CLRModule root; - static MethodWrapper hook; - static IntPtr py_clr_module; + private static IntPtr py_import; + private static CLRModule root; + private static MethodWrapper hook; + private static IntPtr py_clr_module; #if PYTHON3 - static IntPtr module_def = IntPtr.Zero; + private static IntPtr module_def = IntPtr.Zero; internal static void InitializeModuleDef() { @@ -36,8 +36,8 @@ internal static void Initialize() // modules (Python doesn't provide a way to emulate packages). IntPtr dict = Runtime.PyImport_GetModuleDict(); - IntPtr mod = Runtime.IsPython3 - ? Runtime.PyImport_ImportModule("builtins") + IntPtr mod = Runtime.IsPython3 + ? Runtime.PyImport_ImportModule("builtins") : Runtime.PyDict_GetItemString(dict, "__builtin__"); py_import = Runtime.PyObject_GetAttrString(mod, "__import__"); diff --git a/src/runtime/interfaceobject.cs b/src/runtime/interfaceobject.cs index 2085feac8..ce1bc9eb0 100644 --- a/src/runtime/interfaceobject.cs +++ b/src/runtime/interfaceobject.cs @@ -23,7 +23,7 @@ internal InterfaceObject(Type tp) : base(tp) } } - static Type cc_attr; + private static Type cc_attr; static InterfaceObject() { diff --git a/src/runtime/interop.cs b/src/runtime/interop.cs index dad5cb941..966d38f47 100644 --- a/src/runtime/interop.cs +++ b/src/runtime/interop.cs @@ -334,8 +334,8 @@ internal class TypeFlags internal class Interop { - static ArrayList keepAlive; - static Hashtable pmap; + private static ArrayList keepAlive; + private static Hashtable pmap; static Interop() { diff --git a/src/runtime/iterator.cs b/src/runtime/iterator.cs index efa49537c..c7c60ab19 100644 --- a/src/runtime/iterator.cs +++ b/src/runtime/iterator.cs @@ -9,7 +9,7 @@ namespace Python.Runtime /// internal class Iterator : ExtensionType { - IEnumerator iter; + private IEnumerator iter; public Iterator(IEnumerator e) { diff --git a/src/runtime/metatype.cs b/src/runtime/metatype.cs index 64c47b63e..bfb71e26d 100644 --- a/src/runtime/metatype.cs +++ b/src/runtime/metatype.cs @@ -10,7 +10,7 @@ namespace Python.Runtime /// internal class MetaType : ManagedType { - static IntPtr PyCLRMetaType; + private static IntPtr PyCLRMetaType; /// @@ -266,7 +266,7 @@ public static void tp_dealloc(IntPtr tp) NativeCall.Void_Call_1(op, tp); } - static IntPtr DoInstanceCheck(IntPtr tp, IntPtr args, bool checkType) + private static IntPtr DoInstanceCheck(IntPtr tp, IntPtr args, bool checkType) { var cb = GetManagedObject(tp) as ClassBase; diff --git a/src/runtime/moduleobject.cs b/src/runtime/moduleobject.cs index 1d8581b1b..8361f7fc7 100644 --- a/src/runtime/moduleobject.cs +++ b/src/runtime/moduleobject.cs @@ -11,7 +11,7 @@ namespace Python.Runtime /// internal class ModuleObject : ExtensionType { - Dictionary cache; + private Dictionary cache; internal string moduleName; internal IntPtr dict; protected string _namespace; diff --git a/src/runtime/nativecall.cs b/src/runtime/nativecall.cs index e81b34dde..9d1b0f41c 100644 --- a/src/runtime/nativecall.cs +++ b/src/runtime/nativecall.cs @@ -23,8 +23,8 @@ namespace Python.Runtime /// internal class NativeCall { - static AssemblyBuilder aBuilder; - static ModuleBuilder mBuilder; + private static AssemblyBuilder aBuilder; + private static ModuleBuilder mBuilder; public static INativeCall Impl; diff --git a/src/runtime/overload.cs b/src/runtime/overload.cs index e8f51c01d..6b48299e8 100644 --- a/src/runtime/overload.cs +++ b/src/runtime/overload.cs @@ -9,8 +9,8 @@ namespace Python.Runtime /// internal class OverloadMapper : ExtensionType { - MethodObject m; - IntPtr target; + private MethodObject m; + private IntPtr target; public OverloadMapper(MethodObject m, IntPtr target) { diff --git a/src/runtime/propertyobject.cs b/src/runtime/propertyobject.cs index dae47667f..7d758e38e 100644 --- a/src/runtime/propertyobject.cs +++ b/src/runtime/propertyobject.cs @@ -9,9 +9,9 @@ namespace Python.Runtime /// internal class PropertyObject : ExtensionType { - PropertyInfo info; - MethodInfo getter; - MethodInfo setter; + private PropertyInfo info; + private MethodInfo getter; + private MethodInfo setter; [StrongNameIdentityPermission(SecurityAction.Assert)] public PropertyObject(PropertyInfo md) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 0d122764f..22b590657 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -6,7 +6,7 @@ namespace Python.Runtime { [SuppressUnmanagedCodeSecurity] - static class NativeMethods + internal static class NativeMethods { #if MONO_LINUX || MONO_OSX private static int RTLD_NOW = 0x2; diff --git a/src/runtime/typemanager.cs b/src/runtime/typemanager.cs index 930030a71..b3b065cc4 100644 --- a/src/runtime/typemanager.cs +++ b/src/runtime/typemanager.cs @@ -12,8 +12,8 @@ namespace Python.Runtime /// internal class TypeManager { - static BindingFlags tbFlags; - static Dictionary cache; + private static BindingFlags tbFlags; + private static Dictionary cache; static TypeManager() { diff --git a/src/testing/conversiontest.cs b/src/testing/conversiontest.cs index f204a9f85..7179c7607 100644 --- a/src/testing/conversiontest.cs +++ b/src/testing/conversiontest.cs @@ -42,7 +42,7 @@ public interface ISpam public class Spam : ISpam { - string value; + private string value; public Spam(string value) { diff --git a/src/testing/propertytest.cs b/src/testing/propertytest.cs index 999865ef6..f54fd8bb5 100644 --- a/src/testing/propertytest.cs +++ b/src/testing/propertytest.cs @@ -9,7 +9,7 @@ public PropertyTest() { } - int _public_property = 0; + private int _public_property = 0; public int PublicProperty { @@ -17,7 +17,7 @@ public int PublicProperty set { _public_property = value; } } - static int _public_static_property = 0; + private static int _public_static_property = 0; public static int PublicStaticProperty { @@ -25,7 +25,7 @@ public static int PublicStaticProperty set { _public_static_property = value; } } - int _protected_property = 0; + private int _protected_property = 0; protected int ProtectedProperty { @@ -33,7 +33,7 @@ protected int ProtectedProperty set { _protected_property = value; } } - static int _protected_static_property = 0; + private static int _protected_static_property = 0; protected static int ProtectedStaticProperty { @@ -41,7 +41,7 @@ protected static int ProtectedStaticProperty set { _protected_static_property = value; } } - int _internal_property = 0; + private int _internal_property = 0; internal int InternalProperty { @@ -49,7 +49,7 @@ internal int InternalProperty set { _internal_property = value; } } - static int _internal_static_property = 0; + private static int _internal_static_property = 0; internal static int InternalStaticProperty { @@ -57,7 +57,7 @@ internal static int InternalStaticProperty set { _internal_static_property = value; } } - int _private_property = 0; + private int _private_property = 0; private int PrivateProperty { @@ -65,7 +65,7 @@ private int PrivateProperty set { _private_property = value; } } - static int _private_static_property = 0; + private static int _private_static_property = 0; private static int PrivateStaticProperty { @@ -73,7 +73,7 @@ private static int PrivateStaticProperty set { _private_static_property = value; } } - ShortEnum _enum_property = ShortEnum.Zero; + private ShortEnum _enum_property = ShortEnum.Zero; public ShortEnum EnumProperty { From d8cf55ada385ea0528d1490137d88fa6d00c77d6 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 14:14:16 -0700 Subject: [PATCH 100/245] Clean-up code-style Remove redundant parenthesis, enforce brackets, use keywork types. --- src/runtime/classobject.cs | 34 ++++++++++++------------ src/runtime/converter.cs | 52 +++++++++++++++++++------------------ src/runtime/interop.cs | 2 +- src/runtime/moduleobject.cs | 4 +-- src/runtime/pyobject.cs | 13 +++++++++- src/runtime/pythonengine.cs | 42 ++++++++++++++++++++++-------- 6 files changed, 91 insertions(+), 56 deletions(-) diff --git a/src/runtime/classobject.cs b/src/runtime/classobject.cs index 08656aefe..46257c73f 100644 --- a/src/runtime/classobject.cs +++ b/src/runtime/classobject.cs @@ -32,11 +32,13 @@ internal ClassObject(Type tp) : base(tp) internal IntPtr GetDocString() { MethodBase[] methods = binder.GetMethods(); - string str = ""; + var str = ""; foreach (MethodBase t in methods) { if (str.Length > 0) + { str += Environment.NewLine; + } str += t.ToString(); } return Runtime.PyString_FromString(str); @@ -48,7 +50,7 @@ internal IntPtr GetDocString() /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { - ClassObject self = GetManagedObject(tp) as ClassObject; + var self = GetManagedObject(tp) as ClassObject; // Sanity check: this ensures a graceful error if someone does // something intentially wrong like use the managed metatype for @@ -72,7 +74,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) } IntPtr op = Runtime.PyTuple_GetItem(args, 0); - Object result; + object result; if (!Converter.ToManaged(op, type, out result, true)) { @@ -94,7 +96,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) return IntPtr.Zero; } - Object obj = self.binder.InvokeRaw(IntPtr.Zero, args, kw); + object obj = self.binder.InvokeRaw(IntPtr.Zero, args, kw); if (obj == null) { return IntPtr.Zero; @@ -119,8 +121,8 @@ public override IntPtr type_subscript(IntPtr idx) { return Exceptions.RaiseTypeError("type expected"); } - ClassBase c = GetManagedObject(idx) as ClassBase; - Type t = (c != null) ? c.type : Converter.GetTypeByAlias(idx); + var c = GetManagedObject(idx) as ClassBase; + Type t = c != null ? c.type : Converter.GetTypeByAlias(idx); if (t == null) { return Exceptions.RaiseTypeError("type expected"); @@ -159,7 +161,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) { //ManagedType self = GetManagedObject(ob); IntPtr tp = Runtime.PyObject_TYPE(ob); - ClassBase cls = (ClassBase)GetManagedObject(tp); + var cls = (ClassBase)GetManagedObject(tp); if (cls.indexer == null || !cls.indexer.CanGet) { @@ -171,7 +173,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) // parameters. If so, use it directly, else make a new tuple // with the index arg (method binders expect arg tuples). IntPtr args = idx; - bool free = false; + var free = false; if (!Runtime.PyTuple_Check(idx)) { @@ -205,7 +207,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) { //ManagedType self = GetManagedObject(ob); IntPtr tp = Runtime.PyObject_TYPE(ob); - ClassBase cls = (ClassBase)GetManagedObject(tp); + var cls = (ClassBase)GetManagedObject(tp); if (cls.indexer == null || !cls.indexer.CanSet) { @@ -217,7 +219,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) // parameters. If so, use it directly, else make a new tuple // with the index arg (method binders expect arg tuples). IntPtr args = idx; - bool free = false; + var free = false; if (!Runtime.PyTuple_Check(idx)) { @@ -233,7 +235,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) int numOfDefaultArgs = Runtime.PyTuple_Size(defaultArgs); int temp = i + numOfDefaultArgs; IntPtr real = Runtime.PyTuple_New(temp + 1); - for (int n = 0; n < i; n++) + for (var n = 0; n < i; n++) { IntPtr item = Runtime.PyTuple_GetItem(args, n); Runtime.XIncref(item); @@ -241,7 +243,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) } // Add Default Args if needed - for (int n = 0; n < numOfDefaultArgs; n++) + for (var n = 0; n < numOfDefaultArgs; n++) { IntPtr item = Runtime.PyTuple_GetItem(defaultArgs, n); Runtime.XIncref(item); @@ -288,7 +290,7 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { //ManagedType self = GetManagedObject(ob); IntPtr tp = Runtime.PyObject_TYPE(ob); - ClassBase cb = (ClassBase)GetManagedObject(tp); + var cb = (ClassBase)GetManagedObject(tp); if (cb.type != typeof(Delegate)) { @@ -296,15 +298,15 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) return IntPtr.Zero; } - CLRObject co = (CLRObject)ManagedType.GetManagedObject(ob); - Delegate d = co.inst as Delegate; + var co = (CLRObject)GetManagedObject(ob); + var d = co.inst as Delegate; BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; MethodInfo method = d.GetType().GetMethod("Invoke", flags); - MethodBinder binder = new MethodBinder(method); + var binder = new MethodBinder(method); return binder.Invoke(ob, args, kw); } } diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 38fec1256..fa5d73c86 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -52,8 +52,8 @@ static Converter() /// internal static Type GetTypeByAlias(IntPtr op) { - if ((op == Runtime.PyStringType) || - (op == Runtime.PyUnicodeType)) + if (op == Runtime.PyStringType || + op == Runtime.PyUnicodeType) { return stringType; } @@ -83,15 +83,15 @@ internal static IntPtr GetPythonTypeByAlias(Type op) return Runtime.PyUnicodeType; } - else if (Runtime.IsPython3 && ((op == int16Type) || - (op == int32Type) || - (op == int64Type))) + else if (Runtime.IsPython3 && (op == int16Type || + op == int32Type || + op == int64Type)) { return Runtime.PyIntType; } - else if ((op == int16Type) || - (op == int32Type)) + else if (op == int16Type || + op == int32Type) { return Runtime.PyIntType; } @@ -99,8 +99,8 @@ internal static IntPtr GetPythonTypeByAlias(Type op) { return Runtime.PyLongType; } - else if ((op == doubleType) || - (op == singleType)) + else if (op == doubleType || + op == singleType) { return Runtime.PyFloatType; } @@ -123,7 +123,7 @@ internal static IntPtr ToPython(T value) return ToPython(value, typeof(T)); } - internal static IntPtr ToPython(Object value, Type type) + internal static IntPtr ToPython(object value, Type type) { if (value is PyObject) { @@ -144,7 +144,7 @@ internal static IntPtr ToPython(Object value, Type type) // it the type is a python subclass of a managed type then return the // underlying python object rather than construct a new wrapper object. - IPythonDerivedType pyderived = value as IPythonDerivedType; + var pyderived = value as IPythonDerivedType; if (null != pyderived) { return ClassDerivedObject.ToPython(pyderived); @@ -221,7 +221,9 @@ internal static IntPtr ToPython(Object value, Type type) foreach (object o in (IEnumerable)value) { using (var p = new PyObject(ToPython(o, o?.GetType()))) + { resultlist.Append(p); + } } Runtime.XIncref(resultlist.Handle); return resultlist.Handle; @@ -237,7 +239,7 @@ internal static IntPtr ToPython(Object value, Type type) /// In a few situations, we don't have any advisory type information /// when we want to convert an object to Python. /// - internal static IntPtr ToPythonImplicit(Object value) + internal static IntPtr ToPythonImplicit(object value) { if (value == null) { @@ -266,7 +268,7 @@ internal static bool ToManaged(IntPtr value, Type type, internal static bool ToManagedValue(IntPtr value, Type obType, - out Object result, bool setError) + out object result, bool setError) { if (obType == typeof(PyObject)) { @@ -290,8 +292,8 @@ internal static bool ToManagedValue(IntPtr value, Type obType, result = tmp; return true; } - string err = "value cannot be converted to {0}"; - err = String.Format(err, obType); + var err = "value cannot be converted to {0}"; + err = string.Format(err, obType); Exceptions.SetError(Exceptions.TypeError, err); return false; } @@ -474,7 +476,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo } long ll = (long)Runtime.PyLong_AsLongLong(op); Runtime.XDecref(op); - if ((ll == -1) && Exceptions.ErrorOccurred()) + if (ll == -1 && Exceptions.ErrorOccurred()) { goto overflow; } @@ -487,7 +489,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo } case TypeCode.Boolean: - result = (Runtime.PyObject_IsTrue(value) != 0); + result = Runtime.PyObject_IsTrue(value) != 0; return true; case TypeCode.Byte: @@ -791,9 +793,9 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo if (setError) { - string format = "'{0}' value cannot be converted to {1}"; + var format = "'{0}' value cannot be converted to {1}"; string tpName = Runtime.PyObject_GetTypeName(value); - string error = String.Format(format, tpName, obType); + string error = string.Format(format, tpName, obType); Exceptions.SetError(Exceptions.TypeError, error); } @@ -803,7 +805,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo if (setError) { - string error = "value too large to convert"; + var error = "value too large to convert"; Exceptions.SetError(Exceptions.OverflowError, error); } @@ -811,12 +813,12 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo } - static void SetConversionError(IntPtr value, Type target) + private static void SetConversionError(IntPtr value, Type target) { IntPtr ob = Runtime.PyObject_Repr(value); string src = Runtime.GetManagedString(ob); Runtime.XDecref(ob); - string error = String.Format("Cannot convert {0} to {1}", src, target); + string error = string.Format("Cannot convert {0} to {1}", src, target); Exceptions.SetError(Exceptions.TypeError, error); } @@ -844,9 +846,9 @@ private static bool ToArray(IntPtr value, Type obType, out object result, bool s Array items = Array.CreateInstance(elementType, size); // XXX - is there a better way to unwrap this if it is a real array? - for (int i = 0; i < size; i++) + for (var i = 0; i < size; i++) { - Object obj = null; + object obj = null; IntPtr item = Runtime.PySequence_GetItem(value, i); if (item == IntPtr.Zero) { @@ -899,7 +901,7 @@ private static bool ToEnum(IntPtr value, Type obType, out object result, bool se if (setError) { - string error = "invalid enumeration value"; + var error = "invalid enumeration value"; Exceptions.SetError(Exceptions.ValueError, error); } diff --git a/src/runtime/interop.cs b/src/runtime/interop.cs index 966d38f47..14a69591c 100644 --- a/src/runtime/interop.cs +++ b/src/runtime/interop.cs @@ -74,7 +74,7 @@ internal class ObjectOffset static ObjectOffset() { int size = IntPtr.Size; - int n = 0; // Py_TRACE_REFS add two pointers to PyObject_HEAD + var n = 0; // Py_TRACE_REFS add two pointers to PyObject_HEAD #if Py_DEBUG _ob_next = 0; _ob_prev = 1 * size; diff --git a/src/runtime/moduleobject.cs b/src/runtime/moduleobject.cs index 8361f7fc7..b324e6f3a 100644 --- a/src/runtime/moduleobject.cs +++ b/src/runtime/moduleobject.cs @@ -43,7 +43,7 @@ public ModuleObject(string name) IntPtr pyname = Runtime.PyString_FromString(moduleName); IntPtr pyfilename = Runtime.PyString_FromString(filename); IntPtr pydocstring = Runtime.PyString_FromString(docstring); - IntPtr pycls = TypeManager.GetTypeHandle(this.GetType()); + IntPtr pycls = TypeManager.GetTypeHandle(GetType()); Runtime.PyDict_SetItemString(dict, "__name__", pyname); Runtime.PyDict_SetItemString(dict, "__file__", pyfilename); Runtime.PyDict_SetItemString(dict, "__doc__", pydocstring); @@ -318,7 +318,7 @@ public CLRModule() : base("clr") // import requires the module to pass PyModule_Check. :( if (!hacked) { - IntPtr type = this.tpHandle; + IntPtr type = tpHandle; IntPtr mro = Marshal.ReadIntPtr(type, TypeOffset.tp_mro); IntPtr ext = Runtime.ExtendTuple(mro, Runtime.PyModuleType); Marshal.WriteIntPtr(type, TypeOffset.tp_mro, ext); diff --git a/src/runtime/pyobject.cs b/src/runtime/pyobject.cs index 837c2d312..4527e145f 100644 --- a/src/runtime/pyobject.cs +++ b/src/runtime/pyobject.cs @@ -895,7 +895,9 @@ public override bool TryGetMember(GetMemberBinder binder, out object result) return true; } else + { return base.TryGetMember(binder, out result); + } } public override bool TrySetMember(SetMemberBinder binder, object value) @@ -906,13 +908,18 @@ public override bool TrySetMember(SetMemberBinder binder, object value) return true; } else + { return base.TrySetMember(binder, value); + } } private void GetArgs(object[] inargs, out PyTuple args, out PyDict kwargs) { int arg_count; - for (arg_count = 0; arg_count < inargs.Length && !(inargs[arg_count] is Py.KeywordArguments); ++arg_count) ; + for (arg_count = 0; arg_count < inargs.Length && !(inargs[arg_count] is Py.KeywordArguments); ++arg_count) + { + ; + } IntPtr argtuple = Runtime.PyTuple_New(arg_count); for (var i = 0; i < arg_count; i++) { @@ -975,7 +982,9 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o return true; } else + { return base.TryInvokeMember(binder, args, out result); + } } public override bool TryInvoke(InvokeBinder binder, object[] args, out object result) @@ -1003,7 +1012,9 @@ public override bool TryInvoke(InvokeBinder binder, object[] args, out object re return true; } else + { return base.TryInvoke(binder, args, out result); + } } public override bool TryConvert(ConvertBinder binder, out object result) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index c66ae0c47..ae3e135b1 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -162,13 +162,15 @@ public static void Initialize(IEnumerable args) "atexit.register(clr._AtExit)\n"; PyObject r = PythonEngine.RunString(code); if (r != null) + { r.Dispose(); + } // Load the clr.py resource into the clr module IntPtr clr = Python.Runtime.ImportHook.GetCLRModule(); IntPtr clr_dict = Runtime.PyModule_GetDict(clr); - PyDict locals = new PyDict(); + var locals = new PyDict(); try { IntPtr module = Runtime.PyImport_AddModule("clr._extras"); @@ -176,15 +178,17 @@ public static void Initialize(IEnumerable args) IntPtr builtins = Runtime.PyEval_GetBuiltins(); Runtime.PyDict_SetItemString(module_globals, "__builtins__", builtins); - var assembly = Assembly.GetExecutingAssembly(); + Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream("clr.py")) - using (StreamReader reader = new StreamReader(stream)) + using (var reader = new StreamReader(stream)) { // add the contents of clr.py to the module string clr_py = reader.ReadToEnd(); PyObject result = RunString(clr_py, module_globals, locals.Handle); if (null == result) + { throw new PythonException(); + } result.Dispose(); } @@ -415,9 +419,9 @@ public static PyObject ModuleFromString(string name, string code) /// public static PyObject RunString( string code, IntPtr? globals = null, IntPtr? locals = null - ) + ) { - bool borrowedGlobals = true; + var borrowedGlobals = true; if (globals == null) { globals = Runtime.PyEval_GetGlobals(); @@ -427,25 +431,25 @@ public static PyObject RunString( Runtime.PyDict_SetItemString( globals.Value, "__builtins__", Runtime.PyEval_GetBuiltins() - ); + ); borrowedGlobals = false; } } - bool borrowedLocals = true; + var borrowedLocals = true; if (locals == null) { locals = Runtime.PyDict_New(); borrowedLocals = false; } - IntPtr flag = (IntPtr)257; /* Py_file_input */ + var flag = (IntPtr)257; /* Py_file_input */ try { IntPtr result = Runtime.PyRun_String( code, flag, globals.Value, locals.Value - ); + ); Py.Throw(); @@ -454,9 +458,13 @@ public static PyObject RunString( finally { if (!borrowedLocals) + { Runtime.XDecref(locals.Value); + } if (!borrowedGlobals) + { Runtime.XDecref(globals.Value); + } } } } @@ -466,7 +474,9 @@ public static class Py public static GILState GIL() { if (!PythonEngine.IsInitialized) + { PythonEngine.Initialize(); + } return new GILState(); } @@ -500,18 +510,28 @@ public static KeywordArguments kw(params object[] kv) { var dict = new KeywordArguments(); if (kv.Length % 2 != 0) + { throw new ArgumentException("Must have an equal number of keys and values"); - for (int i = 0; i < kv.Length; i += 2) + } + for (var i = 0; i < kv.Length; i += 2) { IntPtr value; if (kv[i + 1] is PyObject) + { value = ((PyObject)kv[i + 1]).Handle; + } else + { value = Converter.ToPython(kv[i + 1], kv[i + 1]?.GetType()); + } if (Runtime.PyDict_SetItemString(dict.Handle, (string)kv[i], value) != 0) + { throw new ArgumentException(string.Format("Cannot add key '{0}' to dictionary.", (string)kv[i])); + } if (!(kv[i + 1] is PyObject)) + { Runtime.XDecref(value); + } } return dict; } @@ -549,7 +569,7 @@ public static void SetArgv(IEnumerable argv) { using (GIL()) { - var arr = argv.ToArray(); + string[] arr = argv.ToArray(); Runtime.PySys_SetArgvEx(arr.Length, arr, 0); Py.Throw(); } From 42a6191adb825aef797f902e34854d81081e5296 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 14:16:40 -0700 Subject: [PATCH 101/245] Remove obsoleted & Unenforced PermissionSet See: http://stackoverflow.com/questions/11625447/securityaction-requestminimum-is-obsolete-in-net-4-0 --- src/console/AssemblyInfo.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/console/AssemblyInfo.cs b/src/console/AssemblyInfo.cs index fcdc2b693..17d792c7a 100644 --- a/src/console/AssemblyInfo.cs +++ b/src/console/AssemblyInfo.cs @@ -10,7 +10,6 @@ [assembly: AssemblyDefaultAlias("python.exe")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] -[assembly: PermissionSet(SecurityAction.RequestMinimum, Name = "FullTrust")] [assembly: AssemblyDescription("")] [assembly: AssemblyCopyright("MIT License")] [assembly: AssemblyFileVersion("2.0.0.4")] From ca8d1cb49c85e552f0e6660ce261c07ed5e0dcc6 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 17:35:54 -0700 Subject: [PATCH 102/245] Add expire to license shield Github Cache issue https://github.com/github/markup/issues/224 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cb9a0f910..86825386c 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ int32 [codecov shield]: https://img.shields.io/codecov/c/github/pythonnet/pythonnet/master.svg?label=codecov -[license shield]: https://img.shields.io/badge/license-MIT-blue.svg +[license shield]: https://img.shields.io/badge/license-MIT-blue.svg?maxAge=3600 [pypi package version]: https://img.shields.io/pypi/v/pythonnet.svg From d82ca2878368475d81ed7b60d94402e1faae6b91 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 18:36:41 -0700 Subject: [PATCH 103/245] Remove usage of #region It hides away the code in Visual Studio --- src/runtime/pyiter.cs | 4 ---- src/runtime/pythonengine.cs | 4 ---- 2 files changed, 8 deletions(-) diff --git a/src/runtime/pyiter.cs b/src/runtime/pyiter.cs index 3c9b2a238..ee07bcecf 100644 --- a/src/runtime/pyiter.cs +++ b/src/runtime/pyiter.cs @@ -50,8 +50,6 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } - #region IEnumerator Members - public bool MoveNext() { // dispose of the previous object, if there was one @@ -80,7 +78,5 @@ public object Current { get { return _current; } } - - #endregion } } diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index ae3e135b1..e9fa888a9 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -35,8 +35,6 @@ public void Dispose() Shutdown(); } - #region Properties - public static bool IsInitialized { get { return initialized; } @@ -122,8 +120,6 @@ public static int RunSimpleString(string code) return Runtime.PyRun_SimpleString(code); } - #endregion - public static void Initialize() { Initialize(Enumerable.Empty()); From 75dd5448fc19caa4de32cb224afb89c53139f090 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 15:29:28 -0700 Subject: [PATCH 104/245] Turn on NUNIT exit code --- ci/appveyor_run_tests.ps1 | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 index 78bae50b9..3bfaf216d 100644 --- a/ci/appveyor_run_tests.ps1 +++ b/ci/appveyor_run_tests.ps1 @@ -26,8 +26,7 @@ if ($NUNIT_STATUS -ne 0) { } # Embedded tests failing due to open issues, pass/fail only on Python exit code -# if ($PYTHON_STATUS -ne 0 -or $NUNIT_STATUS -ne 0) { -if ($PYTHON_STATUS -ne 0) { +if ($PYTHON_STATUS -ne 0 -or $NUNIT_STATUS -ne 0) { Write-Host "Tests failed" -ForegroundColor "Red" $host.SetShouldExit(1) } From c69297e1da11ea09f5f6576578028420771cb3e8 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 18:18:25 -0700 Subject: [PATCH 105/245] Fix GC on PyObject during Finalizing Similar to how `PythonDerivedType` finalizes. Closes #364 Possibly related to #245 --- src/runtime/pyobject.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/runtime/pyobject.cs b/src/runtime/pyobject.cs index 4527e145f..3296d81f8 100644 --- a/src/runtime/pyobject.cs +++ b/src/runtime/pyobject.cs @@ -113,7 +113,7 @@ protected virtual void Dispose(bool disposing) { if (!disposed) { - if (Runtime.Py_IsInitialized() > 0) + if (Runtime.Py_IsInitialized() > 0 && !Runtime.IsFinalizing) { IntPtr gs = PythonEngine.AcquireLock(); Runtime.XDecref(obj); From c954442c3f2ae594ca318f298ebd4607ea7fab3d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Feb 2017 19:11:49 -0700 Subject: [PATCH 106/245] Update CHANGELOG --- CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05b8126ce..0dcf33d7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Code Coverage (#345) - Added `pysetargv` (#347) - Added XML Documentation (#349) +- Added Embedded tests on Appveyor (#353) - Added PY3 settings to configuration-manager (#346) ### Changed @@ -21,11 +22,11 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Completed refactor of Build Directives on `Runtime.cs` (#339) - Refactor python unittests (#329) - Unfroze Mono version on Travis (#345) -- Enabled Embedded tests on Appveyor (#353) ### Fixed -- Fixed crash during Shutdown (#343) +- Fixed crash during Initialization (#343) +- Fixed crash during Shutdown (#365) ### Removed From 79eeb61362e637e3eb8ec0676c748abd5013370d Mon Sep 17 00:00:00 2001 From: denfromufa Date: Wed, 8 Feb 2017 11:44:03 -0600 Subject: [PATCH 107/245] Add sys.args tests (#301) --- src/embed_tests/pyimport.cs | 14 +++++++++++--- src/tests/PyImportTest/sysargv.py | 5 +++++ src/tests/runtests.py | 3 +++ src/tests/test_sysargv.py | 17 +++++++++++++++++ src/tests/tests.pyproj | 2 ++ 5 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 src/tests/PyImportTest/sysargv.py create mode 100644 src/tests/test_sysargv.py diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index e4ba8d546..dc9d90fe2 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -1,9 +1,7 @@ using System; -using System.Reflection; -using System.Collections.Generic; +using System.IO; using NUnit.Framework; using Python.Runtime; -using System.IO; namespace Python.EmbeddingTest { @@ -55,5 +53,15 @@ public void TestDottedName() PyObject module = PythonEngine.ImportModule("PyImportTest.test.one"); Assert.IsNotNull(module, ">>> import PyImportTest.test.one # FAILED"); } + + /// + /// Tests that sys.args is set. If it wasn't exception would be raised. + /// + [Test] + public void TestSysArgsImportException() + { + PyObject module = PythonEngine.ImportModule("PyImportTest.sysargv"); + Assert.IsNotNull(module, ">>> import PyImportTest.sysargv # FAILED"); + } } } diff --git a/src/tests/PyImportTest/sysargv.py b/src/tests/PyImportTest/sysargv.py new file mode 100644 index 000000000..2e1508bff --- /dev/null +++ b/src/tests/PyImportTest/sysargv.py @@ -0,0 +1,5 @@ +# -*- coding: utf-8 -*- + +import sys +# if argv is available, as expected, then no exception +num_args = len(sys.argv) diff --git a/src/tests/runtests.py b/src/tests/runtests.py index 9b77f99dd..92d9ecbd0 100644 --- a/src/tests/runtests.py +++ b/src/tests/runtests.py @@ -23,6 +23,9 @@ clr.AddReference("System.Management") test_modules = ( + # has to be first test before other module import clr + 'test_sysargv', + # test_module passes on its own, but not here if # other test modules that import System.Windows.Forms # run first. They must not do module level import/AddReference() diff --git a/src/tests/test_sysargv.py b/src/tests/test_sysargv.py new file mode 100644 index 000000000..eefb4d341 --- /dev/null +++ b/src/tests/test_sysargv.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- + +import unittest +import sys + +class SysArgvTests(unittest.TestCase): + """Test sys.argv state.""" + + def test_sys_argv_state(self): + """Test sys.argv state doesn't change after clr import.""" + argv = sys.argv + import clr + self.assertTrue(argv == sys.argv) + + +def test_suite(): + return unittest.makeSuite(SysArgvTests) diff --git a/src/tests/tests.pyproj b/src/tests/tests.pyproj index cf8f74a4a..5d042249e 100644 --- a/src/tests/tests.pyproj +++ b/src/tests/tests.pyproj @@ -29,12 +29,14 @@ + + From 3995130ab43bd43ea211350317778865813b1520 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 8 Feb 2017 11:09:48 -0700 Subject: [PATCH 108/245] Use NUnit from Nuget to ensure right version. --- .travis.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index df89014f4..fcb0f265e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,6 @@ addons: packages: - mono-devel - ca-certificates-mono - - nunit-console install: - pip install pycparser coverage codecov @@ -36,7 +35,7 @@ install: script: - export PYTHONPATH=`pwd`:$PYTHONPATH - python src/tests/runtests.py - # - nunit-console src/embed_tests/bin/Python.EmbeddingTest.dll + # - mono ./packages/NUnit.Runners*/tools/nunit-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll after_success: # Uncomment if need to geninterop, ie. py37 final From 4919bffd2d861376cf04fa5acdfe9731f114c148 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 8 Feb 2017 19:01:10 -0700 Subject: [PATCH 109/245] Simplify Embedded tests & Add new tests (#369) * Add Tuple tests * Update AppVeyor comments and show when tests start. * Rename InitializeTest to pyinitialize Keep consistent with other test classes. * Simplify embed_tests Since the previous bug involving initialize/finalize have been solved, we can confidently upgrade these test to use simpler format. Also Remove Assert fail messages NUnit already says the name of which test failed. --- ci/appveyor_run_tests.ps1 | 4 +- src/embed_tests/Python.EmbeddingTest.csproj | 3 +- src/embed_tests/pyimport.cs | 30 +++--- .../{InitializeTest.cs => pyinitialize.cs} | 6 +- src/embed_tests/pyiter.cs | 43 +++------ src/embed_tests/pylong.cs | 27 ++---- src/embed_tests/pyobject.cs | 25 +---- src/embed_tests/pythonexception.cs | 7 ++ src/embed_tests/pytuple.cs | 94 +++++++++++++++++++ 9 files changed, 148 insertions(+), 91 deletions(-) rename src/embed_tests/{InitializeTest.cs => pyinitialize.cs} (89%) create mode 100644 src/embed_tests/pytuple.cs diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 index 3bfaf216d..300b2caa0 100644 --- a/ci/appveyor_run_tests.ps1 +++ b/ci/appveyor_run_tests.ps1 @@ -12,6 +12,7 @@ $RUNTIME_DIR = ".\src\runtime\bin\" # Run python tests with C# coverage # why `2>&1 | %{ "$_" }`? see: http://stackoverflow.com/a/20950421/5208670 +Write-Host ("Starting Python tests") -ForegroundColor "Green" .$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:py.coverage -target:"$PY" -targetargs:src\tests\runtests.py -returntargetcode 2>&1 | %{ "$_" } $PYTHON_STATUS = $LastExitCode if ($PYTHON_STATUS -ne 0) { @@ -19,13 +20,14 @@ if ($PYTHON_STATUS -ne 0) { } # Run Embedded tests with C# coverage +Write-Host ("Starting embedded tests") -ForegroundColor "Green" .$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:cs.coverage -target:"$NUNIT" -targetargs:"$CS_TESTS" -returntargetcode $NUNIT_STATUS = $LastExitCode if ($NUNIT_STATUS -ne 0) { Write-Host "Embedded tests failed" -ForegroundColor "Red" } -# Embedded tests failing due to open issues, pass/fail only on Python exit code +# Set exit code to fail if either Python or Embedded tests failed if ($PYTHON_STATUS -ne 0 -or $NUNIT_STATUS -ne 0) { Write-Host "Tests failed" -ForegroundColor "Red" $host.SetShouldExit(1) diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 48fe2554e..9cca794b4 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -75,12 +75,13 @@ - + + diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index dc9d90fe2..ebdc5b125 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -5,6 +5,18 @@ namespace Python.EmbeddingTest { + /// + /// Test Import unittests and regressions + /// + /// + /// Keeping in old-style SetUp/TearDown due to required SetUp. + /// The required directory structure was added to .\pythonnet\src\tests\ directory: + /// + PyImportTest/ + /// | - __init__.py + /// | + test/ + /// | | - __init__.py + /// | | - one.py + /// [TestFixture] public class PyImportTest { @@ -18,10 +30,8 @@ public void SetUp() /* Append the tests directory to sys.path * using reflection to circumvent the private - * modifiers placed on most Runtime methods. - */ - const string s = @"../../tests"; - + * modifiers placed on most Runtime methods. */ + const string s = "../../tests"; string testPath = Path.Combine(TestContext.CurrentContext.TestDirectory, s); IntPtr str = Runtime.Runtime.PyString_FromString(testPath); @@ -39,19 +49,11 @@ public void TearDown() /// /// Test subdirectory import /// - /// - /// The required directory structure was added to .\pythonnet\src\tests\ directory: - /// + PyImportTest/ - /// | - __init__.py - /// | + test/ - /// | | - __init__.py - /// | | - one.py - /// [Test] public void TestDottedName() { PyObject module = PythonEngine.ImportModule("PyImportTest.test.one"); - Assert.IsNotNull(module, ">>> import PyImportTest.test.one # FAILED"); + Assert.IsNotNull(module); } /// @@ -61,7 +63,7 @@ public void TestDottedName() public void TestSysArgsImportException() { PyObject module = PythonEngine.ImportModule("PyImportTest.sysargv"); - Assert.IsNotNull(module, ">>> import PyImportTest.sysargv # FAILED"); + Assert.IsNotNull(module); } } } diff --git a/src/embed_tests/InitializeTest.cs b/src/embed_tests/pyinitialize.cs similarity index 89% rename from src/embed_tests/InitializeTest.cs rename to src/embed_tests/pyinitialize.cs index 3c5974fb5..71aea58be 100644 --- a/src/embed_tests/InitializeTest.cs +++ b/src/embed_tests/pyinitialize.cs @@ -1,13 +1,9 @@ using NUnit.Framework; using Python.Runtime; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Python.EmbeddingTest { - public class InitializeTest + public class PyInitializeTest { [Test] public static void LoadSpecificArgs() diff --git a/src/embed_tests/pyiter.cs b/src/embed_tests/pyiter.cs index 1f0c651f8..b110903f6 100644 --- a/src/embed_tests/pyiter.cs +++ b/src/embed_tests/pyiter.cs @@ -1,45 +1,30 @@ -using System; using System.Collections.Generic; using NUnit.Framework; using Python.Runtime; namespace Python.EmbeddingTest { - [TestFixture] public class PyIterTest { - private IntPtr gs; - - [SetUp] - public void SetUp() - { - PythonEngine.Initialize(); - gs = PythonEngine.AcquireLock(); - } - - [TearDown] - public void TearDown() - { - PythonEngine.ReleaseLock(gs); - PythonEngine.Shutdown(); - } - [Test] public void TestOnPyList() { - var list = new PyList(); - list.Append(new PyString("foo")); - list.Append(new PyString("bar")); - list.Append(new PyString("baz")); - var result = new List(); - foreach (PyObject item in list) + using (Py.GIL()) { - result.Add(item.ToString()); + var list = new PyList(); + list.Append(new PyString("foo")); + list.Append(new PyString("bar")); + list.Append(new PyString("baz")); + var result = new List(); + foreach (PyObject item in list) + { + result.Add(item.ToString()); + } + Assert.AreEqual(3, result.Count); + Assert.AreEqual("foo", result[0]); + Assert.AreEqual("bar", result[1]); + Assert.AreEqual("baz", result[2]); } - Assert.AreEqual(3, result.Count); - Assert.AreEqual("foo", result[0]); - Assert.AreEqual("bar", result[1]); - Assert.AreEqual("baz", result[2]); } } } diff --git a/src/embed_tests/pylong.cs b/src/embed_tests/pylong.cs index 3a7365a61..37cf1042d 100644 --- a/src/embed_tests/pylong.cs +++ b/src/embed_tests/pylong.cs @@ -1,34 +1,19 @@ -using System; using NUnit.Framework; using Python.Runtime; namespace Python.EmbeddingTest { - [TestFixture] public class PyLongTest { - private IntPtr gs; - - [SetUp] - public void SetUp() - { - PythonEngine.Initialize(); - gs = PythonEngine.AcquireLock(); - } - - [TearDown] - public void TearDown() - { - PythonEngine.ReleaseLock(gs); - PythonEngine.Shutdown(); - } - [Test] public void TestToInt64() { - long largeNumber = 8L * 1024L * 1024L * 1024L; // 8 GB - var pyLargeNumber = new PyLong(largeNumber); - Assert.AreEqual(largeNumber, pyLargeNumber.ToInt64()); + using (Py.GIL()) + { + long largeNumber = 8L * 1024L * 1024L * 1024L; // 8 GB + var pyLargeNumber = new PyLong(largeNumber); + Assert.AreEqual(largeNumber, pyLargeNumber.ToInt64()); + } } } } diff --git a/src/embed_tests/pyobject.cs b/src/embed_tests/pyobject.cs index c0f18df39..f114d3d9e 100644 --- a/src/embed_tests/pyobject.cs +++ b/src/embed_tests/pyobject.cs @@ -1,33 +1,18 @@ -using System; using NUnit.Framework; using Python.Runtime; namespace Python.EmbeddingTest { - [TestFixture] public class PyObjectTest { - private IntPtr gs; - - [SetUp] - public void SetUp() - { - PythonEngine.Initialize(); - gs = PythonEngine.AcquireLock(); - } - - [TearDown] - public void TearDown() - { - PythonEngine.ReleaseLock(gs); - PythonEngine.Shutdown(); - } - [Test] public void TestUnicode() { - PyObject s = new PyString("foo\u00e9"); - Assert.AreEqual("foo\u00e9", s.ToString()); + using (Py.GIL()) + { + PyObject s = new PyString("foo\u00e9"); + Assert.AreEqual("foo\u00e9", s.ToString()); + } } } } diff --git a/src/embed_tests/pythonexception.cs b/src/embed_tests/pythonexception.cs index aaaf2c61c..0b7771d96 100644 --- a/src/embed_tests/pythonexception.cs +++ b/src/embed_tests/pythonexception.cs @@ -4,6 +4,13 @@ namespace Python.EmbeddingTest { + /// + /// Test Python Exceptions + /// + /// + /// Keeping this in the old-style SetUp/TearDown + /// to ensure that setup still works. + /// [TestFixture] public class PythonExceptionTest { diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/pytuple.cs new file mode 100644 index 000000000..ea2319d3c --- /dev/null +++ b/src/embed_tests/pytuple.cs @@ -0,0 +1,94 @@ +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + public class PyTupleTest + { + [Test] + public void TestPyTupleEmpty() + { + using (Py.GIL()) + { + var t = new PyTuple(); + Assert.AreEqual(0, t.Length()); + } + } + + [Test] + [ExpectedException("Python.Runtime.PythonException")] + public void TestPyTupleInvalidAppend() + { + using (Py.GIL()) + { + PyObject s = new PyString("foo"); + var t = new PyTuple(); + t.Concat(s); + } + } + + [Test] + public void TestPyTupleValidAppend() + { + using (Py.GIL()) + { + var t0 = new PyTuple(); + var t = new PyTuple(); + t.Concat(t0); + Assert.IsNotNull(t); + Assert.IsInstanceOf(typeof(PyTuple), t); + } + } + + [Test] + public void TestPyTupleIsTupleType() + { + using (Py.GIL()) + { + var s = new PyString("foo"); + var t = new PyTuple(); + Assert.IsTrue(PyTuple.IsTupleType(t)); + Assert.IsFalse(PyTuple.IsTupleType(s)); + } + } + + [Test] + public void TestPyTupleStringConvert() + { + using (Py.GIL()) + { + PyObject s = new PyString("foo"); + PyTuple t = PyTuple.AsTuple(s); + Assert.IsNotNull(t); + Assert.IsInstanceOf(typeof(PyTuple), t); + Assert.AreEqual("f", t[0].ToString()); + Assert.AreEqual("o", t[1].ToString()); + Assert.AreEqual("o", t[2].ToString()); + } + } + + [Test] + public void TestPyTupleValidConvert() + { + using (Py.GIL()) + { + var l = new PyList(); + PyTuple t = PyTuple.AsTuple(l); + Assert.IsNotNull(t); + Assert.IsInstanceOf(typeof(PyTuple), t); + } + } + + [Test] + public void TestNewPyTupleFromPyTuple() + { + using (Py.GIL()) + { + var t0 = new PyTuple(); + var t = new PyTuple(t0); + Assert.IsNotNull(t); + Assert.IsInstanceOf(typeof(PyTuple), t); + } + } + } +} From 9cfb4f19fd18ba29d585ec6de04f6be4413b74e6 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 8 Feb 2017 19:05:24 -0700 Subject: [PATCH 110/245] Add e-mail to remove setup.py warnings --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index a7c2910ac..85d5da3d9 100644 --- a/setup.py +++ b/setup.py @@ -373,6 +373,7 @@ def run(self): url='https://pythonnet.github.io/', license='MIT', author="The Python for .Net developers", + email="pythondotnet@python.org", setup_requires=setup_requires, long_description=_get_long_description(), ext_modules=[ From 58bc902b521fcb89a91d6d01b75c063921737bc3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 8 Feb 2017 19:13:53 -0700 Subject: [PATCH 111/245] Update NUnit syntax Use xUnit2 and nUnit3 friendly syntax --- setup.py | 2 +- src/embed_tests/pyinitialize.cs | 6 +++--- src/embed_tests/pythonexception.cs | 2 +- src/embed_tests/pytuple.cs | 3 +-- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/setup.py b/setup.py index 85d5da3d9..f2790ddd3 100644 --- a/setup.py +++ b/setup.py @@ -373,7 +373,7 @@ def run(self): url='https://pythonnet.github.io/', license='MIT', author="The Python for .Net developers", - email="pythondotnet@python.org", + author_email="pythondotnet@python.org", setup_requires=setup_requires, long_description=_get_long_description(), ext_modules=[ diff --git a/src/embed_tests/pyinitialize.cs b/src/embed_tests/pyinitialize.cs index 71aea58be..bfd95aaab 100644 --- a/src/embed_tests/pyinitialize.cs +++ b/src/embed_tests/pyinitialize.cs @@ -12,8 +12,8 @@ public static void LoadSpecificArgs() using (new PythonEngine(args)) using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) { - Assert.That(argv[0].ToString() == args[0]); - Assert.That(argv[1].ToString() == args[1]); + Assert.AreEqual(args[0], argv[0].ToString()); + Assert.AreEqual(args[1], argv[1].ToString()); } } @@ -23,7 +23,7 @@ public static void LoadDefaultArgs() using (new PythonEngine()) using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) { - Assert.That(argv.Length() != 0); + Assert.AreNotEqual(0, argv.Length()); } } diff --git a/src/embed_tests/pythonexception.cs b/src/embed_tests/pythonexception.cs index 0b7771d96..7811bd37b 100644 --- a/src/embed_tests/pythonexception.cs +++ b/src/embed_tests/pythonexception.cs @@ -47,7 +47,7 @@ public void TestMessage() [Test] public void TestNoError() { - var e = new PythonException(); //There is no PyErr to fetch + var e = new PythonException(); // There is no PyErr to fetch Assert.AreEqual("", e.Message); } } diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/pytuple.cs index ea2319d3c..18a6ea344 100644 --- a/src/embed_tests/pytuple.cs +++ b/src/embed_tests/pytuple.cs @@ -16,14 +16,13 @@ public void TestPyTupleEmpty() } [Test] - [ExpectedException("Python.Runtime.PythonException")] public void TestPyTupleInvalidAppend() { using (Py.GIL()) { PyObject s = new PyString("foo"); var t = new PyTuple(); - t.Concat(s); + Assert.Throws(() => t.Concat(s)); } } From 310d50d3da15f5ac748c19b58d60cd15ea5ccd89 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 9 Feb 2017 00:52:59 -0700 Subject: [PATCH 112/245] Use string interpolation Removed extra newline at beginning from deprecation warning message --- src/runtime/assemblymanager.cs | 7 +++---- src/runtime/classbase.cs | 3 +-- src/runtime/classderived.cs | 2 +- src/runtime/constructorbinding.cs | 3 +-- src/runtime/converter.cs | 21 +++++++-------------- src/runtime/moduleobject.cs | 3 ++- 6 files changed, 15 insertions(+), 24 deletions(-) diff --git a/src/runtime/assemblymanager.cs b/src/runtime/assemblymanager.cs index c86e7a473..06a4449a2 100644 --- a/src/runtime/assemblymanager.cs +++ b/src/runtime/assemblymanager.cs @@ -1,9 +1,9 @@ using System; using System.Collections; -using System.IO; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Reflection; using System.Threading; @@ -323,9 +323,8 @@ public static bool LoadImplicit(string name, bool warn = true) if (warn && loaded) { string location = Path.GetFileNameWithoutExtension(lastAssembly.Location); - string deprWarning = $@" -The module was found, but not in a referenced namespace. -Implicit loading is deprecated. Please use clr.AddReference(""{location}"")."; + string deprWarning = "The module was found, but not in a referenced namespace.\n" + + $"Implicit loading is deprecated. Please use clr.AddReference('{location}')."; Exceptions.deprecation(deprWarning); } diff --git a/src/runtime/classbase.cs b/src/runtime/classbase.cs index e480b309a..4dd3b5364 100644 --- a/src/runtime/classbase.cs +++ b/src/runtime/classbase.cs @@ -199,8 +199,7 @@ public static IntPtr tp_iter(IntPtr ob) if (o == null) { - var message = "iteration over non-sequence"; - return Exceptions.RaiseTypeError(message); + return Exceptions.RaiseTypeError("iteration over non-sequence"); } } diff --git a/src/runtime/classderived.cs b/src/runtime/classderived.cs index 0f8f156e8..c180f9acc 100644 --- a/src/runtime/classderived.cs +++ b/src/runtime/classderived.cs @@ -737,7 +737,7 @@ public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, s if (origMethodName == null) { - throw new NotImplementedException("Python object does not have a '" + methodName + "' method"); + throw new NotImplementedException($"Python object does not have a '{methodName}' method"); } obj.GetType().InvokeMember(origMethodName, diff --git a/src/runtime/constructorbinding.cs b/src/runtime/constructorbinding.cs index d17d6ac96..e756cd4d2 100644 --- a/src/runtime/constructorbinding.cs +++ b/src/runtime/constructorbinding.cs @@ -104,8 +104,7 @@ public static IntPtr mp_subscript(IntPtr op, IntPtr key) ConstructorInfo ci = self.type.GetConstructor(types); if (ci == null) { - var msg = "No match found for constructor signature"; - return Exceptions.RaiseTypeError(msg); + return Exceptions.RaiseTypeError("No match found for constructor signature"); } var boundCtor = new BoundContructor(self.type, self.pyTypeHndl, self.ctorBinder, ci); diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index fa5d73c86..3a3fa309d 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -1,9 +1,9 @@ using System; +using System.Collections; +using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; -using System.Globalization; using System.Security; -using System.Collections; namespace Python.Runtime { @@ -292,9 +292,7 @@ internal static bool ToManagedValue(IntPtr value, Type obType, result = tmp; return true; } - var err = "value cannot be converted to {0}"; - err = string.Format(err, obType); - Exceptions.SetError(Exceptions.TypeError, err); + Exceptions.SetError(Exceptions.TypeError, $"value cannot be converted to {obType}"); return false; } if (mt is ClassBase) @@ -793,10 +791,8 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo if (setError) { - var format = "'{0}' value cannot be converted to {1}"; string tpName = Runtime.PyObject_GetTypeName(value); - string error = string.Format(format, tpName, obType); - Exceptions.SetError(Exceptions.TypeError, error); + Exceptions.SetError(Exceptions.TypeError, $"'{tpName}' value cannot be converted to {obType}"); } return false; @@ -805,8 +801,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo if (setError) { - var error = "value too large to convert"; - Exceptions.SetError(Exceptions.OverflowError, error); + Exceptions.SetError(Exceptions.OverflowError, "value too large to convert"); } return false; @@ -818,8 +813,7 @@ private static void SetConversionError(IntPtr value, Type target) IntPtr ob = Runtime.PyObject_Repr(value); string src = Runtime.GetManagedString(ob); Runtime.XDecref(ob); - string error = string.Format("Cannot convert {0} to {1}", src, target); - Exceptions.SetError(Exceptions.TypeError, error); + Exceptions.SetError(Exceptions.TypeError, $"Cannot convert {src} to {target}"); } @@ -901,8 +895,7 @@ private static bool ToEnum(IntPtr value, Type obType, out object result, bool se if (setError) { - var error = "invalid enumeration value"; - Exceptions.SetError(Exceptions.ValueError, error); + Exceptions.SetError(Exceptions.ValueError, "invalid enumeration value"); } return false; diff --git a/src/runtime/moduleobject.cs b/src/runtime/moduleobject.cs index b324e6f3a..258d77bac 100644 --- a/src/runtime/moduleobject.cs +++ b/src/runtime/moduleobject.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Reflection; using System.Runtime.InteropServices; @@ -396,7 +397,7 @@ public static Assembly AddReference(string name) } if (assembly == null) { - throw new System.IO.FileNotFoundException($"Unable to find assembly '{name}'."); + throw new FileNotFoundException($"Unable to find assembly '{name}'."); } return assembly; From a2e8d46ced7d8ec6c6cf54ce7ec09bfe255e35d9 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 9 Feb 2017 14:49:47 -0700 Subject: [PATCH 113/245] Replace PyString_FromStringAndSize usage to PyString_FromString --- src/runtime/fieldobject.cs | 3 +-- src/runtime/methodbinding.cs | 4 ++-- src/runtime/methodobject.cs | 3 +-- src/runtime/modulefunctionobject.cs | 3 +-- src/runtime/propertyobject.cs | 3 +-- src/runtime/pyansistring.cs | 2 +- 6 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/runtime/fieldobject.cs b/src/runtime/fieldobject.cs index 96572e5a5..7c9a466d5 100644 --- a/src/runtime/fieldobject.cs +++ b/src/runtime/fieldobject.cs @@ -136,8 +136,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) public static IntPtr tp_repr(IntPtr ob) { var self = (FieldObject)GetManagedObject(ob); - string s = $""; - return Runtime.PyString_FromStringAndSize(s, s.Length); + return Runtime.PyString_FromString($""); } } } diff --git a/src/runtime/methodbinding.cs b/src/runtime/methodbinding.cs index 22b883186..df6632068 100644 --- a/src/runtime/methodbinding.cs +++ b/src/runtime/methodbinding.cs @@ -231,8 +231,8 @@ public static IntPtr tp_repr(IntPtr ob) { var self = (MethodBinding)GetManagedObject(ob); string type = self.target == IntPtr.Zero ? "unbound" : "bound"; - string s = string.Format("<{0} method '{1}'>", type, self.m.name); - return Runtime.PyString_FromStringAndSize(s, s.Length); + string name = self.m.name; + return Runtime.PyString_FromString($"<{type} method '{name}'>"); } /// diff --git a/src/runtime/methodobject.cs b/src/runtime/methodobject.cs index d2d821eb5..8df9c8029 100644 --- a/src/runtime/methodobject.cs +++ b/src/runtime/methodobject.cs @@ -187,8 +187,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) public static IntPtr tp_repr(IntPtr ob) { var self = (MethodObject)GetManagedObject(ob); - string s = string.Format("", self.name); - return Runtime.PyString_FromStringAndSize(s, s.Length); + return Runtime.PyString_FromString($""); } /// diff --git a/src/runtime/modulefunctionobject.cs b/src/runtime/modulefunctionobject.cs index aa4c8fb06..8f8692af9 100644 --- a/src/runtime/modulefunctionobject.cs +++ b/src/runtime/modulefunctionobject.cs @@ -33,8 +33,7 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) public new static IntPtr tp_repr(IntPtr ob) { var self = (ModuleFunctionObject)GetManagedObject(ob); - string s = $""; - return Runtime.PyString_FromStringAndSize(s, s.Length); + return Runtime.PyString_FromString($""); } } } diff --git a/src/runtime/propertyobject.cs b/src/runtime/propertyobject.cs index 7d758e38e..f2c97f163 100644 --- a/src/runtime/propertyobject.cs +++ b/src/runtime/propertyobject.cs @@ -158,8 +158,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) public static IntPtr tp_repr(IntPtr ob) { var self = (PropertyObject)GetManagedObject(ob); - string s = $""; - return Runtime.PyString_FromStringAndSize(s, s.Length); + return Runtime.PyString_FromString($""); } } } diff --git a/src/runtime/pyansistring.cs b/src/runtime/pyansistring.cs index 4973d8b2a..4843e5e2c 100644 --- a/src/runtime/pyansistring.cs +++ b/src/runtime/pyansistring.cs @@ -44,7 +44,7 @@ public PyAnsiString(PyObject o) /// public PyAnsiString(string s) { - obj = Runtime.PyString_FromStringAndSize(s, s.Length); + obj = Runtime.PyString_FromString(s); if (obj == IntPtr.Zero) { throw new PythonException(); From 54841da1d2a25bb58526bd58b45a13f312aad20e Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 13 Feb 2017 10:27:57 -0700 Subject: [PATCH 114/245] Fix xml-docs build warnings --- src/runtime/constructorbinding.cs | 9 +++------ src/runtime/exceptions.cs | 2 +- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/runtime/constructorbinding.cs b/src/runtime/constructorbinding.cs index e756cd4d2..4839f9913 100644 --- a/src/runtime/constructorbinding.cs +++ b/src/runtime/constructorbinding.cs @@ -82,14 +82,11 @@ public static IntPtr tp_descr_get(IntPtr op, IntPtr instance, IntPtr owner) /// /// Implement explicit overload selection using subscript syntax ([]). /// - /// + /// /// ConstructorBinding.GetItem(PyObject *o, PyObject *key) /// Return element of o corresponding to the object key or NULL on failure. /// This is the equivalent of the Python expression o[key]. - /// - /// - /// - /// + /// public static IntPtr mp_subscript(IntPtr op, IntPtr key) { var self = (ConstructorBinding)GetManagedObject(op); @@ -183,7 +180,7 @@ public BoundContructor(Type type, IntPtr pyTypeHndl, ConstructorBinder ctorBinde /// /// BoundContructor.__call__(PyObject *callable_object, PyObject *args, PyObject *kw) /// - /// PyObject *callable_object + /// PyObject *callable_object /// PyObject *args /// PyObject *kw /// A reference to a new instance of the class by invoking the selected ctor(). diff --git a/src/runtime/exceptions.cs b/src/runtime/exceptions.cs index b18cd7d69..21300f500 100644 --- a/src/runtime/exceptions.cs +++ b/src/runtime/exceptions.cs @@ -134,10 +134,10 @@ internal static void Shutdown() /// __getattr__ implementation, and thus dereferencing a NULL /// pointer. /// - /// A CLR exception /// The python object wrapping internal static void SetArgsAndCause(IntPtr ob) { + // e: A CLR Exception Exception e = ExceptionClassObject.ToException(ob); if (e == null) { From a5d325f79d599d1e38b7e62a8e13f15641520738 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 13 Feb 2017 14:46:17 -0700 Subject: [PATCH 115/245] Refactor AppVeyor/Travis embedded test_runner Make it easier to diff and upgrade versions by breaking into multiple lines and using path completion Powershell continuation: http://stackoverflow.com/a/2608186/5208670 Powershell options splatting: http://stackoverflow.com/a/24313253/5208670 --- .travis.yml | 2 +- ci/appveyor_run_tests.ps1 | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index fcb0f265e..fd462ea6a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,7 +35,7 @@ install: script: - export PYTHONPATH=`pwd`:$PYTHONPATH - python src/tests/runtests.py - # - mono ./packages/NUnit.Runners*/tools/nunit-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll + # - mono ./packages/NUnit.*/tools/nunit-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll after_success: # Uncomment if need to geninterop, ie. py37 final diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 index 300b2caa0..18005a047 100644 --- a/ci/appveyor_run_tests.ps1 +++ b/ci/appveyor_run_tests.ps1 @@ -3,7 +3,7 @@ # Executable paths for OpenCover # Note if OpenCover fails, it won't affect the exit codes. $OPENCOVER = Resolve-Path .\packages\OpenCover.*\tools\OpenCover.Console.exe -$NUNIT = Resolve-Path .\packages\NUnit.Runners*\tools\"$env:NUNIT".exe +$NUNIT = Resolve-Path .\packages\NUnit.*\tools\"$env:NUNIT".exe $PY = Get-Command python # Can't use ".\build\*\Python.EmbeddingTest.dll". Missing framework files. @@ -13,15 +13,22 @@ $RUNTIME_DIR = ".\src\runtime\bin\" # Run python tests with C# coverage # why `2>&1 | %{ "$_" }`? see: http://stackoverflow.com/a/20950421/5208670 Write-Host ("Starting Python tests") -ForegroundColor "Green" -.$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:py.coverage -target:"$PY" -targetargs:src\tests\runtests.py -returntargetcode 2>&1 | %{ "$_" } +.$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:py.coverage ` + -target:"$PY" -targetargs:src\tests\runtests.py ` + -returntargetcode ` + 2>&1 | %{ "$_" } $PYTHON_STATUS = $LastExitCode if ($PYTHON_STATUS -ne 0) { Write-Host "Python tests failed, continuing to embedded tests" -ForegroundColor "Red" } # Run Embedded tests with C# coverage +# Powershell continuation: http://stackoverflow.com/a/2608186/5208670 +# Powershell options splatting: http://stackoverflow.com/a/24313253/5208670 Write-Host ("Starting embedded tests") -ForegroundColor "Green" -.$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:cs.coverage -target:"$NUNIT" -targetargs:"$CS_TESTS" -returntargetcode +.$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:cs.coverage ` + -target:"$NUNIT" -targetargs:"$CS_TESTS" ` + -returntargetcode $NUNIT_STATUS = $LastExitCode if ($NUNIT_STATUS -ne 0) { Write-Host "Embedded tests failed" -ForegroundColor "Red" From ba7794b616ea810a457cdbd4728077d085105319 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 13 Jan 2017 12:09:52 -0700 Subject: [PATCH 116/245] Add pytest to CI pytest on travis initially required `sudo=required` otherwise failed. Without the sudo flag pytest wasn't being upgraded. Needed to force upgrade. https://github.com/pytest-dev/pytest/issues/2240 --- .travis.yml | 6 ++++-- appveyor.yml | 2 +- ci/appveyor_run_tests.ps1 | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index fd462ea6a..7043d4893 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,6 @@ sudo: false +# language: csharp installs mono/dotnet but has limited python. language: python python: - 2.7 @@ -29,12 +30,13 @@ addons: - ca-certificates-mono install: - - pip install pycparser coverage codecov + - pip install --upgrade pycparser coverage codecov pytest + # setup.py install works too, but need to deal w Python.test then - coverage run setup.py build_ext --inplace script: - export PYTHONPATH=`pwd`:$PYTHONPATH - - python src/tests/runtests.py + - python -m pytest # - mono ./packages/NUnit.*/tools/nunit-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll after_success: diff --git a/appveyor.yml b/appveyor.yml index fd5822ac9..6876bb442 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -48,7 +48,7 @@ init: install: # install for wheels & coverage - - pip install --upgrade pip wheel coverage codecov + - pip install --upgrade pip wheel coverage codecov pytest # Install OpenCover. Can't put on packages.config; not Linux/Mono compatible - .\tools\nuget\nuget.exe install OpenCover -OutputDirectory packages diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 index 18005a047..974114cdb 100644 --- a/ci/appveyor_run_tests.ps1 +++ b/ci/appveyor_run_tests.ps1 @@ -14,7 +14,7 @@ $RUNTIME_DIR = ".\src\runtime\bin\" # why `2>&1 | %{ "$_" }`? see: http://stackoverflow.com/a/20950421/5208670 Write-Host ("Starting Python tests") -ForegroundColor "Green" .$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:py.coverage ` - -target:"$PY" -targetargs:src\tests\runtests.py ` + -target:"$PY" -targetargs:"-m pytest" ` -returntargetcode ` 2>&1 | %{ "$_" } $PYTHON_STATUS = $LastExitCode From 1ea29c71a4b1fec28fc90d9c4deff1305e5d7cdb Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 14 Jan 2017 20:10:27 -0700 Subject: [PATCH 117/245] Convert unittest to pytest Needs local imports to work. Conversion done with unittests2pytests and a couple regex --- src/tests/_compat.py | 2 +- src/tests/{test_suite => }/_missing_import.py | 0 src/tests/conftest.py | 57 + src/tests/leaktest.py | 8 +- src/tests/profile.py | 2 +- src/tests/runtests.py | 62 +- src/tests/stress.py | 4 +- src/tests/stresstest.py | 2 +- src/tests/test_array.py | 2115 +++++++++-------- src/tests/test_callback.py | 27 + src/tests/test_class.py | 391 +-- src/tests/test_compat.py | 438 ++-- src/tests/test_constructors.py | 62 +- src/tests/test_conversion.py | 979 ++++---- src/tests/test_delegate.py | 365 +-- src/tests/test_docstring.py | 37 +- src/tests/test_engine.py | 59 +- src/tests/test_enum.py | 271 ++- src/tests/test_event.py | 789 +++--- src/tests/test_exceptions.py | 523 ++-- src/tests/test_field.py | 541 +++-- src/tests/test_generic.py | 1525 ++++++------ src/tests/test_import.py | 13 + src/tests/test_indexer.py | 802 ++++--- src/tests/test_interface.py | 93 +- src/tests/test_method.py | 1238 +++++----- src/tests/test_module.py | 647 ++--- src/tests/test_property.py | 201 +- src/tests/test_recursive_types.py | 12 + src/tests/test_subclass.py | 223 +- src/tests/test_suite/__init__.py | 15 - src/tests/test_suite/test_callback.py | 33 - src/tests/test_suite/test_import.py | 18 - src/tests/test_suite/test_recursive_types.py | 19 - src/tests/test_sysargv.py | 19 +- src/tests/test_thread.py | 88 +- src/tests/utils.py | 2 +- 37 files changed, 5937 insertions(+), 5745 deletions(-) rename src/tests/{test_suite => }/_missing_import.py (100%) create mode 100644 src/tests/conftest.py create mode 100644 src/tests/test_callback.py create mode 100644 src/tests/test_import.py create mode 100644 src/tests/test_recursive_types.py delete mode 100644 src/tests/test_suite/__init__.py delete mode 100644 src/tests/test_suite/test_callback.py delete mode 100644 src/tests/test_suite/test_import.py delete mode 100644 src/tests/test_suite/test_recursive_types.py diff --git a/src/tests/_compat.py b/src/tests/_compat.py index 3a9d48c7e..178777e4a 100644 --- a/src/tests/_compat.py +++ b/src/tests/_compat.py @@ -33,7 +33,7 @@ unicode = str # from nowhere import Nothing - cmp = lambda a, b: (a > b) - (a < b) # No Py3 equivalent + cmp = lambda a, b: (a > b) - (a < b) # No PY3 equivalent map = map range = range zip = zip diff --git a/src/tests/test_suite/_missing_import.py b/src/tests/_missing_import.py similarity index 100% rename from src/tests/test_suite/_missing_import.py rename to src/tests/_missing_import.py diff --git a/src/tests/conftest.py b/src/tests/conftest.py new file mode 100644 index 000000000..85fff291f --- /dev/null +++ b/src/tests/conftest.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# TODO: move tests one out of src. Pythonnet doesn't run... + +"""Helpers for testing.""" + +import io +import os +import sys + +import pytest +import clr + +sys.path.append('C:/testdir/') +clr.AddReference("Python.Test") +clr.AddReference("System.Collections") +clr.AddReference("System.Data") + +DIR_PATH = os.path.dirname(__file__) +FILES_DIR = os.path.join(DIR_PATH, 'files') + + +@pytest.fixture() +def filepath(): + """Returns full file path for test files.""" + + def make_filepath(filename): + # http://stackoverflow.com/questions/18011902/parameter-to-a-fixture + # Alternate solution is to use paramtrization `inderect=True` + # http://stackoverflow.com/a/33879151 + # Syntax is noisy and requires specific variable names + return os.path.join(FILES_DIR, filename) + + return make_filepath + + +@pytest.fixture() +def load_file(filepath): + """Opens filename with encoding and return its contents.""" + + def make_load_file(filename, encoding='utf-8'): + # http://stackoverflow.com/questions/18011902/parameter-to-a-fixture + # Alternate solution is to use paramtrization `inderect=True` + # http://stackoverflow.com/a/33879151 + # Syntax is noisy and requires specific variable names + # And seems to be limited to only 1 argument. + with io.open(filepath(filename), encoding=encoding) as f: + return f.read().strip() + + return make_load_file + + +@pytest.fixture() +def get_stream(filepath): + def make_stream(filename, encoding='utf-8'): + return io.open(filepath(filename), encoding=encoding) + + return make_stream diff --git a/src/tests/leaktest.py b/src/tests/leaktest.py index 646cb512e..05b76e867 100644 --- a/src/tests/leaktest.py +++ b/src/tests/leaktest.py @@ -10,10 +10,10 @@ import System -from _compat import range -from utils import (CallableHandler, ClassMethodHandler, GenericHandler, - HelloClass, StaticMethodHandler, VarCallableHandler, - VariableArgsHandler, hello_func) +from ._compat import range +from .utils import (CallableHandler, ClassMethodHandler, GenericHandler, + HelloClass, StaticMethodHandler, VarCallableHandler, + VariableArgsHandler, hello_func) class LeakTest(object): diff --git a/src/tests/profile.py b/src/tests/profile.py index f6576ddce..4af3589e8 100644 --- a/src/tests/profile.py +++ b/src/tests/profile.py @@ -14,7 +14,7 @@ import time import runtests -from _compat import range +from ._compat import range def main(): diff --git a/src/tests/runtests.py b/src/tests/runtests.py index 92d9ecbd0..8011d05e6 100644 --- a/src/tests/runtests.py +++ b/src/tests/runtests.py @@ -5,11 +5,10 @@ from __future__ import print_function -import os import sys -import unittest +import pytest -from _compat import input +from ._compat import input try: import System @@ -22,63 +21,16 @@ clr.AddReference("System.Data") clr.AddReference("System.Management") -test_modules = ( - # has to be first test before other module import clr - 'test_sysargv', - + +def main(verbosity=1): # test_module passes on its own, but not here if # other test modules that import System.Windows.Forms # run first. They must not do module level import/AddReference() # of the System.Windows.Forms namespace. - 'test_module', - - 'test_suite', - 'test_event', - 'test_constructors', - 'test_enum', - 'test_method', - 'test_exceptions', - 'test_compat', - 'test_generic', - 'test_conversion', - 'test_class', - 'test_interface', - 'test_field', - 'test_property', - 'test_indexer', - 'test_delegate', - 'test_array', - 'test_thread', - 'test_docstring', - - # FIXME: Has tests that are being skipped. - 'test_engine', - - # FIXME: Has tests that are being skipped. - 'test_subclass', -) - - -def remove_pyc(): - path = os.path.dirname(os.path.abspath(__file__)) - for name in test_modules: - pyc = os.path.join(path, "{0}.pyc".format(name)) - if os.path.isfile(pyc): - os.unlink(pyc) - - -def main(verbosity=1): - remove_pyc() - - suite = unittest.TestSuite() - - for name in test_modules: - module = __import__(name) - suite.addTests((module.test_suite(),)) - result = unittest.TextTestRunner(verbosity=verbosity).run(suite) - if not result.wasSuccessful(): - raise Exception("Tests failed") + # FIXME: test_engine has tests that are being skipped. + # FIXME: test_subclass has tests that are being skipped. + pytest.main() if __name__ == '__main__': diff --git a/src/tests/stress.py b/src/tests/stress.py index 2ffe06958..c6fa8b7e3 100644 --- a/src/tests/stress.py +++ b/src/tests/stress.py @@ -17,8 +17,8 @@ import threading import time -from _compat import range, thread -from utils import dprint +from ._compat import range, thread +from .utils import dprint class StressTest(object): diff --git a/src/tests/stresstest.py b/src/tests/stresstest.py index 947959239..74b863bdc 100644 --- a/src/tests/stresstest.py +++ b/src/tests/stresstest.py @@ -11,7 +11,7 @@ import unittest # import pdb -from _compat import range +from ._compat import range try: import System diff --git a/src/tests/test_array.py b/src/tests/test_array.py index 36f225c82..7ccadddff 100644 --- a/src/tests/test_array.py +++ b/src/tests/test_array.py @@ -1,1306 +1,1339 @@ # -*- coding: utf-8 -*- -import unittest +"""Test support for managed arrays.""" import Python.Test as Test import System +import pytest -from _compat import PY2, UserList, long, range, unichr +from ._compat import PY2, UserList, long, range, unichr -class ArrayTests(unittest.TestCase): - """Test support for managed arrays.""" +def test_public_array(): + """Test public arrays.""" + ob = Test.PublicArrayTest() + items = ob.items - def test_public_array(self): - """Test public arrays.""" - ob = Test.PublicArrayTest() - items = ob.items + assert len(items) == 5 - self.assertTrue(len(items) == 5) + assert items[0] == 0 + assert items[4] == 4 - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) + items[0] = 8 + assert items[0] == 8 - items[0] = 8 - self.assertTrue(items[0] == 8) + items[4] = 9 + assert items[4] == 9 - items[4] = 9 - self.assertTrue(items[4] == 9) + items[-4] = 0 + assert items[-4] == 0 - items[-4] = 0 - self.assertTrue(items[-4] == 0) + items[-1] = 4 + assert items[-1] == 4 - items[-1] = 4 - self.assertTrue(items[-1] == 4) - def test_protected_array(self): - """Test protected arrays.""" - ob = Test.ProtectedArrayTest() - items = ob.items +def test_protected_array(): + """Test protected arrays.""" + ob = Test.ProtectedArrayTest() + items = ob.items - self.assertTrue(len(items) == 5) + assert len(items) == 5 - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) + assert items[0] == 0 + assert items[4] == 4 - items[0] = 8 - self.assertTrue(items[0] == 8) + items[0] = 8 + assert items[0] == 8 - items[4] = 9 - self.assertTrue(items[4] == 9) + items[4] = 9 + assert items[4] == 9 - items[-4] = 0 - self.assertTrue(items[-4] == 0) + items[-4] = 0 + assert items[-4] == 0 - items[-1] = 4 - self.assertTrue(items[-1] == 4) + items[-1] = 4 + assert items[-1] == 4 - def test_internal_array(self): - """Test internal arrays.""" - with self.assertRaises(AttributeError): - ob = Test.InternalArrayTest() - _ = ob.items +def test_internal_array(): + """Test internal arrays.""" - def test_private_array(self): - """Test private arrays.""" + with pytest.raises(AttributeError): + ob = Test.InternalArrayTest() + _ = ob.items - with self.assertRaises(AttributeError): - ob = Test.PrivateArrayTest() - _ = ob.items - def test_array_bounds_checking(self): - """Test array bounds checking.""" +def test_private_array(): + """Test private arrays.""" - ob = Test.Int32ArrayTest() - items = ob.items + with pytest.raises(AttributeError): + ob = Test.PrivateArrayTest() + _ = ob.items - self.assertTrue(items[0] == 0) - self.assertTrue(items[1] == 1) - self.assertTrue(items[2] == 2) - self.assertTrue(items[3] == 3) - self.assertTrue(items[4] == 4) - self.assertTrue(items[-5] == 0) - self.assertTrue(items[-4] == 1) - self.assertTrue(items[-3] == 2) - self.assertTrue(items[-2] == 3) - self.assertTrue(items[-1] == 4) +def test_array_bounds_checking(): + """Test array bounds checking.""" - with self.assertRaises(IndexError): - ob = Test.Int32ArrayTest() - _ = ob.items[5] + ob = Test.Int32ArrayTest() + items = ob.items - with self.assertRaises(IndexError): - ob = Test.Int32ArrayTest() - ob.items[5] = 0 + assert items[0] == 0 + assert items[1] == 1 + assert items[2] == 2 + assert items[3] == 3 + assert items[4] == 4 - with self.assertRaises(IndexError): - ob = Test.Int32ArrayTest() - items[-6] + assert items[-5] == 0 + assert items[-4] == 1 + assert items[-3] == 2 + assert items[-2] == 3 + assert items[-1] == 4 - with self.assertRaises(IndexError): - ob = Test.Int32ArrayTest() - items[-6] = 0 + with pytest.raises(IndexError): + ob = Test.Int32ArrayTest() + _ = ob.items[5] - def test_array_contains(self): - """Test array support for __contains__.""" + with pytest.raises(IndexError): + ob = Test.Int32ArrayTest() + ob.items[5] = 0 + + with pytest.raises(IndexError): + ob = Test.Int32ArrayTest() + items[-6] + with pytest.raises(IndexError): ob = Test.Int32ArrayTest() - items = ob.items + items[-6] = 0 - self.assertTrue(0 in items) - self.assertTrue(1 in items) - self.assertTrue(2 in items) - self.assertTrue(3 in items) - self.assertTrue(4 in items) - self.assertFalse(5 in items) # "H:\Python27\Lib\unittest\case.py", line 592, in deprecated_func, - self.assertFalse(-1 in items) # TypeError: int() argument must be a string or a number, not 'NoneType' - self.assertFalse(None in items) # which threw ^ here which is a little odd. - # But when run from runtests.py. Not when this module ran by itself. +def test_array_contains(): + """Test array support for __contains__.""" - def test_boolean_array(self): - """Test boolean arrays.""" - ob = Test.BooleanArrayTest() - items = ob.items + ob = Test.Int32ArrayTest() + items = ob.items - self.assertTrue(len(items) == 5) + assert 0 in items + assert 1 in items + assert 2 in items + assert 3 in items + assert 4 in items - self.assertTrue(items[0] is True) - self.assertTrue(items[1] is False) - self.assertTrue(items[2] is True) - self.assertTrue(items[3] is False) - self.assertTrue(items[4] is True) + 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. + # But when run from runtests.py. Not when this module ran by itself. - items[0] = False - self.assertTrue(items[0] is False) - items[0] = True - self.assertTrue(items[0] is True) +def test_boolean_array(): + """Test boolean arrays.""" + ob = Test.BooleanArrayTest() + items = ob.items - with self.assertRaises(TypeError): - ob = Test.ByteArrayTest() - _ = ob.items["wrong"] + assert len(items) == 5 - with self.assertRaises(TypeError): - ob = Test.ByteArrayTest() - ob[0] = "wrong" + assert items[0] is True + assert items[1] is False + assert items[2] is True + assert items[3] is False + assert items[4] is True + + items[0] = False + assert items[0] is False + + items[0] = True + assert items[0] is True + + with pytest.raises(TypeError): + ob = Test.ByteArrayTest() + _ = ob.items["wrong"] - def test_byte_array(self): - """Test byte arrays.""" + with pytest.raises(TypeError): ob = Test.ByteArrayTest() - items = ob.items + ob[0] = "wrong" - self.assertTrue(len(items) == 5) - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) +def test_byte_array(): + """Test byte arrays.""" + ob = Test.ByteArrayTest() + items = ob.items - max_ = 255 - min_ = 0 + assert len(items) == 5 - items[0] = max_ - self.assertTrue(items[0] == max_) + assert items[0] == 0 + assert items[4] == 4 - items[0] = min_ - self.assertTrue(items[0] == min_) + max_ = 255 + min_ = 0 - items[-4] = max_ - self.assertTrue(items[-4] == max_) + items[0] = max_ + assert items[0] == max_ - items[-1] = min_ - self.assertTrue(items[-1] == min_) + items[0] = min_ + assert items[0] == min_ - with self.assertRaises(OverflowError): - ob = Test.ByteArrayTest() - ob.items[0] = max_ + 1 + items[-4] = max_ + assert items[-4] == max_ - with self.assertRaises(OverflowError): - ob = Test.ByteArrayTest() - ob.items[0] = min_ - 1 + items[-1] = min_ + assert items[-1] == min_ + + with pytest.raises(OverflowError): + ob = Test.ByteArrayTest() + ob.items[0] = max_ + 1 + + with pytest.raises(OverflowError): + ob = Test.ByteArrayTest() + ob.items[0] = min_ - 1 + + with pytest.raises(TypeError): + ob = Test.ByteArrayTest() + _ = ob.items["wrong"] + + with pytest.raises(TypeError): + ob = Test.ByteArrayTest() + ob[0] = "wrong" - with self.assertRaises(TypeError): - ob = Test.ByteArrayTest() - _ = ob.items["wrong"] - with self.assertRaises(TypeError): - ob = Test.ByteArrayTest() - ob[0] = "wrong" +def test_sbyte_array(): + """Test sbyte arrays.""" + ob = Test.SByteArrayTest() + items = ob.items - def test_sbyte_array(self): - """Test sbyte arrays.""" + assert len(items) == 5 + + assert items[0] == 0 + assert items[4] == 4 + + max_ = 127 + min_ = -128 + + items[0] = max_ + assert items[0] == max_ + + items[0] = min_ + assert items[0] == min_ + + items[-4] = max_ + assert items[-4] == max_ + + items[-1] = min_ + assert items[-1] == min_ + + with pytest.raises(OverflowError): + ob = Test.SByteArrayTest() + ob.items[0] = max_ + 1 + + with pytest.raises(OverflowError): + ob = Test.SByteArrayTest() + ob.items[0] = min_ - 1 + + with pytest.raises(TypeError): ob = Test.SByteArrayTest() - items = ob.items + _ = ob.items["wrong"] - self.assertTrue(len(items) == 5) + with pytest.raises(TypeError): + ob = Test.SByteArrayTest() + ob[0] = "wrong" - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) - max_ = 127 - min_ = -128 +def test_char_array(): + """Test char arrays.""" + ob = Test.CharArrayTest() + items = ob.items - items[0] = max_ - self.assertTrue(items[0] == max_) + assert len(items) == 5 - items[0] = min_ - self.assertTrue(items[0] == min_) + assert items[0] == 'a' + assert items[4] == 'e' - items[-4] = max_ - self.assertTrue(items[-4] == max_) + max_ = unichr(65535) + min_ = unichr(0) - items[-1] = min_ - self.assertTrue(items[-1] == min_) + items[0] = max_ + assert items[0] == max_ - with self.assertRaises(OverflowError): - ob = Test.SByteArrayTest() - ob.items[0] = max_ + 1 + items[0] = min_ + assert items[0] == min_ - with self.assertRaises(OverflowError): - ob = Test.SByteArrayTest() - ob.items[0] = min_ - 1 + items[-4] = max_ + assert items[-4] == max_ - with self.assertRaises(TypeError): - ob = Test.SByteArrayTest() - _ = ob.items["wrong"] + items[-1] = min_ + assert items[-1] == min_ - with self.assertRaises(TypeError): - ob = Test.SByteArrayTest() - ob[0] = "wrong" + with pytest.raises(TypeError): + ob = Test.CharArrayTest() + _ = ob.items["wrong"] - def test_char_array(self): - """Test char arrays.""" + with pytest.raises(TypeError): ob = Test.CharArrayTest() - items = ob.items + ob[0] = "wrong" + + +def test_int16_array(): + """Test Int16 arrays.""" + ob = Test.Int16ArrayTest() + items = ob.items + + assert len(items) == 5 - self.assertTrue(len(items) == 5) + assert items[0] == 0 + assert items[4] == 4 - self.assertTrue(items[0] == 'a') - self.assertTrue(items[4] == 'e') + max_ = 32767 + min_ = -32768 - max_ = unichr(65535) - min_ = unichr(0) + items[0] = max_ + assert items[0] == max_ - items[0] = max_ - self.assertTrue(items[0] == max_) + items[0] = min_ + assert items[0] == min_ - items[0] = min_ - self.assertTrue(items[0] == min_) + items[-4] = max_ + assert items[-4] == max_ - items[-4] = max_ - self.assertTrue(items[-4] == max_) + items[-1] = min_ + assert items[-1] == min_ - items[-1] = min_ - self.assertTrue(items[-1] == min_) + with pytest.raises(OverflowError): + ob = Test.Int16ArrayTest() + ob.items[0] = max_ + 1 - with self.assertRaises(TypeError): - ob = Test.CharArrayTest() - _ = ob.items["wrong"] + with pytest.raises(OverflowError): + ob = Test.Int16ArrayTest() + ob.items[0] = min_ - 1 - with self.assertRaises(TypeError): - ob = Test.CharArrayTest() - ob[0] = "wrong" + with pytest.raises(TypeError): + ob = Test.Int16ArrayTest() + _ = ob.items["wrong"] - def test_int16_array(self): - """Test Int16 arrays.""" + with pytest.raises(TypeError): ob = Test.Int16ArrayTest() - items = ob.items + ob[0] = "wrong" - self.assertTrue(len(items) == 5) - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) +def test_int32_array(): + """Test Int32 arrays.""" + ob = Test.Int32ArrayTest() + items = ob.items - max_ = 32767 - min_ = -32768 + assert len(items) == 5 - items[0] = max_ - self.assertTrue(items[0] == max_) + assert items[0] == 0 + assert items[4] == 4 - items[0] = min_ - self.assertTrue(items[0] == min_) + max_ = 2147483647 + min_ = -2147483648 - items[-4] = max_ - self.assertTrue(items[-4] == max_) + items[0] = max_ + assert items[0] == max_ - items[-1] = min_ - self.assertTrue(items[-1] == min_) + items[0] = min_ + assert items[0] == min_ - with self.assertRaises(OverflowError): - ob = Test.Int16ArrayTest() - ob.items[0] = max_ + 1 + items[-4] = max_ + assert items[-4] == max_ - with self.assertRaises(OverflowError): - ob = Test.Int16ArrayTest() - ob.items[0] = min_ - 1 + items[-1] = min_ + assert items[-1] == min_ - with self.assertRaises(TypeError): - ob = Test.Int16ArrayTest() - _ = ob.items["wrong"] + with pytest.raises(OverflowError): + ob = Test.Int32ArrayTest() + ob.items[0] = max_ + 1 - with self.assertRaises(TypeError): - ob = Test.Int16ArrayTest() - ob[0] = "wrong" + with pytest.raises(OverflowError): + ob = Test.Int32ArrayTest() + ob.items[0] = min_ - 1 - def test_int32_array(self): - """Test Int32 arrays.""" + with pytest.raises(TypeError): ob = Test.Int32ArrayTest() - items = ob.items + _ = ob.items["wrong"] - self.assertTrue(len(items) == 5) + with pytest.raises(TypeError): + ob = Test.Int32ArrayTest() + ob[0] = "wrong" - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) - max_ = 2147483647 - min_ = -2147483648 +def test_int64_array(): + """Test Int64 arrays.""" + ob = Test.Int64ArrayTest() + items = ob.items - items[0] = max_ - self.assertTrue(items[0] == max_) + assert len(items) == 5 - items[0] = min_ - self.assertTrue(items[0] == min_) + assert items[0] == 0 + assert items[4] == 4 - items[-4] = max_ - self.assertTrue(items[-4] == max_) + max_ = long(9223372036854775807) + min_ = long(-9223372036854775808) - items[-1] = min_ - self.assertTrue(items[-1] == min_) + items[0] = max_ + assert items[0] == max_ - with self.assertRaises(OverflowError): - ob = Test.Int32ArrayTest() - ob.items[0] = max_ + 1 + items[0] = min_ + assert items[0] == min_ - with self.assertRaises(OverflowError): - ob = Test.Int32ArrayTest() - ob.items[0] = min_ - 1 + items[-4] = max_ + assert items[-4] == max_ - with self.assertRaises(TypeError): - ob = Test.Int32ArrayTest() - _ = ob.items["wrong"] + items[-1] = min_ + assert items[-1] == min_ - with self.assertRaises(TypeError): - ob = Test.Int32ArrayTest() - ob[0] = "wrong" + with pytest.raises(OverflowError): + ob = Test.Int64ArrayTest() + ob.items[0] = max_ + 1 - def test_int64_array(self): - """Test Int64 arrays.""" + with pytest.raises(OverflowError): ob = Test.Int64ArrayTest() - items = ob.items + ob.items[0] = min_ - 1 - self.assertTrue(len(items) == 5) + with pytest.raises(TypeError): + ob = Test.Int64ArrayTest() + _ = ob.items["wrong"] - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) + with pytest.raises(TypeError): + ob = Test.Int64ArrayTest() + ob[0] = "wrong" - max_ = long(9223372036854775807) - min_ = long(-9223372036854775808) - items[0] = max_ - self.assertTrue(items[0] == max_) +def test_uint16_array(): + """Test UInt16 arrays.""" + ob = Test.UInt16ArrayTest() + items = ob.items - items[0] = min_ - self.assertTrue(items[0] == min_) + assert len(items) == 5 - items[-4] = max_ - self.assertTrue(items[-4] == max_) + assert items[0] == 0 + assert items[4] == 4 - items[-1] = min_ - self.assertTrue(items[-1] == min_) + max_ = 65535 + min_ = 0 - with self.assertRaises(OverflowError): - ob = Test.Int64ArrayTest() - ob.items[0] = max_ + 1 + items[0] = max_ + assert items[0] == max_ - with self.assertRaises(OverflowError): - ob = Test.Int64ArrayTest() - ob.items[0] = min_ - 1 + items[0] = min_ + assert items[0] == min_ - with self.assertRaises(TypeError): - ob = Test.Int64ArrayTest() - _ = ob.items["wrong"] + items[-4] = max_ + assert items[-4] == max_ - with self.assertRaises(TypeError): - ob = Test.Int64ArrayTest() - ob[0] = "wrong" + items[-1] = min_ + assert items[-1] == min_ - def test_uint16_array(self): - """Test UInt16 arrays.""" + with pytest.raises(OverflowError): ob = Test.UInt16ArrayTest() - items = ob.items + ob.items[0] = max_ + 1 - self.assertTrue(len(items) == 5) + with pytest.raises(OverflowError): + ob = Test.UInt16ArrayTest() + ob.items[0] = min_ - 1 + + with pytest.raises(TypeError): + ob = Test.UInt16ArrayTest() + _ = ob.items["wrong"] + + with pytest.raises(TypeError): + ob = Test.UInt16ArrayTest() + ob[0] = "wrong" - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) - max_ = 65535 - min_ = 0 +def test_uint32_array(): + """Test UInt32 arrays.""" + ob = Test.UInt32ArrayTest() + items = ob.items - items[0] = max_ - self.assertTrue(items[0] == max_) + assert len(items) == 5 - items[0] = min_ - self.assertTrue(items[0] == min_) + assert items[0] == 0 + assert items[4] == 4 - items[-4] = max_ - self.assertTrue(items[-4] == max_) + max_ = long(4294967295) + min_ = 0 - items[-1] = min_ - self.assertTrue(items[-1] == min_) + items[0] = max_ + assert items[0] == max_ - with self.assertRaises(OverflowError): - ob = Test.UInt16ArrayTest() - ob.items[0] = max_ + 1 + items[0] = min_ + assert items[0] == min_ - with self.assertRaises(OverflowError): - ob = Test.UInt16ArrayTest() - ob.items[0] = min_ - 1 + items[-4] = max_ + assert items[-4] == max_ - with self.assertRaises(TypeError): - ob = Test.UInt16ArrayTest() - _ = ob.items["wrong"] + items[-1] = min_ + assert items[-1] == min_ - with self.assertRaises(TypeError): - ob = Test.UInt16ArrayTest() - ob[0] = "wrong" + with pytest.raises(OverflowError): + ob = Test.UInt32ArrayTest() + ob.items[0] = max_ + 1 - def test_uint32_array(self): - """Test UInt32 arrays.""" + with pytest.raises(OverflowError): ob = Test.UInt32ArrayTest() - items = ob.items + ob.items[0] = min_ - 1 - self.assertTrue(len(items) == 5) + with pytest.raises(TypeError): + ob = Test.UInt32ArrayTest() + _ = ob.items["wrong"] - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) + with pytest.raises(TypeError): + ob = Test.UInt32ArrayTest() + ob[0] = "wrong" - max_ = long(4294967295) - min_ = 0 - items[0] = max_ - self.assertTrue(items[0] == max_) +def test_uint64_array(): + """Test UInt64 arrays.""" + ob = Test.UInt64ArrayTest() + items = ob.items - items[0] = min_ - self.assertTrue(items[0] == min_) + assert len(items) == 5 - items[-4] = max_ - self.assertTrue(items[-4] == max_) + assert items[0] == 0 + assert items[4] == 4 - items[-1] = min_ - self.assertTrue(items[-1] == min_) + max_ = long(18446744073709551615) + min_ = 0 - with self.assertRaises(OverflowError): - ob = Test.UInt32ArrayTest() - ob.items[0] = max_ + 1 + items[0] = max_ + assert items[0] == max_ - with self.assertRaises(OverflowError): - ob = Test.UInt32ArrayTest() - ob.items[0] = min_ - 1 + items[0] = min_ + assert items[0] == min_ - with self.assertRaises(TypeError): - ob = Test.UInt32ArrayTest() - _ = ob.items["wrong"] + items[-4] = max_ + assert items[-4] == max_ - with self.assertRaises(TypeError): - ob = Test.UInt32ArrayTest() - ob[0] = "wrong" + items[-1] = min_ + assert items[-1] == min_ - def test_uint64_array(self): - """Test UInt64 arrays.""" + with pytest.raises(OverflowError): ob = Test.UInt64ArrayTest() - items = ob.items + ob.items[0] = max_ + 1 - self.assertTrue(len(items) == 5) + with pytest.raises(OverflowError): + ob = Test.UInt64ArrayTest() + ob.items[0] = min_ - 1 + + with pytest.raises(TypeError): + ob = Test.UInt64ArrayTest() + _ = ob.items["wrong"] + + with pytest.raises(TypeError): + ob = Test.UInt64ArrayTest() + ob[0] = "wrong" - self.assertTrue(items[0] == 0) - self.assertTrue(items[4] == 4) - max_ = long(18446744073709551615) - min_ = 0 +def test_single_array(): + """Test Single arrays.""" + ob = Test.SingleArrayTest() + items = ob.items - items[0] = max_ - self.assertTrue(items[0] == max_) + assert len(items) == 5 - items[0] = min_ - self.assertTrue(items[0] == min_) + assert items[0] == 0.0 + assert items[4] == 4.0 - items[-4] = max_ - self.assertTrue(items[-4] == max_) + max_ = 3.402823e38 + min_ = -3.402823e38 - items[-1] = min_ - self.assertTrue(items[-1] == min_) + items[0] = max_ + assert items[0] == max_ - with self.assertRaises(OverflowError): - ob = Test.UInt64ArrayTest() - ob.items[0] = max_ + 1 + items[0] = min_ + assert items[0] == min_ - with self.assertRaises(OverflowError): - ob = Test.UInt64ArrayTest() - ob.items[0] = min_ - 1 + items[-4] = max_ + assert items[-4] == max_ - with self.assertRaises(TypeError): - ob = Test.UInt64ArrayTest() - _ = ob.items["wrong"] + items[-1] = min_ + assert items[-1] == min_ - with self.assertRaises(TypeError): - ob = Test.UInt64ArrayTest() - ob[0] = "wrong" + with pytest.raises(TypeError): + ob = Test.SingleArrayTest() + _ = ob.items["wrong"] - def test_single_array(self): - """Test Single arrays.""" + with pytest.raises(TypeError): ob = Test.SingleArrayTest() - items = ob.items + ob[0] = "wrong" - self.assertTrue(len(items) == 5) - self.assertTrue(items[0] == 0.0) - self.assertTrue(items[4] == 4.0) +def test_double_array(): + """Test Double arrays.""" + ob = Test.DoubleArrayTest() + items = ob.items - max_ = 3.402823e38 - min_ = -3.402823e38 + assert len(items) == 5 - items[0] = max_ - self.assertTrue(items[0] == max_) + assert items[0] == 0.0 + assert items[4] == 4.0 - items[0] = min_ - self.assertTrue(items[0] == min_) + max_ = 1.7976931348623157e308 + min_ = -1.7976931348623157e308 - items[-4] = max_ - self.assertTrue(items[-4] == max_) + items[0] = max_ + assert items[0] == max_ - items[-1] = min_ - self.assertTrue(items[-1] == min_) + items[0] = min_ + assert items[0] == min_ - with self.assertRaises(TypeError): - ob = Test.SingleArrayTest() - _ = ob.items["wrong"] + items[-4] = max_ + assert items[-4] == max_ - with self.assertRaises(TypeError): - ob = Test.SingleArrayTest() - ob[0] = "wrong" + items[-1] = min_ + assert items[-1] == min_ + + with pytest.raises(TypeError): + ob = Test.DoubleArrayTest() + _ = ob.items["wrong"] - def test_double_array(self): - """Test Double arrays.""" + with pytest.raises(TypeError): ob = Test.DoubleArrayTest() - items = ob.items + ob[0] = "wrong" - self.assertTrue(len(items) == 5) - self.assertTrue(items[0] == 0.0) - self.assertTrue(items[4] == 4.0) +def test_decimal_array(): + """Test Decimal arrays.""" + ob = Test.DecimalArrayTest() + items = ob.items - max_ = 1.7976931348623157e308 - min_ = -1.7976931348623157e308 + from System import Decimal + max_d = Decimal.Parse("79228162514264337593543950335") + min_d = Decimal.Parse("-79228162514264337593543950335") - items[0] = max_ - self.assertTrue(items[0] == max_) + assert len(items) == 5 - items[0] = min_ - self.assertTrue(items[0] == min_) + assert items[0] == Decimal(0) + assert items[4] == Decimal(4) - items[-4] = max_ - self.assertTrue(items[-4] == max_) + items[0] = max_d + assert items[0] == max_d - items[-1] = min_ - self.assertTrue(items[-1] == min_) + items[0] = min_d + assert items[0] == min_d - with self.assertRaises(TypeError): - ob = Test.DoubleArrayTest() - _ = ob.items["wrong"] + items[-4] = max_d + assert items[-4] == max_d - with self.assertRaises(TypeError): - ob = Test.DoubleArrayTest() - ob[0] = "wrong" + items[-1] = min_d + assert items[-1] == min_d - def test_decimal_array(self): - """Test Decimal arrays.""" + with pytest.raises(TypeError): ob = Test.DecimalArrayTest() - items = ob.items + _ = ob.items["wrong"] - from System import Decimal - max_d = Decimal.Parse("79228162514264337593543950335") - min_d = Decimal.Parse("-79228162514264337593543950335") + with pytest.raises(TypeError): + ob = Test.DecimalArrayTest() + ob[0] = "wrong" - self.assertTrue(len(items) == 5) - self.assertTrue(items[0] == Decimal(0)) - self.assertTrue(items[4] == Decimal(4)) +def test_string_array(): + """Test String arrays.""" + ob = Test.StringArrayTest() + items = ob.items - items[0] = max_d - self.assertTrue(items[0] == max_d) + assert len(items) == 5 - items[0] = min_d - self.assertTrue(items[0] == min_d) + assert items[0] == '0' + assert items[4] == '4' - items[-4] = max_d - self.assertTrue(items[-4] == max_d) + items[0] = "spam" + assert items[0] == "spam" - items[-1] = min_d - self.assertTrue(items[-1] == min_d) + items[0] = "eggs" + assert items[0] == "eggs" - with self.assertRaises(TypeError): - ob = Test.DecimalArrayTest() - _ = ob.items["wrong"] + items[-4] = "spam" + assert items[-4] == "spam" - with self.assertRaises(TypeError): - ob = Test.DecimalArrayTest() - ob[0] = "wrong" + items[-1] = "eggs" + assert items[-1] == "eggs" - def test_string_array(self): - """Test String arrays.""" + with pytest.raises(TypeError): ob = Test.StringArrayTest() - items = ob.items + _ = ob.items["wrong"] + + with pytest.raises(TypeError): + ob = Test.Int64ArrayTest() + ob[0] = 0 + - self.assertTrue(len(items) == 5) +def test_enum_array(): + """Test enum arrays.""" + from Python.Test import ShortEnum + ob = Test.EnumArrayTest() + items = ob.items - self.assertTrue(items[0] == '0') - self.assertTrue(items[4] == '4') + assert len(items) == 5 - items[0] = "spam" - self.assertTrue(items[0] == "spam") + assert items[0] == ShortEnum.Zero + assert items[4] == ShortEnum.Four - items[0] = "eggs" - self.assertTrue(items[0] == "eggs") + items[0] = ShortEnum.Four + assert items[0] == ShortEnum.Four - items[-4] = "spam" - self.assertTrue(items[-4] == "spam") + items[0] = ShortEnum.Zero + assert items[0] == ShortEnum.Zero - items[-1] = "eggs" - self.assertTrue(items[-1] == "eggs") + items[-4] = ShortEnum.Four + assert items[-4] == ShortEnum.Four - with self.assertRaises(TypeError): - ob = Test.StringArrayTest() - _ = ob.items["wrong"] + items[-1] = ShortEnum.Zero + assert items[-1] == ShortEnum.Zero - with self.assertRaises(TypeError): - ob = Test.Int64ArrayTest() - ob[0] = 0 + with pytest.raises(ValueError): + ob = Test.EnumArrayTest() + ob.items[0] = 99 + + with pytest.raises(TypeError): + ob = Test.EnumArrayTest() + _ = ob.items["wrong"] - def test_enum_array(self): - """Test enum arrays.""" - from Python.Test import ShortEnum + with pytest.raises(TypeError): ob = Test.EnumArrayTest() - items = ob.items + ob[0] = "wrong" + - self.assertTrue(len(items) == 5) +def test_object_array(): + """Test ob arrays.""" + from Python.Test import Spam + ob = Test.ObjectArrayTest() + items = ob.items - self.assertTrue(items[0] == ShortEnum.Zero) - self.assertTrue(items[4] == ShortEnum.Four) + assert len(items) == 5 - items[0] = ShortEnum.Four - self.assertTrue(items[0] == ShortEnum.Four) + assert items[0].GetValue() == "0" + assert items[4].GetValue() == "4" - items[0] = ShortEnum.Zero - self.assertTrue(items[0] == ShortEnum.Zero) + items[0] = Spam("4") + assert items[0].GetValue() == "4" - items[-4] = ShortEnum.Four - self.assertTrue(items[-4] == ShortEnum.Four) + items[0] = Spam("0") + assert items[0].GetValue() == "0" - items[-1] = ShortEnum.Zero - self.assertTrue(items[-1] == ShortEnum.Zero) + items[-4] = Spam("4") + assert items[-4].GetValue() == "4" - with self.assertRaises(ValueError): - ob = Test.EnumArrayTest() - ob.items[0] = 99 + items[-1] = Spam("0") + assert items[-1].GetValue() == "0" - with self.assertRaises(TypeError): - ob = Test.EnumArrayTest() - _ = ob.items["wrong"] + items[0] = 99 + assert items[0] == 99 - with self.assertRaises(TypeError): - ob = Test.EnumArrayTest() - ob[0] = "wrong" + items[0] = None + assert items[0] is None - def test_object_array(self): - """Test ob arrays.""" - from Python.Test import Spam + with pytest.raises(TypeError): ob = Test.ObjectArrayTest() - items = ob.items + _ = ob.items["wrong"] - self.assertTrue(len(items) == 5) + with pytest.raises(TypeError): + ob = Test.ObjectArrayTest() + ob.items["wrong"] = "wrong" - self.assertTrue(items[0].GetValue() == "0") - self.assertTrue(items[4].GetValue() == "4") - items[0] = Spam("4") - self.assertTrue(items[0].GetValue() == "4") +def test_null_array(): + """Test null arrays.""" + ob = Test.NullArrayTest() + items = ob.items - items[0] = Spam("0") - self.assertTrue(items[0].GetValue() == "0") + assert len(items) == 5 - items[-4] = Spam("4") - self.assertTrue(items[-4].GetValue() == "4") + assert items[0] is None + assert items[4] is None - items[-1] = Spam("0") - self.assertTrue(items[-1].GetValue() == "0") + items[0] = "spam" + assert items[0] == "spam" - items[0] = 99 - self.assertTrue(items[0] == 99) + items[0] = None + assert items[0] is None - items[0] = None - self.assertTrue(items[0] is None) + items[-4] = "spam" + assert items[-4] == "spam" - with self.assertRaises(TypeError): - ob = Test.ObjectArrayTest() - _ = ob.items["wrong"] + items[-1] = None + assert items[-1] is None - with self.assertRaises(TypeError): - ob = Test.ObjectArrayTest() - ob.items["wrong"] = "wrong" + empty = ob.empty + assert len(empty) == 0 - def test_null_array(self): - """Test null arrays.""" + with pytest.raises(TypeError): ob = Test.NullArrayTest() - items = ob.items + _ = ob.items["wrong"] + - self.assertTrue(len(items) == 5) +def test_interface_array(): + """Test interface arrays.""" + from Python.Test import Spam + ob = Test.InterfaceArrayTest() + items = ob.items - self.assertTrue(items[0] is None) - self.assertTrue(items[4] is None) + assert len(items) == 5 - items[0] = "spam" - self.assertTrue(items[0] == "spam") + assert items[0].GetValue() == "0" + assert items[4].GetValue() == "4" - items[0] = None - self.assertTrue(items[0] is None) + items[0] = Spam("4") + assert items[0].GetValue() == "4" - items[-4] = "spam" - self.assertTrue(items[-4] == "spam") + items[0] = Spam("0") + assert items[0].GetValue() == "0" - items[-1] = None - self.assertTrue(items[-1] is None) + items[-4] = Spam("4") + assert items[-4].GetValue() == "4" - empty = ob.empty - self.assertTrue(len(empty) == 0) + items[-1] = Spam("0") + assert items[-1].GetValue() == "0" - with self.assertRaises(TypeError): - ob = Test.NullArrayTest() - _ = ob.items["wrong"] + items[0] = None + assert items[0] is None - def test_interface_array(self): - """Test interface arrays.""" - from Python.Test import Spam + with pytest.raises(TypeError): ob = Test.InterfaceArrayTest() - items = ob.items + ob.items[0] = 99 - self.assertTrue(len(items) == 5) + with pytest.raises(TypeError): + ob = Test.InterfaceArrayTest() + _ = ob.items["wrong"] + + with pytest.raises(TypeError): + ob = Test.InterfaceArrayTest() + ob.items["wrong"] = "wrong" - self.assertTrue(items[0].GetValue() == "0") - self.assertTrue(items[4].GetValue() == "4") - items[0] = Spam("4") - self.assertTrue(items[0].GetValue() == "4") +def test_typed_array(): + """Test typed arrays.""" + from Python.Test import Spam + ob = Test.TypedArrayTest() + items = ob.items - items[0] = Spam("0") - self.assertTrue(items[0].GetValue() == "0") + assert len(items) == 5 - items[-4] = Spam("4") - self.assertTrue(items[-4].GetValue() == "4") + assert items[0].GetValue() == "0" + assert items[4].GetValue() == "4" - items[-1] = Spam("0") - self.assertTrue(items[-1].GetValue() == "0") + items[0] = Spam("4") + assert items[0].GetValue() == "4" - items[0] = None - self.assertTrue(items[0] is None) + items[0] = Spam("0") + assert items[0].GetValue() == "0" - with self.assertRaises(TypeError): - ob = Test.InterfaceArrayTest() - ob.items[0] = 99 + items[-4] = Spam("4") + assert items[-4].GetValue() == "4" - with self.assertRaises(TypeError): - ob = Test.InterfaceArrayTest() - _ = ob.items["wrong"] + items[-1] = Spam("0") + assert items[-1].GetValue() == "0" - with self.assertRaises(TypeError): - ob = Test.InterfaceArrayTest() - ob.items["wrong"] = "wrong" + items[0] = None + assert items[0] is None - def test_typed_array(self): - """Test typed arrays.""" - from Python.Test import Spam + with pytest.raises(TypeError): ob = Test.TypedArrayTest() - items = ob.items + ob.items[0] = 99 - self.assertTrue(len(items) == 5) + with pytest.raises(TypeError): + ob = Test.TypedArrayTest() + _ = ob.items["wrong"] - self.assertTrue(items[0].GetValue() == "0") - self.assertTrue(items[4].GetValue() == "4") + with pytest.raises(TypeError): + ob = Test.TypedArrayTest() + ob.items["wrong"] = "wrong" + + +def test_multi_dimensional_array(): + """Test multi-dimensional arrays.""" + ob = Test.MultiDimensionalArrayTest() + items = ob.items + + assert len(items) == 25 + + assert items[0, 0] == 0 + assert items[0, 1] == 1 + assert items[0, 2] == 2 + assert items[0, 3] == 3 + assert items[0, 4] == 4 + assert items[1, 0] == 5 + assert items[1, 1] == 6 + assert items[1, 2] == 7 + assert items[1, 3] == 8 + assert items[1, 4] == 9 + assert items[2, 0] == 10 + assert items[2, 1] == 11 + assert items[2, 2] == 12 + assert items[2, 3] == 13 + assert items[2, 4] == 14 + assert items[3, 0] == 15 + assert items[3, 1] == 16 + assert items[3, 2] == 17 + assert items[3, 3] == 18 + assert items[3, 4] == 19 + assert items[4, 0] == 20 + assert items[4, 1] == 21 + assert items[4, 2] == 22 + assert items[4, 3] == 23 + assert items[4, 4] == 24 + + max_ = 2147483647 + min_ = -2147483648 + + items[0, 0] = max_ + assert items[0, 0] == max_ + + items[0, 0] = min_ + assert items[0, 0] == min_ + + items[-4, 0] = max_ + assert items[-4, 0] == max_ + + items[-1, -1] = min_ + assert items[-1, -1] == min_ + + with pytest.raises(OverflowError): + ob = Test.MultiDimensionalArrayTest() + ob.items[0, 0] = max_ + 1 - items[0] = Spam("4") - self.assertTrue(items[0].GetValue() == "4") + with pytest.raises(OverflowError): + ob = Test.MultiDimensionalArrayTest() + ob.items[0, 0] = min_ - 1 - items[0] = Spam("0") - self.assertTrue(items[0].GetValue() == "0") + with pytest.raises(TypeError): + ob = Test.MultiDimensionalArrayTest() + _ = ob.items["wrong", 0] + + with pytest.raises(TypeError): + ob = Test.MultiDimensionalArrayTest() + ob[0, 0] = "wrong" - items[-4] = Spam("4") - self.assertTrue(items[-4].GetValue() == "4") - items[-1] = Spam("0") - self.assertTrue(items[-1].GetValue() == "0") +def test_array_iteration(): + """Test array iteration.""" + items = Test.Int32ArrayTest().items - items[0] = None - self.assertTrue(items[0] is None) + for i in items: + assert (i > -1) and (i < 5) - with self.assertRaises(TypeError): - ob = Test.TypedArrayTest() - ob.items[0] = 99 + items = Test.NullArrayTest().items - with self.assertRaises(TypeError): - ob = Test.TypedArrayTest() - _ = ob.items["wrong"] + for i in items: + assert i is None - with self.assertRaises(TypeError): - ob = Test.TypedArrayTest() - ob.items["wrong"] = "wrong" + empty = Test.NullArrayTest().empty + + for i in empty: + raise TypeError('iteration over empty array') + + +def test_tuple_array_conversion(): + """Test conversion of tuples to array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + + items = [] + for i in range(10): + items.append(Spam(str(i))) + items = tuple(items) + + result = ArrayConversionTest.EchoRange(items) + assert result[0].__class__ == Spam + assert len(result) == 10 + + +def test_tuple_nested_array_conversion(): + """Test conversion of tuples to array-of-array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + + items = [] + for i in range(10): + subs = [] + for _ in range(10): + subs.append(Spam(str(i))) + items.append(tuple(subs)) + items = tuple(items) + + result = ArrayConversionTest.EchoRangeAA(items) + + assert len(result) == 10 + assert len(result[0]) == 10 + assert result[0][0].__class__ == Spam + + +def test_list_array_conversion(): + """Test conversion of lists to array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + + items = [] + for i in range(10): + items.append(Spam(str(i))) + + result = ArrayConversionTest.EchoRange(items) + assert result[0].__class__ == Spam + assert len(result) == 10 + + +def test_list_nested_array_conversion(): + """Test conversion of lists to array-of-array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + + items = [] + for i in range(10): + subs = [] + for _ in range(10): + subs.append(Spam(str(i))) + items.append(subs) + + result = ArrayConversionTest.EchoRangeAA(items) + + assert len(result) == 10 + assert len(result[0]) == 10 + assert result[0][0].__class__ == Spam + + +def test_sequence_array_conversion(): + """Test conversion of sequence-like obs to array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + + items = UserList() + for i in range(10): + items.append(Spam(str(i))) + + result = ArrayConversionTest.EchoRange(items) + assert result[0].__class__ == Spam + assert len(result) == 10 + + +def test_sequence_nested_array_conversion(): + """Test conversion of sequences to array-of-array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + + items = UserList() + for i in range(10): + subs = UserList() + for _ in range(10): + subs.append(Spam(str(i))) + items.append(subs) + + result = ArrayConversionTest.EchoRangeAA(items) + + assert len(result) == 10 + assert len(result[0]) == 10 + assert result[0][0].__class__ == Spam + + +def test_tuple_array_conversion_type_checking(): + """Test error handling for tuple conversion to array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + + # This should work, because null / None is a valid value in an + # array of reference types. + + items = [] + for i in range(10): + items.append(Spam(str(i))) + items[1] = None + items = tuple(items) + + result = ArrayConversionTest.EchoRange(items) + + assert result[0].__class__ == Spam + assert result[1] is None + assert len(result) == 10 + + with pytest.raises(TypeError): + temp = list(items) + temp[1] = 1 + _ = ArrayConversionTest.EchoRange(tuple(temp)) + + with pytest.raises(TypeError): + temp = list(items) + temp[1] = "spam" + _ = ArrayConversionTest.EchoRange(tuple(temp)) + + +def test_list_array_conversion_type_checking(): + """Test error handling for list conversion to array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + + # This should work, because null / None is a valid value in an + # array of reference types. + + items = [] + for i in range(10): + items.append(Spam(str(i))) + items[1] = None + + result = ArrayConversionTest.EchoRange(items) + + assert result[0].__class__ == Spam + assert result[1] is None + assert len(result) == 10 + + with pytest.raises(TypeError): + items[1] = 1 + _ = ArrayConversionTest.EchoRange(items) + + with pytest.raises(TypeError): + items[1] = "spam" + _ = ArrayConversionTest.EchoRange(items) + + +def test_sequence_array_conversion_type_checking(): + """Test error handling for sequence conversion to array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + + # This should work, because null / None is a valid value in an + # array of reference types. + + items = UserList() + for i in range(10): + items.append(Spam(str(i))) + items[1] = None + + result = ArrayConversionTest.EchoRange(items) + + assert result[0].__class__ == Spam + assert result[1] is None + assert len(result) == 10 + + with pytest.raises(TypeError): + items[1] = 1 + _ = ArrayConversionTest.EchoRange(items) + + with pytest.raises(TypeError): + items[1] = "spam" + _ = ArrayConversionTest.EchoRange(items) - def test_multi_dimensional_array(self): - """Test multi-dimensional arrays.""" - ob = Test.MultiDimensionalArrayTest() - items = ob.items - - self.assertTrue(len(items) == 25) - - self.assertTrue(items[0, 0] == 0) - self.assertTrue(items[0, 1] == 1) - self.assertTrue(items[0, 2] == 2) - self.assertTrue(items[0, 3] == 3) - self.assertTrue(items[0, 4] == 4) - self.assertTrue(items[1, 0] == 5) - self.assertTrue(items[1, 1] == 6) - self.assertTrue(items[1, 2] == 7) - self.assertTrue(items[1, 3] == 8) - self.assertTrue(items[1, 4] == 9) - self.assertTrue(items[2, 0] == 10) - self.assertTrue(items[2, 1] == 11) - self.assertTrue(items[2, 2] == 12) - self.assertTrue(items[2, 3] == 13) - self.assertTrue(items[2, 4] == 14) - self.assertTrue(items[3, 0] == 15) - self.assertTrue(items[3, 1] == 16) - self.assertTrue(items[3, 2] == 17) - self.assertTrue(items[3, 3] == 18) - self.assertTrue(items[3, 4] == 19) - self.assertTrue(items[4, 0] == 20) - self.assertTrue(items[4, 1] == 21) - self.assertTrue(items[4, 2] == 22) - self.assertTrue(items[4, 3] == 23) - self.assertTrue(items[4, 4] == 24) - - max_ = 2147483647 - min_ = -2147483648 - - items[0, 0] = max_ - self.assertTrue(items[0, 0] == max_) - - items[0, 0] = min_ - self.assertTrue(items[0, 0] == min_) - - items[-4, 0] = max_ - self.assertTrue(items[-4, 0] == max_) - - items[-1, -1] = min_ - self.assertTrue(items[-1, -1] == min_) - - with self.assertRaises(OverflowError): - ob = Test.MultiDimensionalArrayTest() - ob.items[0, 0] = max_ + 1 - - with self.assertRaises(OverflowError): - ob = Test.MultiDimensionalArrayTest() - ob.items[0, 0] = min_ - 1 - - with self.assertRaises(TypeError): - ob = Test.MultiDimensionalArrayTest() - _ = ob.items["wrong", 0] - - with self.assertRaises(TypeError): - ob = Test.MultiDimensionalArrayTest() - ob[0, 0] = "wrong" - - def test_array_iteration(self): - """Test array iteration.""" - items = Test.Int32ArrayTest().items - - for i in items: - self.assertTrue((i > -1) and (i < 5)) - - items = Test.NullArrayTest().items - - for i in items: - self.assertTrue(i is None) - - empty = Test.NullArrayTest().empty - - for i in empty: - raise TypeError('iteration over empty array') - - def test_tuple_array_conversion(self): - """Test conversion of tuples to array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - - items = [] - for i in range(10): - items.append(Spam(str(i))) - items = tuple(items) - - result = ArrayConversionTest.EchoRange(items) - self.assertTrue(result[0].__class__ == Spam) - self.assertTrue(len(result) == 10) - - def test_tuple_nested_array_conversion(self): - """Test conversion of tuples to array-of-array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - - items = [] - for i in range(10): - subs = [] - for _ in range(10): - subs.append(Spam(str(i))) - items.append(tuple(subs)) - items = tuple(items) - - result = ArrayConversionTest.EchoRangeAA(items) - - self.assertTrue(len(result) == 10) - self.assertTrue(len(result[0]) == 10) - self.assertTrue(result[0][0].__class__ == Spam) - - def test_list_array_conversion(self): - """Test conversion of lists to array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - - items = [] - for i in range(10): - items.append(Spam(str(i))) - - result = ArrayConversionTest.EchoRange(items) - self.assertTrue(result[0].__class__ == Spam) - self.assertTrue(len(result) == 10) - - def test_list_nested_array_conversion(self): - """Test conversion of lists to array-of-array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - items = [] - for i in range(10): - subs = [] - for _ in range(10): - subs.append(Spam(str(i))) - items.append(subs) +def test_md_array_conversion(): + """Test passing of multi-dimensional array arguments.""" + from Python.Test import ArrayConversionTest + from Python.Test import Spam + from System import Array - result = ArrayConversionTest.EchoRangeAA(items) + # Currently, the runtime does not support automagic conversion of + # Python sequences to true multi-dimensional arrays (though it + # does support arrays-of-arrays). This test exists mostly as an + # example of how a multi-dimensional array can be created and used + # with managed code from Python. - self.assertTrue(len(result) == 10) - self.assertTrue(len(result[0]) == 10) - self.assertTrue(result[0][0].__class__ == Spam) - - def test_sequence_array_conversion(self): - """Test conversion of sequence-like obs to array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - - items = UserList() - for i in range(10): - items.append(Spam(str(i))) - - result = ArrayConversionTest.EchoRange(items) - self.assertTrue(result[0].__class__ == Spam) - self.assertTrue(len(result) == 10) - - def test_sequence_nested_array_conversion(self): - """Test conversion of sequences to array-of-array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - - items = UserList() - for i in range(10): - subs = UserList() - for _ in range(10): - subs.append(Spam(str(i))) - items.append(subs) - - result = ArrayConversionTest.EchoRangeAA(items) - - self.assertTrue(len(result) == 10) - self.assertTrue(len(result[0]) == 10) - self.assertTrue(result[0][0].__class__ == Spam) - - def test_tuple_array_conversion_type_checking(self): - """Test error handling for tuple conversion to array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - - # This should work, because null / None is a valid value in an - # array of reference types. - - items = [] - for i in range(10): - items.append(Spam(str(i))) - items[1] = None - items = tuple(items) - - result = ArrayConversionTest.EchoRange(items) - - self.assertTrue(result[0].__class__ == Spam) - self.assertTrue(result[1] is None) - self.assertTrue(len(result) == 10) - - with self.assertRaises(TypeError): - temp = list(items) - temp[1] = 1 - _ = ArrayConversionTest.EchoRange(tuple(temp)) - - with self.assertRaises(TypeError): - temp = list(items) - temp[1] = "spam" - _ = ArrayConversionTest.EchoRange(tuple(temp)) - - def test_list_array_conversion_type_checking(self): - """Test error handling for list conversion to array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - - # This should work, because null / None is a valid value in an - # array of reference types. - - items = [] - for i in range(10): - items.append(Spam(str(i))) - items[1] = None - - result = ArrayConversionTest.EchoRange(items) - - self.assertTrue(result[0].__class__ == Spam) - self.assertTrue(result[1] is None) - self.assertTrue(len(result) == 10) - - with self.assertRaises(TypeError): - items[1] = 1 - _ = ArrayConversionTest.EchoRange(items) - - with self.assertRaises(TypeError): - items[1] = "spam" - _ = ArrayConversionTest.EchoRange(items) - - def test_sequence_array_conversion_type_checking(self): - """Test error handling for sequence conversion to array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - - # This should work, because null / None is a valid value in an - # array of reference types. - - items = UserList() - for i in range(10): - items.append(Spam(str(i))) - items[1] = None - - result = ArrayConversionTest.EchoRange(items) - - self.assertTrue(result[0].__class__ == Spam) - self.assertTrue(result[1] is None) - self.assertTrue(len(result) == 10) - - with self.assertRaises(TypeError): - items[1] = 1 - _ = ArrayConversionTest.EchoRange(items) - - with self.assertRaises(TypeError): - items[1] = "spam" - _ = ArrayConversionTest.EchoRange(items) - - def test_md_array_conversion(self): - """Test passing of multi-dimensional array arguments.""" - from Python.Test import ArrayConversionTest - from Python.Test import Spam - from System import Array - - # Currently, the runtime does not support automagic conversion of - # Python sequences to true multi-dimensional arrays (though it - # does support arrays-of-arrays). This test exists mostly as an - # example of how a multi-dimensional array can be created and used - # with managed code from Python. - - items = Array.CreateInstance(Spam, 5, 5) - - for i in range(5): - for n in range(5): - items.SetValue(Spam(str((i, n))), (i, n)) - - result = ArrayConversionTest.EchoRangeMD(items) - - self.assertTrue(len(result) == 25) - self.assertTrue(result[0, 0].__class__ == Spam) - self.assertTrue(result[0, 0].__class__ == Spam) - - def test_boxed_value_type_mutation_result(self): - """Test behavior of boxed value types.""" - - # This test actually exists mostly as documentation of an important - # concern when dealing with value types. Python does not have any - # value type semantics that can be mapped to the CLR, so it is easy - # to accidentally write code like the following which is not really - # mutating value types in-place but changing boxed copies. - - from System.Drawing import Point - from System import Array - - items = Array.CreateInstance(Point, 5) - - for i in range(5): - items[i] = Point(i, i) - - for i in range(5): - # Boxed items, so set_attr will not change the array member. - self.assertTrue(items[i].X == i) - self.assertTrue(items[i].Y == i) - items[i].X = i + 1 - items[i].Y = i + 1 - self.assertTrue(items[i].X == i) - self.assertTrue(items[i].Y == i) - - for i in range(5): - # Demonstrates the workaround that will change the members. - self.assertTrue(items[i].X == i) - self.assertTrue(items[i].Y == i) - item = items[i] - item.X = i + 1 - item.Y = i + 1 - items[i] = item - self.assertTrue(items[i].X == i + 1) - self.assertTrue(items[i].Y == i + 1) - - def test_special_array_creation(self): - """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]) - self.assertTrue(value[0] is True) - self.assertTrue(value[1] is True) - self.assertTrue(value.Length == 2) - - value = Array[bool]([True, True]) - self.assertTrue(value[0] is True) - self.assertTrue(value[1] is True) - self.assertTrue(value.Length == 2) - - value = Array[System.Byte]([0, 255]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 255) - self.assertTrue(value.Length == 2) - - value = Array[System.SByte]([0, 127]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 127) - self.assertTrue(value.Length == 2) - - value = Array[System.Char]([u'A', u'Z']) - self.assertTrue(value[0] == u'A') - self.assertTrue(value[1] == u'Z') - self.assertTrue(value.Length == 2) - - value = Array[System.Char]([0, 65535]) - self.assertTrue(value[0] == unichr(0)) - self.assertTrue(value[1] == unichr(65535)) - self.assertTrue(value.Length == 2) - - value = Array[System.Int16]([0, 32767]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 32767) - self.assertTrue(value.Length == 2) - - value = Array[System.Int32]([0, 2147483647]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 2147483647) - self.assertTrue(value.Length == 2) - - value = Array[int]([0, 2147483647]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 2147483647) - self.assertTrue(value.Length == 2) - - value = Array[System.Int64]([0, long(9223372036854775807)]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == long(9223372036854775807)) - self.assertTrue(value.Length == 2) - - # there's no explicit long type in python3, use System.Int64 instead - if PY2: - value = Array[long]([0, long(9223372036854775807)]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == long(9223372036854775807)) - self.assertTrue(value.Length == 2) - - value = Array[System.UInt16]([0, 65000]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 65000) - self.assertTrue(value.Length == 2) - - value = Array[System.UInt32]([0, long(4294967295)]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == long(4294967295)) - self.assertTrue(value.Length == 2) - - value = Array[System.UInt64]([0, long(18446744073709551615)]) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == long(18446744073709551615)) - self.assertTrue(value.Length == 2) - - value = Array[System.Single]([0.0, 3.402823e38]) - self.assertTrue(value[0] == 0.0) - self.assertTrue(value[1] == 3.402823e38) - self.assertTrue(value.Length == 2) - - value = Array[System.Double]([0.0, 1.7976931348623157e308]) - self.assertTrue(value[0] == 0.0) - self.assertTrue(value[1] == 1.7976931348623157e308) - self.assertTrue(value.Length == 2) - - value = Array[float]([0.0, 1.7976931348623157e308]) - self.assertTrue(value[0] == 0.0) - self.assertTrue(value[1] == 1.7976931348623157e308) - self.assertTrue(value.Length == 2) - - value = Array[System.Decimal]([System.Decimal.Zero, System.Decimal.One]) - self.assertTrue(value[0] == System.Decimal.Zero) - self.assertTrue(value[1] == System.Decimal.One) - self.assertTrue(value.Length == 2) - - value = Array[System.String](["one", "two"]) - self.assertTrue(value[0] == "one") - self.assertTrue(value[1] == "two") - self.assertTrue(value.Length == 2) - - value = Array[str](["one", "two"]) - self.assertTrue(value[0] == "one") - self.assertTrue(value[1] == "two") - self.assertTrue(value.Length == 2) - - value = Array[ShortEnum]([ShortEnum.Zero, ShortEnum.One]) - self.assertTrue(value[0] == ShortEnum.Zero) - self.assertTrue(value[1] == ShortEnum.One) - self.assertTrue(value.Length == 2) - - value = Array[System.Object]([inst, inst]) - self.assertTrue(value[0].__class__ == inst.__class__) - self.assertTrue(value[1].__class__ == inst.__class__) - self.assertTrue(value.Length == 2) - - value = Array[InterfaceTest]([inst, inst]) - self.assertTrue(value[0].__class__ == inst.__class__) - self.assertTrue(value[1].__class__ == inst.__class__) - self.assertTrue(value.Length == 2) - - value = Array[ISayHello1]([inst, inst]) - self.assertTrue(value[0].__class__ == inst.__class__) - self.assertTrue(value[1].__class__ == inst.__class__) - self.assertTrue(value.Length == 2) - - inst = System.Exception("badness") - value = Array[System.Exception]([inst, inst]) - self.assertTrue(value[0].__class__ == inst.__class__) - self.assertTrue(value[1].__class__ == inst.__class__) - self.assertTrue(value.Length == 2) - - def test_array_abuse(self): - """Test array abuse.""" - _class = Test.PublicArrayTest - ob = Test.PublicArrayTest() - - with self.assertRaises(AttributeError): - del _class.__getitem__ - - with self.assertRaises(AttributeError): - del ob.__getitem__ - - with self.assertRaises(AttributeError): - del _class.__setitem__ - - with self.assertRaises(AttributeError): - del ob.__setitem__ - - with self.assertRaises(TypeError): - Test.PublicArrayTest.__getitem__(0, 0) - - with self.assertRaises(TypeError): - Test.PublicArrayTest.__setitem__(0, 0, 0) - - with self.assertRaises(TypeError): - desc = Test.PublicArrayTest.__dict__['__getitem__'] - desc(0, 0) - - with self.assertRaises(TypeError): - desc = Test.PublicArrayTest.__dict__['__setitem__'] - desc(0, 0, 0) - - -def test_suite(): - return unittest.makeSuite(ArrayTests) + items = Array.CreateInstance(Spam, 5, 5) + + for i in range(5): + for n in range(5): + items.SetValue(Spam(str((i, n))), (i, n)) + + result = ArrayConversionTest.EchoRangeMD(items) + + assert len(result) == 25 + assert result[0, 0].__class__ == Spam + assert result[0, 0].__class__ == Spam + + +def test_boxed_value_type_mutation_result(): + """Test behavior of boxed value types.""" + + # This test actually exists mostly as documentation of an important + # concern when dealing with value types. Python does not have any + # value type semantics that can be mapped to the CLR, so it is easy + # to accidentally write code like the following which is not really + # mutating value types in-place but changing boxed copies. + + from System.Drawing import Point + from System import Array + + items = Array.CreateInstance(Point, 5) + + for i in range(5): + items[i] = Point(i, i) + + for i in range(5): + # Boxed items, so set_attr will not change the array member. + assert items[i].X == i + assert items[i].Y == i + items[i].X = i + 1 + items[i].Y = i + 1 + assert items[i].X == i + assert items[i].Y == i + + for i in range(5): + # Demonstrates the workaround that will change the members. + assert items[i].X == i + assert items[i].Y == i + item = items[i] + item.X = i + 1 + item.Y = i + 1 + items[i] = item + assert items[i].X == i + 1 + assert items[i].Y == i + 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]) + assert value[0] is True + assert value[1] is True + assert value.Length == 2 + + value = Array[bool]([True, True]) + assert value[0] is True + assert value[1] is True + assert value.Length == 2 + + value = Array[System.Byte]([0, 255]) + assert value[0] == 0 + assert value[1] == 255 + assert value.Length == 2 + + value = Array[System.SByte]([0, 127]) + assert value[0] == 0 + 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' + assert value.Length == 2 + + value = Array[System.Char]([0, 65535]) + assert value[0] == unichr(0) + assert value[1] == unichr(65535) + assert value.Length == 2 + + value = Array[System.Int16]([0, 32767]) + assert value[0] == 0 + assert value[1] == 32767 + assert value.Length == 2 + + value = Array[System.Int32]([0, 2147483647]) + assert value[0] == 0 + assert value[1] == 2147483647 + assert value.Length == 2 + + value = Array[int]([0, 2147483647]) + assert value[0] == 0 + assert value[1] == 2147483647 + assert value.Length == 2 + + value = Array[System.Int64]([0, long(9223372036854775807)]) + assert value[0] == 0 + assert value[1] == long(9223372036854775807) + assert value.Length == 2 + + # there's no explicit long type in python3, use System.Int64 instead + if PY2: + value = Array[long]([0, long(9223372036854775807)]) + assert value[0] == 0 + assert value[1] == long(9223372036854775807) + assert value.Length == 2 + + value = Array[System.UInt16]([0, 65000]) + assert value[0] == 0 + assert value[1] == 65000 + assert value.Length == 2 + + value = Array[System.UInt32]([0, long(4294967295)]) + assert value[0] == 0 + assert value[1] == long(4294967295) + assert value.Length == 2 + + value = Array[System.UInt64]([0, long(18446744073709551615)]) + assert value[0] == 0 + assert value[1] == long(18446744073709551615) + assert value.Length == 2 + + value = Array[System.Single]([0.0, 3.402823e38]) + assert value[0] == 0.0 + assert value[1] == 3.402823e38 + assert value.Length == 2 + + value = Array[System.Double]([0.0, 1.7976931348623157e308]) + assert value[0] == 0.0 + assert value[1] == 1.7976931348623157e308 + assert value.Length == 2 + + value = Array[float]([0.0, 1.7976931348623157e308]) + assert value[0] == 0.0 + assert value[1] == 1.7976931348623157e308 + assert value.Length == 2 + + value = Array[System.Decimal]([System.Decimal.Zero, System.Decimal.One]) + assert value[0] == System.Decimal.Zero + assert value[1] == System.Decimal.One + assert value.Length == 2 + + value = Array[System.String](["one", "two"]) + assert value[0] == "one" + assert value[1] == "two" + assert value.Length == 2 + + value = Array[str](["one", "two"]) + assert value[0] == "one" + assert value[1] == "two" + assert value.Length == 2 + + value = Array[ShortEnum]([ShortEnum.Zero, ShortEnum.One]) + assert value[0] == ShortEnum.Zero + assert value[1] == ShortEnum.One + assert value.Length == 2 + + value = Array[System.Object]([inst, inst]) + assert value[0].__class__ == inst.__class__ + assert value[1].__class__ == inst.__class__ + assert value.Length == 2 + + value = Array[InterfaceTest]([inst, inst]) + assert value[0].__class__ == inst.__class__ + assert value[1].__class__ == inst.__class__ + assert value.Length == 2 + + value = Array[ISayHello1]([inst, inst]) + assert value[0].__class__ == inst.__class__ + assert value[1].__class__ == inst.__class__ + assert value.Length == 2 + + inst = System.Exception("badness") + value = Array[System.Exception]([inst, inst]) + assert value[0].__class__ == inst.__class__ + assert value[1].__class__ == inst.__class__ + assert value.Length == 2 + + +def test_array_abuse(): + """Test array abuse.""" + _class = Test.PublicArrayTest + ob = Test.PublicArrayTest() + + with pytest.raises(AttributeError): + del _class.__getitem__ + + with pytest.raises(AttributeError): + del ob.__getitem__ + + with pytest.raises(AttributeError): + del _class.__setitem__ + + with pytest.raises(AttributeError): + del ob.__setitem__ + + with pytest.raises(TypeError): + Test.PublicArrayTest.__getitem__(0, 0) + + with pytest.raises(TypeError): + Test.PublicArrayTest.__setitem__(0, 0, 0) + + with pytest.raises(TypeError): + desc = Test.PublicArrayTest.__dict__['__getitem__'] + desc(0, 0) + + with pytest.raises(TypeError): + desc = Test.PublicArrayTest.__dict__['__setitem__'] + desc(0, 0, 0) diff --git a/src/tests/test_callback.py b/src/tests/test_callback.py new file mode 100644 index 000000000..f94a9d52e --- /dev/null +++ b/src/tests/test_callback.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- + +"""Test that callbacks from C# into python work.""" + + +def simpleDefaultArg(arg='test'): + return arg + + +def test_default_for_null(): + """Test that C# can use null for an optional python argument""" + from Python.Test import CallbackTest + + test_instance = CallbackTest() + ret_val = test_instance.Call_simpleDefaultArg_WithNull(__name__) + python_ret_val = simpleDefaultArg(None) + assert ret_val == python_ret_val + + +def test_default_for_none(): + """Test that C# can use no argument for an optional python argument""" + from Python.Test import CallbackTest + + test_instance = CallbackTest() + ret_val = test_instance.Call_simpleDefaultArg_WithEmptyArgs(__name__) + python_ret_val = simpleDefaultArg() + assert ret_val == python_ret_val diff --git a/src/tests/test_class.py b/src/tests/test_class.py index bf3b6f143..68773508b 100644 --- a/src/tests/test_class.py +++ b/src/tests/test_class.py @@ -1,130 +1,138 @@ # -*- coding: utf-8 -*- # TODO: Add tests for ClassicClass, NewStyleClass? -import unittest +"""Test CLR class support.""" import Python.Test as Test import System +import pytest -from _compat import DictProxyType, range +from ._compat import DictProxyType, range -class ClassTests(unittest.TestCase): - """Test CLR class support.""" +def test_basic_reference_type(): + """Test usage of CLR defined reference types.""" + assert System.String.Empty == "" - def test_basic_reference_type(self): - """Test usage of CLR defined reference types.""" - self.assertEquals(System.String.Empty, "") - def test_basic_value_type(self): - """Test usage of CLR defined value types.""" - self.assertEquals(System.Int32.MaxValue, 2147483647) +def test_basic_value_type(): + """Test usage of CLR defined value types.""" + assert System.Int32.MaxValue == 2147483647 - def test_class_standard_attrs(self): - """Test standard class attributes.""" - from Python.Test import ClassTest - self.assertTrue(ClassTest.__name__ == 'ClassTest') - self.assertTrue(ClassTest.__module__ == 'Python.Test') - self.assertTrue(isinstance(ClassTest.__dict__, DictProxyType)) - self.assertTrue(len(ClassTest.__doc__) > 0) +def test_class_standard_attrs(): + """Test standard class attributes.""" + from Python.Test import ClassTest - def test_class_docstrings(self): - """Test standard class docstring generation""" - from Python.Test import ClassTest + assert ClassTest.__name__ == 'ClassTest' + assert ClassTest.__module__ == 'Python.Test' + assert isinstance(ClassTest.__dict__, DictProxyType) + assert len(ClassTest.__doc__) > 0 - value = 'Void .ctor()' - self.assertTrue(ClassTest.__doc__ == value) - def test_class_default_str(self): - """Test the default __str__ implementation for managed objects.""" - s = System.String("this is a test") - self.assertTrue(str(s) == "this is a test") +def test_class_docstrings(): + """Test standard class docstring generation""" + from Python.Test import ClassTest - def test_class_default_repr(self): - """Test the default __repr__ implementation for managed objects.""" - s = System.String("this is a test") - self.assertTrue(repr(s).startswith(" -1) and (item < 10) + + dict_ = ClassTest.GetHashtable() + + for item in dict_: + cname = item.__class__.__name__ + assert cname.endswith('DictionaryEntry') + - for item in list_: - self.assertTrue((item > -1) and (item < 10)) +def test_ienumerator_iteration(): + """Test iteration over objects supporting IEnumerator.""" + from Python.Test import ClassTest - dict_ = ClassTest.GetHashtable() + chars = ClassTest.GetEnumerator() - for item in dict_: - cname = item.__class__.__name__ - self.assertTrue(cname.endswith('DictionaryEntry')) + for item in chars: + assert item in 'test string' - def test_ienumerator_iteration(self): - """Test iteration over objects supporting IEnumerator.""" - from Python.Test import ClassTest - chars = ClassTest.GetEnumerator() +def test_override_get_item(): + """Test managed subclass overriding __getitem__.""" + from System.Collections import Hashtable - for item in chars: - self.assertTrue(item in 'test string') + class MyTable(Hashtable): + def __getitem__(self, key): + value = Hashtable.__getitem__(self, key) + return 'my ' + str(value) - def test_override_get_item(self): - """Test managed subclass overriding __getitem__.""" - from System.Collections import Hashtable + table = MyTable() + table['one'] = 'one' + table['two'] = 'two' + table['three'] = 'three' - class MyTable(Hashtable): - def __getitem__(self, key): - value = Hashtable.__getitem__(self, key) - return 'my ' + str(value) + assert table['one'] == 'my one' + assert table['two'] == 'my two' + assert table['three'] == 'my three' - table = MyTable() - table['one'] = 'one' - table['two'] = 'two' - table['three'] = 'three' + assert table.Count == 3 - self.assertTrue(table['one'] == 'my one') - self.assertTrue(table['two'] == 'my two') - self.assertTrue(table['three'] == 'my three') - self.assertTrue(table.Count == 3) +def test_override_set_item(): + """Test managed subclass overriding __setitem__.""" + from System.Collections import Hashtable - def test_override_set_item(self): - """Test managed subclass overriding __setitem__.""" - from System.Collections import Hashtable + class MyTable(Hashtable): + def __setitem__(self, key, value): + value = 'my ' + str(value) + Hashtable.__setitem__(self, key, value) - class MyTable(Hashtable): - def __setitem__(self, key, value): - value = 'my ' + str(value) - Hashtable.__setitem__(self, key, value) + table = MyTable() + table['one'] = 'one' + table['two'] = 'two' + table['three'] = 'three' - table = MyTable() - table['one'] = 'one' - table['two'] = 'two' - table['three'] = 'three' + assert table['one'] == 'my one' + assert table['two'] == 'my two' + assert table['three'] == 'my three' - self.assertTrue(table['one'] == 'my one') - self.assertTrue(table['two'] == 'my two') - self.assertTrue(table['three'] == 'my three') + assert table.Count == 3 - self.assertTrue(table.Count == 3) - def test_add_and_remove_class_attribute(self): - from System import TimeSpan +def test_add_and_remove_class_attribute(): + from System import TimeSpan - for _ in range(100): - TimeSpan.new_method = lambda self_: self_.TotalMinutes - ts = TimeSpan.FromHours(1) - self.assertTrue(ts.new_method() == 60) - del TimeSpan.new_method - self.assertFalse(hasattr(ts, "new_method")) + for _ in range(100): + TimeSpan.new_method = lambda self_: self_.TotalMinutes + ts = TimeSpan.FromHours(1) + assert ts.new_method() == 60 + del TimeSpan.new_method + assert not hasattr(ts, "new_method") - def test_comparisons(self): - from System import DateTimeOffset - from Python.Test import ClassTest - d1 = DateTimeOffset.Parse("2016-11-14") - d2 = DateTimeOffset.Parse("2016-11-15") +def test_comparisons(): + from System import DateTimeOffset + from Python.Test import ClassTest - self.assertEqual(d1 == d2, False) - self.assertEqual(d1 != d2, True) + d1 = DateTimeOffset.Parse("2016-11-14") + d2 = DateTimeOffset.Parse("2016-11-15") - self.assertEqual(d1 < d2, True) - self.assertEqual(d1 <= d2, True) - self.assertEqual(d1 >= d2, False) - self.assertEqual(d1 > d2, False) + assert (d1 == d2) == False + assert (d1 != d2) == True - self.assertEqual(d1 == d1, True) - self.assertEqual(d1 != d1, False) + assert (d1 < d2) == True + assert (d1 <= d2) == True + assert (d1 >= d2) == False + assert (d1 > d2) == False - self.assertEqual(d1 < d1, False) - self.assertEqual(d1 <= d1, True) - self.assertEqual(d1 >= d1, True) - self.assertEqual(d1 > d1, False) + assert (d1 == d1) == True + assert (d1 != d1) == False - self.assertEqual(d2 == d1, False) - self.assertEqual(d2 != d1, True) + assert (d1 < d1) == False + assert (d1 <= d1) == True + assert (d1 >= d1) == True + assert (d1 > d1) == False - self.assertEqual(d2 < d1, False) - self.assertEqual(d2 <= d1, False) - self.assertEqual(d2 >= d1, True) - self.assertEqual(d2 > d1, True) + assert (d2 == d1) == False + assert (d2 != d1) == True - with self.assertRaises(TypeError): - d1 < None + assert (d2 < d1) == False + assert (d2 <= d1) == False + assert (d2 >= d1) == True + assert (d2 > d1) == True - with self.assertRaises(TypeError): - d1 < System.Guid() + with pytest.raises(TypeError): + d1 < None - # ClassTest does not implement IComparable - c1 = ClassTest() - c2 = ClassTest() - with self.assertRaises(TypeError): - c1 < c2 + with pytest.raises(TypeError): + d1 < System.Guid() - def test_self_callback(self): - """Test calling back and forth between this and a c# baseclass.""" + # ClassTest does not implement IComparable + c1 = ClassTest() + c2 = ClassTest() + with pytest.raises(TypeError): + c1 < c2 - class CallbackUser(Test.SelfCallbackTest): - def DoCallback(self): - self.PyCallbackWasCalled = False - self.SameReference = False - return self.Callback(self) - def PyCallback(self, self2): - self.PyCallbackWasCalled = True - self.SameReference = self == self2 +def test_self_callback(): + """Test calling back and forth between this and a c# baseclass.""" - testobj = CallbackUser() - testobj.DoCallback() - self.assertTrue(testobj.PyCallbackWasCalled) - self.assertTrue(testobj.SameReference) + class CallbackUser(Test.SelfCallbackTest): + def DoCallback(self): + self.PyCallbackWasCalled = False + self.SameReference = False + return self.Callback(self) + def PyCallback(self, self2): + self.PyCallbackWasCalled = True + self.SameReference = self == self2 -def test_suite(): - return unittest.makeSuite(ClassTests) + testobj = CallbackUser() + testobj.DoCallback() + assert testobj.PyCallbackWasCalled + assert testobj.SameReference diff --git a/src/tests/test_compat.py b/src/tests/test_compat.py index cea51ca49..81e7f8143 100644 --- a/src/tests/test_compat.py +++ b/src/tests/test_compat.py @@ -1,233 +1,243 @@ # -*- coding: utf-8 -*- # TODO: Complete removal of methods below. Similar to test_module +"""Backward-compatibility tests for deprecated features.""" + import types -import unittest -from _compat import ClassType, PY2, PY3, range -from utils import is_clr_class, is_clr_module, is_clr_root_module +import pytest +from ._compat import ClassType, PY2, PY3, range +from .utils import is_clr_class, is_clr_module, is_clr_root_module -class CompatibilityTests(unittest.TestCase): - """Backward-compatibility tests for deprecated features.""" - # Tests for old-style CLR-prefixed module naming. +# Tests for old-style CLR-prefixed module naming. +def test_simple_import(): + """Test simple import.""" + import CLR + assert is_clr_root_module(CLR) + assert CLR.__name__ == 'clr' - def test_simple_import(self): - """Test simple import.""" - import CLR - self.assertTrue(is_clr_root_module(CLR)) - self.assertTrue(CLR.__name__ == 'clr') - - import sys - self.assertTrue(isinstance(sys, types.ModuleType)) - self.assertTrue(sys.__name__ == 'sys') - - if PY3: - import http.client - self.assertTrue(isinstance(http.client, types.ModuleType)) - self.assertTrue(http.client.__name__ == 'http.client') - - elif PY2: - import httplib - self.assertTrue(isinstance(httplib, types.ModuleType)) - self.assertTrue(httplib.__name__ == 'httplib') - - def test_simple_import_with_alias(self): - """Test simple import with aliasing.""" - import CLR as myCLR - self.assertTrue(is_clr_root_module(myCLR)) - self.assertTrue(myCLR.__name__ == 'clr') - - import sys as mySys - self.assertTrue(isinstance(mySys, types.ModuleType)) - self.assertTrue(mySys.__name__ == 'sys') - - if PY3: - import http.client as myHttplib - self.assertTrue(isinstance(myHttplib, types.ModuleType)) - self.assertTrue(myHttplib.__name__ == 'http.client') - - elif PY2: - import httplib as myHttplib - self.assertTrue(isinstance(myHttplib, types.ModuleType)) - self.assertTrue(myHttplib.__name__ == 'httplib') - - def test_dotted_name_import(self): - """Test dotted-name import.""" - import CLR.System - self.assertTrue(is_clr_module(CLR.System)) - self.assertTrue(CLR.System.__name__ == 'System') - - import System - self.assertTrue(is_clr_module(System)) - self.assertTrue(System.__name__ == 'System') - - self.assertTrue(System is CLR.System) - - import xml.dom - self.assertTrue(isinstance(xml.dom, types.ModuleType)) - self.assertTrue(xml.dom.__name__ == 'xml.dom') - - def test_dotted_name_import_with_alias(self): - """Test dotted-name import with aliasing.""" - import CLR.System as myCLRSystem - self.assertTrue(is_clr_module(myCLRSystem)) - self.assertTrue(myCLRSystem.__name__ == 'System') - - import System as mySystem - self.assertTrue(is_clr_module(mySystem)) - self.assertTrue(mySystem.__name__ == 'System') - - self.assertTrue(mySystem is myCLRSystem) - - import xml.dom as myDom - self.assertTrue(isinstance(myDom, types.ModuleType)) - self.assertTrue(myDom.__name__ == 'xml.dom') - - def test_simple_import_from(self): - """Test simple 'import from'.""" - from CLR import System - self.assertTrue(is_clr_module(System)) - self.assertTrue(System.__name__ == 'System') - - from xml import dom - self.assertTrue(isinstance(dom, types.ModuleType)) - self.assertTrue(dom.__name__ == 'xml.dom') - - def test_simple_import_from_with_alias(self): - """Test simple 'import from' with aliasing.""" - from CLR import System as mySystem - self.assertTrue(is_clr_module(mySystem)) - self.assertTrue(mySystem.__name__ == 'System') - - from xml import dom as myDom - self.assertTrue(isinstance(myDom, types.ModuleType)) - self.assertTrue(myDom.__name__ == 'xml.dom') - - def test_dotted_name_import_from(self): - """Test dotted-name 'import from'.""" - from CLR.System import Xml - self.assertTrue(is_clr_module(Xml)) - self.assertTrue(Xml.__name__ == 'System.Xml') - - from CLR.System.Xml import XmlDocument - self.assertTrue(is_clr_class(XmlDocument)) - self.assertTrue(XmlDocument.__name__ == 'XmlDocument') - - from xml.dom import pulldom - self.assertTrue(isinstance(pulldom, types.ModuleType)) - self.assertTrue(pulldom.__name__ == 'xml.dom.pulldom') - - from xml.dom.pulldom import PullDOM - self.assertTrue(isinstance(PullDOM, ClassType)) - self.assertTrue(PullDOM.__name__ == 'PullDOM') - - def test_dotted_name_import_from_with_alias(self): - """Test dotted-name 'import from' with aliasing.""" - from CLR.System import Xml as myXml - self.assertTrue(is_clr_module(myXml)) - self.assertTrue(myXml.__name__ == 'System.Xml') - - from CLR.System.Xml import XmlDocument as myXmlDocument - self.assertTrue(is_clr_class(myXmlDocument)) - self.assertTrue(myXmlDocument.__name__ == 'XmlDocument') - - from xml.dom import pulldom as myPulldom - self.assertTrue(isinstance(myPulldom, types.ModuleType)) - self.assertTrue(myPulldom.__name__ == 'xml.dom.pulldom') - - from xml.dom.pulldom import PullDOM as myPullDOM - self.assertTrue(isinstance(myPullDOM, ClassType)) - self.assertTrue(myPullDOM.__name__ == 'PullDOM') - - def test_from_module_import_star(self): - """Test from module import * behavior.""" - count = len(locals().keys()) - m = __import__('CLR.System.Management', globals(), locals(), ['*']) - self.assertTrue(m.__name__ == 'System.Management') - self.assertTrue(is_clr_module(m)) - self.assertTrue(len(locals().keys()) > count + 1) - - m2 = __import__('System.Management', globals(), locals(), ['*']) - self.assertTrue(m2.__name__ == 'System.Management') - self.assertTrue(is_clr_module(m2)) - self.assertTrue(len(locals().keys()) > count + 1) - - self.assertTrue(m is m2) - - def test_explicit_assembly_load(self): - """Test explicit assembly loading using standard CLR tools.""" - from CLR.System.Reflection import Assembly - from CLR import System - import sys - - assembly = Assembly.LoadWithPartialName('System.Data') - self.assertTrue(assembly is not None) - - import CLR.System.Data - self.assertTrue('System.Data' in sys.modules) - - assembly = Assembly.LoadWithPartialName('SpamSpamSpamSpamEggsAndSpam') - self.assertTrue(assembly is None) - - def test_implicit_load_already_valid_namespace(self): - """Test implicit assembly load over an already valid namespace.""" - # In this case, the mscorlib assembly (loaded by default) defines - # a number of types in the System namespace. There is also a System - # assembly, which is _not_ loaded by default, which also contains - # types in the System namespace. The desired behavior is for the - # Python runtime to "do the right thing", allowing types from both - # assemblies to be found in the CLR.System module implicitly. - import CLR.System - self.assertTrue(is_clr_class(CLR.System.UriBuilder)) - - def test_import_non_existant_module(self): - """Test import failure for a non-existent module.""" - with self.assertRaises(ImportError): - import System.SpamSpamSpam - - with self.assertRaises(ImportError): - import CLR.System.SpamSpamSpam - - def test_lookup_no_namespace_type(self): - """Test lookup of types without a qualified namespace.""" - import CLR.Python.Test - import CLR - self.assertTrue(is_clr_class(CLR.NoNamespaceType)) + import sys + assert isinstance(sys, types.ModuleType) + assert sys.__name__ == 'sys' + + if PY3: + import http.client + assert isinstance(http.client, types.ModuleType) + assert http.client.__name__ == 'http.client' + + elif PY2: + import httplib + assert isinstance(httplib, types.ModuleType) + assert httplib.__name__ == 'httplib' + + +def test_simple_import_with_alias(): + """Test simple import with aliasing.""" + import CLR as myCLR + assert is_clr_root_module(myCLR) + assert myCLR.__name__ == 'clr' + + import sys as mySys + assert isinstance(mySys, types.ModuleType) + assert mySys.__name__ == 'sys' + + if PY3: + import http.client as myHttplib + assert isinstance(myHttplib, types.ModuleType) + assert myHttplib.__name__ == 'http.client' + + elif PY2: + import httplib as myHttplib + assert isinstance(myHttplib, types.ModuleType) + assert myHttplib.__name__ == 'httplib' + + +def test_dotted_name_import(): + """Test dotted-name import.""" + import CLR.System + assert is_clr_module(CLR.System) + assert CLR.System.__name__ == 'System' + + import System + assert is_clr_module(System) + assert System.__name__ == 'System' + + assert System is CLR.System + + import xml.dom + assert isinstance(xml.dom, types.ModuleType) + assert xml.dom.__name__ == 'xml.dom' + + +def test_dotted_name_import_with_alias(): + """Test dotted-name import with aliasing.""" + import CLR.System as myCLRSystem + assert is_clr_module(myCLRSystem) + assert myCLRSystem.__name__ == 'System' + + import System as mySystem + assert is_clr_module(mySystem) + assert mySystem.__name__ == 'System' + + assert mySystem is myCLRSystem + + import xml.dom as myDom + assert isinstance(myDom, types.ModuleType) + assert myDom.__name__ == 'xml.dom' + + +def test_simple_import_from(): + """Test simple 'import from'.""" + from CLR import System + assert is_clr_module(System) + assert System.__name__ == 'System' + + from xml import dom + assert isinstance(dom, types.ModuleType) + assert dom.__name__ == 'xml.dom' + + +def test_simple_import_from_with_alias(): + """Test simple 'import from' with aliasing.""" + from CLR import System as mySystem + assert is_clr_module(mySystem) + assert mySystem.__name__ == 'System' + + from xml import dom as myDom + assert isinstance(myDom, types.ModuleType) + assert myDom.__name__ == 'xml.dom' + + +def test_dotted_name_import_from(): + """Test dotted-name 'import from'.""" + from CLR.System import Xml + assert is_clr_module(Xml) + assert Xml.__name__ == 'System.Xml' - def test_module_lookup_recursion(self): - """Test for recursive lookup handling.""" - with self.assertRaises(ImportError): - from CLR import CLR + from CLR.System.Xml import XmlDocument + assert is_clr_class(XmlDocument) + assert XmlDocument.__name__ == 'XmlDocument' - with self.assertRaises(AttributeError): - import CLR - _ = CLR.CLR + from xml.dom import pulldom + assert isinstance(pulldom, types.ModuleType) + assert pulldom.__name__ == 'xml.dom.pulldom' - def test_module_get_attr(self): - """Test module getattr behavior.""" - import CLR.System as System + from xml.dom.pulldom import PullDOM + assert isinstance(PullDOM, ClassType) + assert PullDOM.__name__ == 'PullDOM' - int_type = System.Int32 - self.assertTrue(is_clr_class(int_type)) - module = System.Xml - self.assertTrue(is_clr_module(module)) +def test_dotted_name_import_from_with_alias(): + """Test dotted-name 'import from' with aliasing.""" + from CLR.System import Xml as myXml + assert is_clr_module(myXml) + assert myXml.__name__ == 'System.Xml' - with self.assertRaises(AttributeError): - _ = System.Spam + from CLR.System.Xml import XmlDocument as myXmlDocument + assert is_clr_class(myXmlDocument) + assert myXmlDocument.__name__ == 'XmlDocument' - with self.assertRaises(TypeError): - _ = getattr(System, 1) + from xml.dom import pulldom as myPulldom + assert isinstance(myPulldom, types.ModuleType) + assert myPulldom.__name__ == 'xml.dom.pulldom' - def test_multiple_imports(self): - # import CLR did raise a Seg Fault once - # test if the Exceptions.warn() method still causes it - for _ in range(100): - import CLR - _ = CLR + from xml.dom.pulldom import PullDOM as myPullDOM + assert isinstance(myPullDOM, ClassType) + assert myPullDOM.__name__ == 'PullDOM' -def test_suite(): - return unittest.makeSuite(CompatibilityTests) +def test_from_module_import_star(): + """Test from module import * behavior.""" + count = len(locals().keys()) + m = __import__('CLR.System.Management', globals(), locals(), ['*']) + assert m.__name__ == 'System.Management' + assert is_clr_module(m) + assert len(locals().keys()) > count + 1 + + m2 = __import__('System.Management', globals(), locals(), ['*']) + assert m2.__name__ == 'System.Management' + assert is_clr_module(m2) + assert len(locals().keys()) > count + 1 + + assert m is m2 + + +def test_explicit_assembly_load(): + """Test explicit assembly loading using standard CLR tools.""" + from CLR.System.Reflection import Assembly + from CLR import System + import sys + + assembly = Assembly.LoadWithPartialName('System.Data') + assert assembly is not None + + import CLR.System.Data + assert 'System.Data' in sys.modules + + assembly = Assembly.LoadWithPartialName('SpamSpamSpamSpamEggsAndSpam') + assert assembly is None + + +def test_implicit_load_already_valid_namespace(): + """Test implicit assembly load over an already valid namespace.""" + # In this case, the mscorlib assembly (loaded by default) defines + # a number of types in the System namespace. There is also a System + # assembly, which is _not_ loaded by default, which also contains + # types in the System namespace. The desired behavior is for the + # Python runtime to "do the right thing", allowing types from both + # assemblies to be found in the CLR.System module implicitly. + import CLR.System + assert is_clr_class(CLR.System.UriBuilder) + + +def test_import_non_existant_module(): + """Test import failure for a non-existent module.""" + with pytest.raises(ImportError): + import System.SpamSpamSpam + + with pytest.raises(ImportError): + import CLR.System.SpamSpamSpam + + +def test_lookup_no_namespace_type(): + """Test lookup of types without a qualified namespace.""" + import CLR.Python.Test + import CLR + assert is_clr_class(CLR.NoNamespaceType) + + +def test_module_lookup_recursion(): + """Test for recursive lookup handling.""" + with pytest.raises(ImportError): + from CLR import CLR + + with pytest.raises(AttributeError): + import CLR + _ = CLR.CLR + + +def test_module_get_attr(): + """Test module getattr behavior.""" + import CLR.System as System + + int_type = System.Int32 + assert is_clr_class(int_type) + + module = System.Xml + assert is_clr_module(module) + + with pytest.raises(AttributeError): + _ = System.Spam + + with pytest.raises(TypeError): + _ = getattr(System, 1) + + +def test_multiple_imports(): + # import CLR did raise a Seg Fault once + # test if the Exceptions.warn() method still causes it + for _ in range(100): + import CLR + _ = CLR diff --git a/src/tests/test_constructors.py b/src/tests/test_constructors.py index 0039f9bf3..5e5489630 100644 --- a/src/tests/test_constructors.py +++ b/src/tests/test_constructors.py @@ -1,50 +1,46 @@ # -*- coding: utf-8 -*- -import unittest +"""Test CLR class constructor support.""" import System -class ConstructorTests(unittest.TestCase): - """Test CLR class constructor support.""" +def test_enum_constructor(): + """Test enum constructor args""" + from System import TypeCode + from Python.Test import EnumConstructorTest - def test_enum_constructor(self): - """Test enum constructor args""" - from System import TypeCode - from Python.Test import EnumConstructorTest + ob = EnumConstructorTest(TypeCode.Int32) + assert ob.value == TypeCode.Int32 - ob = EnumConstructorTest(TypeCode.Int32) - self.assertTrue(ob.value == TypeCode.Int32) - def test_flags_constructor(self): - """Test flags constructor args""" - from Python.Test import FlagsConstructorTest - from System.IO import FileAccess +def test_flags_constructor(): + """Test flags constructor args""" + from Python.Test import FlagsConstructorTest + from System.IO import FileAccess - flags = FileAccess.Read | FileAccess.Write - ob = FlagsConstructorTest(flags) - self.assertTrue(ob.value == flags) + flags = FileAccess.Read | FileAccess.Write + ob = FlagsConstructorTest(flags) + assert ob.value == flags - def test_struct_constructor(self): - """Test struct constructor args""" - from System import Guid - from Python.Test import StructConstructorTest - guid = Guid.NewGuid() - ob = StructConstructorTest(guid) - self.assertTrue(ob.value == guid) +def test_struct_constructor(): + """Test struct constructor args""" + from System import Guid + from Python.Test import StructConstructorTest - def test_subclass_constructor(self): - """Test subclass constructor args""" - from Python.Test import SubclassConstructorTest + guid = Guid.NewGuid() + ob = StructConstructorTest(guid) + assert ob.value == guid - class Sub(System.Exception): - pass - instance = Sub() - ob = SubclassConstructorTest(instance) - self.assertTrue(isinstance(ob.value, System.Exception)) +def test_subclass_constructor(): + """Test subclass constructor args""" + from Python.Test import SubclassConstructorTest + class Sub(System.Exception): + pass -def test_suite(): - return unittest.makeSuite(ConstructorTests) + instance = Sub() + ob = SubclassConstructorTest(instance) + assert isinstance(ob.value, System.Exception) diff --git a/src/tests/test_conversion.py b/src/tests/test_conversion.py index 0d0cd4008..ac263ef5d 100644 --- a/src/tests/test_conversion.py +++ b/src/tests/test_conversion.py @@ -1,684 +1,699 @@ # -*- coding: utf-8 -*- -import unittest +"""Test CLR <-> Python type conversions.""" import System +import pytest from Python.Test import ConversionTest -from _compat import indexbytes, long, unichr +from ._compat import indexbytes, long, unichr -class ConversionTests(unittest.TestCase): - """Test CLR <-> Python type conversions.""" +def test_bool_conversion(): + """Test bool conversion.""" + ob = ConversionTest() + assert ob.BooleanField is False + assert ob.BooleanField is False + assert ob.BooleanField == 0 - def test_bool_conversion(self): - """Test bool conversion.""" - ob = ConversionTest() - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField == 0) - - ob.BooleanField = True - self.assertTrue(ob.BooleanField is True) - self.assertTrue(ob.BooleanField is True) - self.assertTrue(ob.BooleanField == 1) - - ob.BooleanField = False - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField == 0) - - ob.BooleanField = 1 - self.assertTrue(ob.BooleanField is True) - self.assertTrue(ob.BooleanField is True) - self.assertTrue(ob.BooleanField == 1) - - ob.BooleanField = 0 - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField == 0) - - ob.BooleanField = System.Boolean(None) - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField == 0) - - ob.BooleanField = System.Boolean('') - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField == 0) - - ob.BooleanField = System.Boolean(0) - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField is False) - self.assertTrue(ob.BooleanField == 0) - - ob.BooleanField = System.Boolean(1) - self.assertTrue(ob.BooleanField is True) - self.assertTrue(ob.BooleanField is True) - self.assertTrue(ob.BooleanField == 1) - - ob.BooleanField = System.Boolean('a') - self.assertTrue(ob.BooleanField is True) - self.assertTrue(ob.BooleanField is True) - self.assertTrue(ob.BooleanField == 1) - - def test_sbyte_conversion(self): - """Test sbyte conversion.""" - self.assertTrue(System.SByte.MaxValue == 127) - self.assertTrue(System.SByte.MinValue == -128) + ob.BooleanField = True + assert ob.BooleanField is True + assert ob.BooleanField is True + assert ob.BooleanField == 1 - ob = ConversionTest() - self.assertTrue(ob.SByteField == 0) + ob.BooleanField = False + assert ob.BooleanField is False + assert ob.BooleanField is False + assert ob.BooleanField == 0 - ob.SByteField = 127 - self.assertTrue(ob.SByteField == 127) + ob.BooleanField = 1 + assert ob.BooleanField is True + assert ob.BooleanField is True + assert ob.BooleanField == 1 - ob.SByteField = -128 - self.assertTrue(ob.SByteField == -128) + ob.BooleanField = 0 + assert ob.BooleanField is False + assert ob.BooleanField is False + assert ob.BooleanField == 0 - ob.SByteField = System.SByte(127) - self.assertTrue(ob.SByteField == 127) + ob.BooleanField = System.Boolean(None) + assert ob.BooleanField is False + assert ob.BooleanField is False + assert ob.BooleanField == 0 - ob.SByteField = System.SByte(-128) - self.assertTrue(ob.SByteField == -128) + ob.BooleanField = System.Boolean('') + assert ob.BooleanField is False + assert ob.BooleanField is False + assert ob.BooleanField == 0 - with self.assertRaises(TypeError): - ConversionTest().SByteField = "spam" + ob.BooleanField = System.Boolean(0) + assert ob.BooleanField is False + assert ob.BooleanField is False + assert ob.BooleanField == 0 - with self.assertRaises(TypeError): - ConversionTest().SByteField = None + ob.BooleanField = System.Boolean(1) + assert ob.BooleanField is True + assert ob.BooleanField is True + assert ob.BooleanField == 1 - with self.assertRaises(OverflowError): - ConversionTest().SByteField = 128 + ob.BooleanField = System.Boolean('a') + assert ob.BooleanField is True + assert ob.BooleanField is True + assert ob.BooleanField == 1 - with self.assertRaises(OverflowError): - ConversionTest().SByteField = -129 - with self.assertRaises(OverflowError): - _ = System.SByte(128) +def test_sbyte_conversion(): + """Test sbyte conversion.""" + assert System.SByte.MaxValue == 127 + assert System.SByte.MinValue == -128 - with self.assertRaises(OverflowError): - _ = System.SByte(-129) + ob = ConversionTest() + assert ob.SByteField == 0 - def test_byte_conversion(self): - """Test byte conversion.""" - self.assertTrue(System.Byte.MaxValue == 255) - self.assertTrue(System.Byte.MinValue == 0) + ob.SByteField = 127 + assert ob.SByteField == 127 - ob = ConversionTest() - self.assertTrue(ob.ByteField == 0) + ob.SByteField = -128 + assert ob.SByteField == -128 - ob.ByteField = 255 - self.assertTrue(ob.ByteField == 255) + ob.SByteField = System.SByte(127) + assert ob.SByteField == 127 - ob.ByteField = 0 - self.assertTrue(ob.ByteField == 0) + ob.SByteField = System.SByte(-128) + assert ob.SByteField == -128 - ob.ByteField = System.Byte(255) - self.assertTrue(ob.ByteField == 255) + with pytest.raises(TypeError): + ConversionTest().SByteField = "spam" - ob.ByteField = System.Byte(0) - self.assertTrue(ob.ByteField == 0) + with pytest.raises(TypeError): + ConversionTest().SByteField = None - with self.assertRaises(TypeError): - ConversionTest().ByteField = "spam" + with pytest.raises(OverflowError): + ConversionTest().SByteField = 128 - with self.assertRaises(TypeError): - ConversionTest().ByteField = None + with pytest.raises(OverflowError): + ConversionTest().SByteField = -129 - with self.assertRaises(OverflowError): - ConversionTest().ByteField = 256 + with pytest.raises(OverflowError): + _ = System.SByte(128) - with self.assertRaises(OverflowError): - ConversionTest().ByteField = -1 + with pytest.raises(OverflowError): + _ = System.SByte(-129) - with self.assertRaises(OverflowError): - _ = System.Byte(256) - with self.assertRaises(OverflowError): - _ = System.Byte(-1) +def test_byte_conversion(): + """Test byte conversion.""" + assert System.Byte.MaxValue == 255 + assert System.Byte.MinValue == 0 - def test_char_conversion(self): - """Test char conversion.""" - self.assertTrue(System.Char.MaxValue == unichr(65535)) - self.assertTrue(System.Char.MinValue == unichr(0)) + ob = ConversionTest() + assert ob.ByteField == 0 - ob = ConversionTest() - self.assertTrue(ob.CharField == u'A') + ob.ByteField = 255 + assert ob.ByteField == 255 - ob.CharField = 'B' - self.assertTrue(ob.CharField == u'B') + ob.ByteField = 0 + assert ob.ByteField == 0 - ob.CharField = u'B' - self.assertTrue(ob.CharField == u'B') + ob.ByteField = System.Byte(255) + assert ob.ByteField == 255 - ob.CharField = 67 - self.assertTrue(ob.CharField == u'C') + ob.ByteField = System.Byte(0) + assert ob.ByteField == 0 - with self.assertRaises(OverflowError): - ConversionTest().CharField = 65536 + with pytest.raises(TypeError): + ConversionTest().ByteField = "spam" - with self.assertRaises(OverflowError): - ConversionTest().CharField = -1 + with pytest.raises(TypeError): + ConversionTest().ByteField = None - with self.assertRaises(TypeError): - ConversionTest().CharField = None + with pytest.raises(OverflowError): + ConversionTest().ByteField = 256 - def test_int16_conversion(self): - """Test int16 conversion.""" - self.assertTrue(System.Int16.MaxValue == 32767) - self.assertTrue(System.Int16.MinValue == -32768) + with pytest.raises(OverflowError): + ConversionTest().ByteField = -1 - ob = ConversionTest() - self.assertTrue(ob.Int16Field == 0) + with pytest.raises(OverflowError): + _ = System.Byte(256) - ob.Int16Field = 32767 - self.assertTrue(ob.Int16Field == 32767) + with pytest.raises(OverflowError): + _ = System.Byte(-1) - ob.Int16Field = -32768 - self.assertTrue(ob.Int16Field == -32768) - ob.Int16Field = System.Int16(32767) - self.assertTrue(ob.Int16Field == 32767) +def test_char_conversion(): + """Test char conversion.""" + assert System.Char.MaxValue == unichr(65535) + assert System.Char.MinValue == unichr(0) - ob.Int16Field = System.Int16(-32768) - self.assertTrue(ob.Int16Field == -32768) + ob = ConversionTest() + assert ob.CharField == u'A' - with self.assertRaises(TypeError): - ConversionTest().Int16Field = "spam" + ob.CharField = 'B' + assert ob.CharField == u'B' - with self.assertRaises(TypeError): - ConversionTest().Int16Field = None + ob.CharField = u'B' + assert ob.CharField == u'B' - with self.assertRaises(OverflowError): - ConversionTest().Int16Field = 32768 + ob.CharField = 67 + assert ob.CharField == u'C' - with self.assertRaises(OverflowError): - ConversionTest().Int16Field = -32769 + with pytest.raises(OverflowError): + ConversionTest().CharField = 65536 - with self.assertRaises(OverflowError): - _ = System.Int16(32768) + with pytest.raises(OverflowError): + ConversionTest().CharField = -1 - with self.assertRaises(OverflowError): - _ = System.Int16(-32769) + with pytest.raises(TypeError): + ConversionTest().CharField = None - def test_int32_conversion(self): - """Test int32 conversion.""" - self.assertTrue(System.Int32.MaxValue == 2147483647) - self.assertTrue(System.Int32.MinValue == -2147483648) - ob = ConversionTest() - self.assertTrue(ob.Int32Field == 0) +def test_int16_conversion(): + """Test int16 conversion.""" + assert System.Int16.MaxValue == 32767 + assert System.Int16.MinValue == -32768 - ob.Int32Field = 2147483647 - self.assertTrue(ob.Int32Field == 2147483647) + ob = ConversionTest() + assert ob.Int16Field == 0 - ob.Int32Field = -2147483648 - self.assertTrue(ob.Int32Field == -2147483648) + ob.Int16Field = 32767 + assert ob.Int16Field == 32767 - ob.Int32Field = System.Int32(2147483647) - self.assertTrue(ob.Int32Field == 2147483647) + ob.Int16Field = -32768 + assert ob.Int16Field == -32768 - ob.Int32Field = System.Int32(-2147483648) - self.assertTrue(ob.Int32Field == -2147483648) + ob.Int16Field = System.Int16(32767) + assert ob.Int16Field == 32767 - with self.assertRaises(TypeError): - ConversionTest().Int32Field = "spam" + ob.Int16Field = System.Int16(-32768) + assert ob.Int16Field == -32768 - with self.assertRaises(TypeError): - ConversionTest().Int32Field = None + with pytest.raises(TypeError): + ConversionTest().Int16Field = "spam" - with self.assertRaises(OverflowError): - ConversionTest().Int32Field = 2147483648 + with pytest.raises(TypeError): + ConversionTest().Int16Field = None - with self.assertRaises(OverflowError): - ConversionTest().Int32Field = -2147483649 + with pytest.raises(OverflowError): + ConversionTest().Int16Field = 32768 - with self.assertRaises(OverflowError): - _ = System.Int32(2147483648) + with pytest.raises(OverflowError): + ConversionTest().Int16Field = -32769 - with self.assertRaises(OverflowError): - _ = System.Int32(-2147483649) + with pytest.raises(OverflowError): + _ = System.Int16(32768) - def test_int64_conversion(self): - """Test int64 conversion.""" - self.assertTrue(System.Int64.MaxValue == long(9223372036854775807)) - self.assertTrue(System.Int64.MinValue == long(-9223372036854775808)) + with pytest.raises(OverflowError): + _ = System.Int16(-32769) - ob = ConversionTest() - self.assertTrue(ob.Int64Field == 0) - ob.Int64Field = long(9223372036854775807) - self.assertTrue(ob.Int64Field == long(9223372036854775807)) +def test_int32_conversion(): + """Test int32 conversion.""" + assert System.Int32.MaxValue == 2147483647 + assert System.Int32.MinValue == -2147483648 - ob.Int64Field = long(-9223372036854775808) - self.assertTrue(ob.Int64Field == long(-9223372036854775808)) + ob = ConversionTest() + assert ob.Int32Field == 0 - ob.Int64Field = System.Int64(long(9223372036854775807)) - self.assertTrue(ob.Int64Field == long(9223372036854775807)) + ob.Int32Field = 2147483647 + assert ob.Int32Field == 2147483647 - ob.Int64Field = System.Int64(long(-9223372036854775808)) - self.assertTrue(ob.Int64Field == long(-9223372036854775808)) + ob.Int32Field = -2147483648 + assert ob.Int32Field == -2147483648 - with self.assertRaises(TypeError): - ConversionTest().Int64Field = "spam" + ob.Int32Field = System.Int32(2147483647) + assert ob.Int32Field == 2147483647 - with self.assertRaises(TypeError): - ConversionTest().Int64Field = None + ob.Int32Field = System.Int32(-2147483648) + assert ob.Int32Field == -2147483648 - with self.assertRaises(OverflowError): - ConversionTest().Int64Field = long(9223372036854775808) + with pytest.raises(TypeError): + ConversionTest().Int32Field = "spam" - with self.assertRaises(OverflowError): - ConversionTest().Int64Field = long(-9223372036854775809) + with pytest.raises(TypeError): + ConversionTest().Int32Field = None - with self.assertRaises(OverflowError): - _ = System.Int64(long(9223372036854775808)) + with pytest.raises(OverflowError): + ConversionTest().Int32Field = 2147483648 - with self.assertRaises(OverflowError): - _ = System.Int64(long(-9223372036854775809)) + with pytest.raises(OverflowError): + ConversionTest().Int32Field = -2147483649 - def test_uint16_conversion(self): - """Test uint16 conversion.""" - self.assertTrue(System.UInt16.MaxValue == 65535) - self.assertTrue(System.UInt16.MinValue == 0) + with pytest.raises(OverflowError): + _ = System.Int32(2147483648) - ob = ConversionTest() - self.assertTrue(ob.UInt16Field == 0) + with pytest.raises(OverflowError): + _ = System.Int32(-2147483649) - ob.UInt16Field = 65535 - self.assertTrue(ob.UInt16Field == 65535) - ob.UInt16Field = -0 - self.assertTrue(ob.UInt16Field == 0) +def test_int64_conversion(): + """Test int64 conversion.""" + assert System.Int64.MaxValue == long(9223372036854775807) + assert System.Int64.MinValue == long(-9223372036854775808) - ob.UInt16Field = System.UInt16(65535) - self.assertTrue(ob.UInt16Field == 65535) + ob = ConversionTest() + assert ob.Int64Field == 0 - ob.UInt16Field = System.UInt16(0) - self.assertTrue(ob.UInt16Field == 0) + ob.Int64Field = long(9223372036854775807) + assert ob.Int64Field == long(9223372036854775807) - with self.assertRaises(TypeError): - ConversionTest().UInt16Field = "spam" + ob.Int64Field = long(-9223372036854775808) + assert ob.Int64Field == long(-9223372036854775808) - with self.assertRaises(TypeError): - ConversionTest().UInt16Field = None + ob.Int64Field = System.Int64(long(9223372036854775807)) + assert ob.Int64Field == long(9223372036854775807) - with self.assertRaises(OverflowError): - ConversionTest().UInt16Field = 65536 + ob.Int64Field = System.Int64(long(-9223372036854775808)) + assert ob.Int64Field == long(-9223372036854775808) - with self.assertRaises(OverflowError): - ConversionTest().UInt16Field = -1 + with pytest.raises(TypeError): + ConversionTest().Int64Field = "spam" - with self.assertRaises(OverflowError): - _ = System.UInt16(65536) + with pytest.raises(TypeError): + ConversionTest().Int64Field = None - with self.assertRaises(OverflowError): - _ = System.UInt16(-1) + with pytest.raises(OverflowError): + ConversionTest().Int64Field = long(9223372036854775808) - def test_uint32_conversion(self): - """Test uint32 conversion.""" - self.assertTrue(System.UInt32.MaxValue == long(4294967295)) - self.assertTrue(System.UInt32.MinValue == 0) + with pytest.raises(OverflowError): + ConversionTest().Int64Field = long(-9223372036854775809) - ob = ConversionTest() - self.assertTrue(ob.UInt32Field == 0) + with pytest.raises(OverflowError): + _ = System.Int64(long(9223372036854775808)) - ob.UInt32Field = long(4294967295) - self.assertTrue(ob.UInt32Field == long(4294967295)) + with pytest.raises(OverflowError): + _ = System.Int64(long(-9223372036854775809)) - ob.UInt32Field = -0 - self.assertTrue(ob.UInt32Field == 0) - ob.UInt32Field = System.UInt32(long(4294967295)) - self.assertTrue(ob.UInt32Field == long(4294967295)) +def test_uint16_conversion(): + """Test uint16 conversion.""" + assert System.UInt16.MaxValue == 65535 + assert System.UInt16.MinValue == 0 - ob.UInt32Field = System.UInt32(0) - self.assertTrue(ob.UInt32Field == 0) + ob = ConversionTest() + assert ob.UInt16Field == 0 - with self.assertRaises(TypeError): - ConversionTest().UInt32Field = "spam" + ob.UInt16Field = 65535 + assert ob.UInt16Field == 65535 - with self.assertRaises(TypeError): - ConversionTest().UInt32Field = None + ob.UInt16Field = -0 + assert ob.UInt16Field == 0 - with self.assertRaises(OverflowError): - ConversionTest().UInt32Field = long(4294967296) + ob.UInt16Field = System.UInt16(65535) + assert ob.UInt16Field == 65535 - with self.assertRaises(OverflowError): - ConversionTest().UInt32Field = -1 + ob.UInt16Field = System.UInt16(0) + assert ob.UInt16Field == 0 - with self.assertRaises(OverflowError): - _ = System.UInt32(long(4294967296)) + with pytest.raises(TypeError): + ConversionTest().UInt16Field = "spam" - with self.assertRaises(OverflowError): - _ = System.UInt32(-1) + with pytest.raises(TypeError): + ConversionTest().UInt16Field = None - def test_uint64_conversion(self): - """Test uint64 conversion.""" - self.assertTrue(System.UInt64.MaxValue == long(18446744073709551615)) - self.assertTrue(System.UInt64.MinValue == 0) + with pytest.raises(OverflowError): + ConversionTest().UInt16Field = 65536 - ob = ConversionTest() - self.assertTrue(ob.UInt64Field == 0) + with pytest.raises(OverflowError): + ConversionTest().UInt16Field = -1 - ob.UInt64Field = long(18446744073709551615) - self.assertTrue(ob.UInt64Field == long(18446744073709551615)) + with pytest.raises(OverflowError): + _ = System.UInt16(65536) - ob.UInt64Field = -0 - self.assertTrue(ob.UInt64Field == 0) + with pytest.raises(OverflowError): + _ = System.UInt16(-1) - ob.UInt64Field = System.UInt64(long(18446744073709551615)) - self.assertTrue(ob.UInt64Field == long(18446744073709551615)) - ob.UInt64Field = System.UInt64(0) - self.assertTrue(ob.UInt64Field == 0) +def test_uint32_conversion(): + """Test uint32 conversion.""" + assert System.UInt32.MaxValue == long(4294967295) + assert System.UInt32.MinValue == 0 - with self.assertRaises(TypeError): - ConversionTest().UInt64Field = "spam" + ob = ConversionTest() + assert ob.UInt32Field == 0 - with self.assertRaises(TypeError): - ConversionTest().UInt64Field = None + ob.UInt32Field = long(4294967295) + assert ob.UInt32Field == long(4294967295) - with self.assertRaises(OverflowError): - ConversionTest().UInt64Field = long(18446744073709551616) + ob.UInt32Field = -0 + assert ob.UInt32Field == 0 - with self.assertRaises(OverflowError): - ConversionTest().UInt64Field = -1 + ob.UInt32Field = System.UInt32(long(4294967295)) + assert ob.UInt32Field == long(4294967295) - with self.assertRaises(OverflowError): - _ = System.UInt64(long(18446744073709551616)) + ob.UInt32Field = System.UInt32(0) + assert ob.UInt32Field == 0 - with self.assertRaises(OverflowError): - _ = System.UInt64(-1) + with pytest.raises(TypeError): + ConversionTest().UInt32Field = "spam" - def test_single_conversion(self): - """Test single conversion.""" - self.assertTrue(System.Single.MaxValue == 3.402823e38) - self.assertTrue(System.Single.MinValue == -3.402823e38) + with pytest.raises(TypeError): + ConversionTest().UInt32Field = None - ob = ConversionTest() - self.assertTrue(ob.SingleField == 0.0) + with pytest.raises(OverflowError): + ConversionTest().UInt32Field = long(4294967296) - ob.SingleField = 3.402823e38 - self.assertTrue(ob.SingleField == 3.402823e38) + with pytest.raises(OverflowError): + ConversionTest().UInt32Field = -1 - ob.SingleField = -3.402823e38 - self.assertTrue(ob.SingleField == -3.402823e38) + with pytest.raises(OverflowError): + _ = System.UInt32(long(4294967296)) - ob.SingleField = System.Single(3.402823e38) - self.assertTrue(ob.SingleField == 3.402823e38) + with pytest.raises(OverflowError): + _ = System.UInt32(-1) - ob.SingleField = System.Single(-3.402823e38) - self.assertTrue(ob.SingleField == -3.402823e38) - with self.assertRaises(TypeError): - ConversionTest().SingleField = "spam" +def test_uint64_conversion(): + """Test uint64 conversion.""" + assert System.UInt64.MaxValue == long(18446744073709551615) + assert System.UInt64.MinValue == 0 - with self.assertRaises(TypeError): - ConversionTest().SingleField = None + ob = ConversionTest() + assert ob.UInt64Field == 0 - with self.assertRaises(OverflowError): - ConversionTest().SingleField = 3.402824e38 + ob.UInt64Field = long(18446744073709551615) + assert ob.UInt64Field == long(18446744073709551615) - with self.assertRaises(OverflowError): - ConversionTest().SingleField = -3.402824e38 + ob.UInt64Field = -0 + assert ob.UInt64Field == 0 - with self.assertRaises(OverflowError): - _ = System.Single(3.402824e38) + ob.UInt64Field = System.UInt64(long(18446744073709551615)) + assert ob.UInt64Field == long(18446744073709551615) - with self.assertRaises(OverflowError): - _ = System.Single(-3.402824e38) + ob.UInt64Field = System.UInt64(0) + assert ob.UInt64Field == 0 - def test_double_conversion(self): - """Test double conversion.""" - self.assertTrue(System.Double.MaxValue == 1.7976931348623157e308) - self.assertTrue(System.Double.MinValue == -1.7976931348623157e308) + with pytest.raises(TypeError): + ConversionTest().UInt64Field = "spam" - ob = ConversionTest() - self.assertTrue(ob.DoubleField == 0.0) + with pytest.raises(TypeError): + ConversionTest().UInt64Field = None - ob.DoubleField = 1.7976931348623157e308 - self.assertTrue(ob.DoubleField == 1.7976931348623157e308) + with pytest.raises(OverflowError): + ConversionTest().UInt64Field = long(18446744073709551616) - ob.DoubleField = -1.7976931348623157e308 - self.assertTrue(ob.DoubleField == -1.7976931348623157e308) + with pytest.raises(OverflowError): + ConversionTest().UInt64Field = -1 - ob.DoubleField = System.Double(1.7976931348623157e308) - self.assertTrue(ob.DoubleField == 1.7976931348623157e308) + with pytest.raises(OverflowError): + _ = System.UInt64(long(18446744073709551616)) - ob.DoubleField = System.Double(-1.7976931348623157e308) - self.assertTrue(ob.DoubleField == -1.7976931348623157e308) + with pytest.raises(OverflowError): + _ = System.UInt64(-1) - with self.assertRaises(TypeError): - ConversionTest().DoubleField = "spam" - with self.assertRaises(TypeError): - ConversionTest().DoubleField = None +def test_single_conversion(): + """Test single conversion.""" + assert System.Single.MaxValue == 3.402823e38 + assert System.Single.MinValue == -3.402823e38 - with self.assertRaises(OverflowError): - ConversionTest().DoubleField = 1.7976931348623159e308 + ob = ConversionTest() + assert ob.SingleField == 0.0 - with self.assertRaises(OverflowError): - ConversionTest().DoubleField = -1.7976931348623159e308 + ob.SingleField = 3.402823e38 + assert ob.SingleField == 3.402823e38 - with self.assertRaises(OverflowError): - _ = System.Double(1.7976931348623159e308) + ob.SingleField = -3.402823e38 + assert ob.SingleField == -3.402823e38 - with self.assertRaises(OverflowError): - _ = System.Double(-1.7976931348623159e308) + ob.SingleField = System.Single(3.402823e38) + assert ob.SingleField == 3.402823e38 - def test_decimal_conversion(self): - """Test decimal conversion.""" - from System import Decimal + ob.SingleField = System.Single(-3.402823e38) + assert ob.SingleField == -3.402823e38 - max_d = Decimal.Parse("79228162514264337593543950335") - min_d = Decimal.Parse("-79228162514264337593543950335") + with pytest.raises(TypeError): + ConversionTest().SingleField = "spam" - self.assertTrue(Decimal.ToInt64(Decimal(10)) == long(10)) + with pytest.raises(TypeError): + ConversionTest().SingleField = None - ob = ConversionTest() - self.assertTrue(ob.DecimalField == Decimal(0)) + with pytest.raises(OverflowError): + ConversionTest().SingleField = 3.402824e38 - ob.DecimalField = Decimal(10) - self.assertTrue(ob.DecimalField == Decimal(10)) + with pytest.raises(OverflowError): + ConversionTest().SingleField = -3.402824e38 - ob.DecimalField = Decimal.One - self.assertTrue(ob.DecimalField == Decimal.One) + with pytest.raises(OverflowError): + _ = System.Single(3.402824e38) - ob.DecimalField = Decimal.Zero - self.assertTrue(ob.DecimalField == Decimal.Zero) + with pytest.raises(OverflowError): + _ = System.Single(-3.402824e38) - ob.DecimalField = max_d - self.assertTrue(ob.DecimalField == max_d) - ob.DecimalField = min_d - self.assertTrue(ob.DecimalField == min_d) +def test_double_conversion(): + """Test double conversion.""" + assert System.Double.MaxValue == 1.7976931348623157e308 + assert System.Double.MinValue == -1.7976931348623157e308 - with self.assertRaises(TypeError): - ConversionTest().DecimalField = None + ob = ConversionTest() + assert ob.DoubleField == 0.0 - with self.assertRaises(TypeError): - ConversionTest().DecimalField = "spam" + ob.DoubleField = 1.7976931348623157e308 + assert ob.DoubleField == 1.7976931348623157e308 - with self.assertRaises(TypeError): - ConversionTest().DecimalField = 1 + ob.DoubleField = -1.7976931348623157e308 + assert ob.DoubleField == -1.7976931348623157e308 - def test_string_conversion(self): - """Test string / unicode conversion.""" - ob = ConversionTest() + ob.DoubleField = System.Double(1.7976931348623157e308) + assert ob.DoubleField == 1.7976931348623157e308 - self.assertTrue(ob.StringField == "spam") - self.assertTrue(ob.StringField == u"spam") + ob.DoubleField = System.Double(-1.7976931348623157e308) + assert ob.DoubleField == -1.7976931348623157e308 - ob.StringField = "eggs" - self.assertTrue(ob.StringField == "eggs") - self.assertTrue(ob.StringField == u"eggs") + with pytest.raises(TypeError): + ConversionTest().DoubleField = "spam" - ob.StringField = u"spam" - self.assertTrue(ob.StringField == "spam") - self.assertTrue(ob.StringField == u"spam") + with pytest.raises(TypeError): + ConversionTest().DoubleField = None - ob.StringField = u'\uffff\uffff' - self.assertTrue(ob.StringField == u'\uffff\uffff') + with pytest.raises(OverflowError): + ConversionTest().DoubleField = 1.7976931348623159e308 - ob.StringField = System.String("spam") - self.assertTrue(ob.StringField == "spam") - self.assertTrue(ob.StringField == u"spam") + with pytest.raises(OverflowError): + ConversionTest().DoubleField = -1.7976931348623159e308 - ob.StringField = System.String(u'\uffff\uffff') - self.assertTrue(ob.StringField == u'\uffff\uffff') + with pytest.raises(OverflowError): + _ = System.Double(1.7976931348623159e308) - ob.StringField = None - self.assertTrue(ob.StringField is None) + with pytest.raises(OverflowError): + _ = System.Double(-1.7976931348623159e308) - with self.assertRaises(TypeError): - ConversionTest().StringField = 1 - def test_interface_conversion(self): - """Test interface conversion.""" - from Python.Test import Spam, ISpam +def test_decimal_conversion(): + """Test decimal conversion.""" + from System import Decimal - ob = ConversionTest() + max_d = Decimal.Parse("79228162514264337593543950335") + min_d = Decimal.Parse("-79228162514264337593543950335") - self.assertTrue(ISpam(ob.SpamField).GetValue() == "spam") - self.assertTrue(ob.SpamField.GetValue() == "spam") + assert Decimal.ToInt64(Decimal(10)) == long(10) - ob.SpamField = Spam("eggs") - self.assertTrue(ISpam(ob.SpamField).GetValue() == "eggs") - self.assertTrue(ob.SpamField.GetValue() == "eggs") + ob = ConversionTest() + assert ob.DecimalField == Decimal(0) - # need to test spam subclass here. + ob.DecimalField = Decimal(10) + assert ob.DecimalField == Decimal(10) - ob.SpamField = None - self.assertTrue(ob.SpamField is None) + ob.DecimalField = Decimal.One + assert ob.DecimalField == Decimal.One - with self.assertRaises(TypeError): - ob = ConversionTest() - ob.SpamField = System.String("bad") + ob.DecimalField = Decimal.Zero + assert ob.DecimalField == Decimal.Zero - with self.assertRaises(TypeError): - ob = ConversionTest() - ob.SpamField = System.Int32(1) + ob.DecimalField = max_d + assert ob.DecimalField == max_d - def test_object_conversion(self): - """Test ob conversion.""" - from Python.Test import Spam + ob.DecimalField = min_d + assert ob.DecimalField == min_d - ob = ConversionTest() - self.assertTrue(ob.ObjectField is None) + with pytest.raises(TypeError): + ConversionTest().DecimalField = None - ob.ObjectField = Spam("eggs") - self.assertTrue(ob.ObjectField.__class__.__name__ == "Spam") - self.assertTrue(ob.ObjectField.GetValue() == "eggs") + with pytest.raises(TypeError): + ConversionTest().DecimalField = "spam" - ob.ObjectField = None - self.assertTrue(ob.ObjectField is None) + with pytest.raises(TypeError): + ConversionTest().DecimalField = 1 - ob.ObjectField = System.String("spam") - self.assertTrue(ob.ObjectField == "spam") - ob.ObjectField = System.Int32(1) - self.assertTrue(ob.ObjectField == 1) +def test_string_conversion(): + """Test string / unicode conversion.""" + ob = ConversionTest() - # need to test subclass here + assert ob.StringField == "spam" + assert ob.StringField == u"spam" - with self.assertRaises(TypeError): - ob = ConversionTest() - ob.ObjectField = self + ob.StringField = "eggs" + assert ob.StringField == "eggs" + assert ob.StringField == u"eggs" - def test_enum_conversion(self): - """Test enum conversion.""" - from Python.Test import ShortEnum + ob.StringField = u"spam" + assert ob.StringField == "spam" + assert ob.StringField == u"spam" - ob = ConversionTest() - self.assertTrue(ob.EnumField == ShortEnum.Zero) + ob.StringField = u'\uffff\uffff' + assert ob.StringField == u'\uffff\uffff' + + ob.StringField = System.String("spam") + assert ob.StringField == "spam" + assert ob.StringField == u"spam" - ob.EnumField = ShortEnum.One - self.assertTrue(ob.EnumField == ShortEnum.One) + ob.StringField = System.String(u'\uffff\uffff') + assert ob.StringField == u'\uffff\uffff' - ob.EnumField = 0 - self.assertTrue(ob.EnumField == ShortEnum.Zero) - self.assertTrue(ob.EnumField == 0) + ob.StringField = None + assert ob.StringField is None - ob.EnumField = 1 - self.assertTrue(ob.EnumField == ShortEnum.One) - self.assertTrue(ob.EnumField == 1) + with pytest.raises(TypeError): + ConversionTest().StringField = 1 - with self.assertRaises(ValueError): - ob = ConversionTest() - ob.EnumField = 10 - with self.assertRaises(ValueError): - ob = ConversionTest() - ob.EnumField = 255 +def test_interface_conversion(): + """Test interface conversion.""" + from Python.Test import Spam, ISpam - with self.assertRaises(OverflowError): - ob = ConversionTest() - ob.EnumField = 1000000 + ob = ConversionTest() - with self.assertRaises(TypeError): - ob = ConversionTest() - ob.EnumField = "spam" + assert ISpam(ob.SpamField).GetValue() == "spam" + assert ob.SpamField.GetValue() == "spam" - def test_null_conversion(self): - """Test null conversion.""" + ob.SpamField = Spam("eggs") + assert ISpam(ob.SpamField).GetValue() == "eggs" + assert ob.SpamField.GetValue() == "eggs" + + # need to test spam subclass here. + + ob.SpamField = None + assert ob.SpamField is None + + with pytest.raises(TypeError): ob = ConversionTest() + ob.SpamField = System.String("bad") + + with pytest.raises(TypeError): + ob = ConversionTest() + ob.SpamField = System.Int32(1) + - ob.StringField = None - self.assertTrue(ob.StringField is None) +def test_object_conversion(): + """Test ob conversion.""" + from Python.Test import Spam - ob.ObjectField = None - self.assertTrue(ob.ObjectField is None) + ob = ConversionTest() + assert ob.ObjectField is None - ob.SpamField = None - self.assertTrue(ob.SpamField is None) + ob.ObjectField = Spam("eggs") + assert ob.ObjectField.__class__.__name__ == "Spam" + assert ob.ObjectField.GetValue() == "eggs" - # Primitive types and enums should not be set to null. + ob.ObjectField = None + assert ob.ObjectField is None - with self.assertRaises(TypeError): - ConversionTest().Int32Field = None + ob.ObjectField = System.String("spam") + assert ob.ObjectField == "spam" - with self.assertRaises(TypeError): - ConversionTest().EnumField = None + ob.ObjectField = System.Int32(1) + assert ob.ObjectField == 1 - def test_byte_array_conversion(self): - """Test byte array conversion.""" + # need to test subclass here + + with pytest.raises(TypeError): + class Foo(object): + pass ob = ConversionTest() + ob.ObjectField = Foo + + +def test_enum_conversion(): + """Test enum conversion.""" + from Python.Test import ShortEnum + + ob = ConversionTest() + assert ob.EnumField == ShortEnum.Zero + + ob.EnumField = ShortEnum.One + assert ob.EnumField == ShortEnum.One + + ob.EnumField = 0 + assert ob.EnumField == ShortEnum.Zero + assert ob.EnumField == 0 - self.assertTrue(ob.ByteArrayField is None) + ob.EnumField = 1 + assert ob.EnumField == ShortEnum.One + assert ob.EnumField == 1 - ob.ByteArrayField = [0, 1, 2, 3, 4] - array = ob.ByteArrayField - self.assertTrue(len(array) == 5) - self.assertTrue(array[0] == 0) - self.assertTrue(array[4] == 4) + with pytest.raises(ValueError): + ob = ConversionTest() + ob.EnumField = 10 + + with pytest.raises(ValueError): + ob = ConversionTest() + ob.EnumField = 255 - value = b"testing" - ob.ByteArrayField = value - array = ob.ByteArrayField - for i, _ in enumerate(value): - self.assertTrue(array[i] == indexbytes(value, i)) + with pytest.raises(OverflowError): + ob = ConversionTest() + ob.EnumField = 1000000 - def test_sbyte_array_conversion(self): - """Test sbyte array conversion.""" + with pytest.raises(TypeError): ob = ConversionTest() + ob.EnumField = "spam" + + +def test_null_conversion(): + """Test null conversion.""" + ob = ConversionTest() + + ob.StringField = None + assert ob.StringField is None + + ob.ObjectField = None + assert ob.ObjectField is None + + ob.SpamField = None + assert ob.SpamField is None + + # Primitive types and enums should not be set to null. + + with pytest.raises(TypeError): + ConversionTest().Int32Field = None + + with pytest.raises(TypeError): + ConversionTest().EnumField = None + + +def test_byte_array_conversion(): + """Test byte array conversion.""" + ob = ConversionTest() + + assert ob.ByteArrayField is None + + ob.ByteArrayField = [0, 1, 2, 3, 4] + array = ob.ByteArrayField + assert len(array) == 5 + assert array[0] == 0 + assert array[4] == 4 + + value = b"testing" + ob.ByteArrayField = value + array = ob.ByteArrayField + for i, _ in enumerate(value): + assert array[i] == indexbytes(value, i) - self.assertTrue(ob.SByteArrayField is None) - ob.SByteArrayField = [0, 1, 2, 3, 4] - array = ob.SByteArrayField - self.assertTrue(len(array) == 5) - self.assertTrue(array[0] == 0) - self.assertTrue(array[4] == 4) +def test_sbyte_array_conversion(): + """Test sbyte array conversion.""" + ob = ConversionTest() - value = b"testing" - ob.SByteArrayField = value - array = ob.SByteArrayField - for i, _ in enumerate(value): - self.assertTrue(array[i] == indexbytes(value, i)) + assert ob.SByteArrayField is None + ob.SByteArrayField = [0, 1, 2, 3, 4] + array = ob.SByteArrayField + assert len(array) == 5 + assert array[0] == 0 + assert array[4] == 4 -def test_suite(): - return unittest.makeSuite(ConversionTests) + value = b"testing" + ob.SByteArrayField = value + array = ob.SByteArrayField + for i, _ in enumerate(value): + assert array[i] == indexbytes(value, i) diff --git a/src/tests/test_delegate.py b/src/tests/test_delegate.py index 4963a09b8..33aca43b3 100644 --- a/src/tests/test_delegate.py +++ b/src/tests/test_delegate.py @@ -1,258 +1,269 @@ # -*- coding: utf-8 -*- # TODO: Add test for ObjectDelegate -import unittest +"""Test CLR delegate support.""" import Python.Test as Test import System +import pytest from Python.Test import DelegateTest, StringDelegate -from _compat import DictProxyType -from utils import HelloClass, hello_func, MultipleHandler +from ._compat import DictProxyType +from .utils import HelloClass, hello_func, MultipleHandler -class DelegateTests(unittest.TestCase): - """Test CLR delegate support.""" +def test_delegate_standard_attrs(): + """Test standard delegate attributes.""" + from Python.Test import PublicDelegate - def test_delegate_standard_attrs(self): - """Test standard delegate attributes.""" - from Python.Test import PublicDelegate + assert PublicDelegate.__name__ == 'PublicDelegate' + assert PublicDelegate.__module__ == 'Python.Test' + assert isinstance(PublicDelegate.__dict__, DictProxyType) + assert PublicDelegate.__doc__ is None - self.assertTrue(PublicDelegate.__name__ == 'PublicDelegate') - self.assertTrue(PublicDelegate.__module__ == 'Python.Test') - self.assertTrue(isinstance(PublicDelegate.__dict__, DictProxyType)) - self.assertTrue(PublicDelegate.__doc__ is None) - def test_global_delegate_visibility(self): - """Test visibility of module-level delegates.""" - from Python.Test import PublicDelegate +def test_global_delegate_visibility(): + """Test visibility of module-level delegates.""" + from Python.Test import PublicDelegate - self.assertTrue(PublicDelegate.__name__ == 'PublicDelegate') - self.assertTrue(Test.PublicDelegate.__name__ == 'PublicDelegate') + assert PublicDelegate.__name__ == 'PublicDelegate' + assert Test.PublicDelegate.__name__ == 'PublicDelegate' - with self.assertRaises(ImportError): - from Python.Test import InternalDelegate - _ = InternalDelegate + with pytest.raises(ImportError): + from Python.Test import InternalDelegate + _ = InternalDelegate - with self.assertRaises(AttributeError): - _ = Test.InternalDelegate + with pytest.raises(AttributeError): + _ = Test.InternalDelegate - def test_nested_delegate_visibility(self): - """Test visibility of nested delegates.""" - ob = DelegateTest.PublicDelegate - self.assertTrue(ob.__name__ == 'PublicDelegate') - ob = DelegateTest.ProtectedDelegate - self.assertTrue(ob.__name__ == 'ProtectedDelegate') +def test_nested_delegate_visibility(): + """Test visibility of nested delegates.""" + ob = DelegateTest.PublicDelegate + assert ob.__name__ == 'PublicDelegate' - with self.assertRaises(AttributeError): - _ = DelegateTest.InternalDelegate + ob = DelegateTest.ProtectedDelegate + assert ob.__name__ == 'ProtectedDelegate' - with self.assertRaises(AttributeError): - _ = DelegateTest.PrivateDelegate + with pytest.raises(AttributeError): + _ = DelegateTest.InternalDelegate - def test_delegate_from_function(self): - """Test delegate implemented with a Python function.""" + with pytest.raises(AttributeError): + _ = DelegateTest.PrivateDelegate - d = StringDelegate(hello_func) - ob = DelegateTest() - self.assertTrue(ob.CallStringDelegate(d) == "hello") - self.assertTrue(d() == "hello") +def test_delegate_from_function(): + """Test delegate implemented with a Python function.""" - ob.stringDelegate = d - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") + d = StringDelegate(hello_func) + ob = DelegateTest() - def test_delegate_from_method(self): - """Test delegate implemented with a Python instance method.""" + assert ob.CallStringDelegate(d) == "hello" + assert d() == "hello" - inst = HelloClass() - d = StringDelegate(inst.hello) - ob = DelegateTest() + ob.stringDelegate = d + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - self.assertTrue(ob.CallStringDelegate(d) == "hello") - self.assertTrue(d() == "hello") - ob.stringDelegate = d - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") +def test_delegate_from_method(): + """Test delegate implemented with a Python instance method.""" - def test_delegate_from_unbound_method(self): - """Test failure mode for unbound methods.""" + inst = HelloClass() + d = StringDelegate(inst.hello) + ob = DelegateTest() - with self.assertRaises(TypeError): - d = StringDelegate(HelloClass.hello) - d() + assert ob.CallStringDelegate(d) == "hello" + assert d() == "hello" - def test_delegate_from_static_method(self): - """Test delegate implemented with a Python static method.""" + ob.stringDelegate = d + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - d = StringDelegate(HelloClass.s_hello) - ob = DelegateTest() - self.assertTrue(ob.CallStringDelegate(d) == "hello") - self.assertTrue(d() == "hello") +def test_delegate_from_unbound_method(): + """Test failure mode for unbound methods.""" - ob.stringDelegate = d - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") + with pytest.raises(TypeError): + d = StringDelegate(HelloClass.hello) + d() - inst = HelloClass() - d = StringDelegate(inst.s_hello) - ob = DelegateTest() - self.assertTrue(ob.CallStringDelegate(d) == "hello") - self.assertTrue(d() == "hello") +def test_delegate_from_static_method(): + """Test delegate implemented with a Python static method.""" - ob.stringDelegate = d - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") + d = StringDelegate(HelloClass.s_hello) + ob = DelegateTest() - def test_delegate_from_class_method(self): - """Test delegate implemented with a Python class method.""" + assert ob.CallStringDelegate(d) == "hello" + assert d() == "hello" - d = StringDelegate(HelloClass.c_hello) - ob = DelegateTest() + ob.stringDelegate = d + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - self.assertTrue(ob.CallStringDelegate(d) == "hello") - self.assertTrue(d() == "hello") + inst = HelloClass() + d = StringDelegate(inst.s_hello) + ob = DelegateTest() - ob.stringDelegate = d - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") + assert ob.CallStringDelegate(d) == "hello" + assert d() == "hello" - inst = HelloClass() - d = StringDelegate(inst.c_hello) - ob = DelegateTest() + ob.stringDelegate = d + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - self.assertTrue(ob.CallStringDelegate(d) == "hello") - self.assertTrue(d() == "hello") - ob.stringDelegate = d - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") +def test_delegate_from_class_method(): + """Test delegate implemented with a Python class method.""" - def test_delegate_from_callable(self): - """Test delegate implemented with a Python callable object.""" + d = StringDelegate(HelloClass.c_hello) + ob = DelegateTest() - inst = HelloClass() - d = StringDelegate(inst) - ob = DelegateTest() + assert ob.CallStringDelegate(d) == "hello" + assert d() == "hello" - self.assertTrue(ob.CallStringDelegate(d) == "hello") - self.assertTrue(d() == "hello") + ob.stringDelegate = d + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - ob.stringDelegate = d - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") + inst = HelloClass() + d = StringDelegate(inst.c_hello) + ob = DelegateTest() - def test_delegate_from_managed_instance_method(self): - """Test delegate implemented with a managed instance method.""" - ob = DelegateTest() - d = StringDelegate(ob.SayHello) + assert ob.CallStringDelegate(d) == "hello" + assert d() == "hello" - self.assertTrue(ob.CallStringDelegate(d) == "hello") - self.assertTrue(d() == "hello") + ob.stringDelegate = d + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - ob.stringDelegate = d - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") - def test_delegate_from_managed_static_method(self): - """Test delegate implemented with a managed static method.""" - d = StringDelegate(DelegateTest.StaticSayHello) - ob = DelegateTest() +def test_delegate_from_callable(): + """Test delegate implemented with a Python callable object.""" - self.assertTrue(ob.CallStringDelegate(d) == "hello") - self.assertTrue(d() == "hello") + inst = HelloClass() + d = StringDelegate(inst) + ob = DelegateTest() - ob.stringDelegate = d - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") + assert ob.CallStringDelegate(d) == "hello" + assert d() == "hello" - def test_delegate_from_delegate(self): - """Test delegate implemented with another delegate.""" - d1 = StringDelegate(hello_func) - d2 = StringDelegate(d1) - ob = DelegateTest() + ob.stringDelegate = d + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - self.assertTrue(ob.CallStringDelegate(d2) == "hello") - self.assertTrue(d2() == "hello") - ob.stringDelegate = d2 - self.assertTrue(ob.CallStringDelegate(ob.stringDelegate) == "hello") - self.assertTrue(ob.stringDelegate() == "hello") +def test_delegate_from_managed_instance_method(): + """Test delegate implemented with a managed instance method.""" + ob = DelegateTest() + d = StringDelegate(ob.SayHello) - def test_delegate_with_invalid_args(self): - """Test delegate instantiation with invalid (non-callable) args.""" + assert ob.CallStringDelegate(d) == "hello" + assert d() == "hello" - with self.assertRaises(TypeError): - _ = StringDelegate(None) + ob.stringDelegate = d + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - with self.assertRaises(TypeError): - _ = StringDelegate("spam") - with self.assertRaises(TypeError): - _ = StringDelegate(1) +def test_delegate_from_managed_static_method(): + """Test delegate implemented with a managed static method.""" + d = StringDelegate(DelegateTest.StaticSayHello) + ob = DelegateTest() - def test_multicast_delegate(self): - """Test multicast delegates.""" + assert ob.CallStringDelegate(d) == "hello" + assert d() == "hello" - inst = MultipleHandler() - d1 = StringDelegate(inst.count) - d2 = StringDelegate(inst.count) + ob.stringDelegate = d + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - md = System.Delegate.Combine(d1, d2) - ob = DelegateTest() - self.assertTrue(ob.CallStringDelegate(md) == "ok") - self.assertTrue(inst.value == 2) +def test_delegate_from_delegate(): + """Test delegate implemented with another delegate.""" + d1 = StringDelegate(hello_func) + d2 = StringDelegate(d1) + ob = DelegateTest() - self.assertTrue(md() == "ok") - self.assertTrue(inst.value == 4) + assert ob.CallStringDelegate(d2) == "hello" + assert d2() == "hello" - def test_subclass_delegate_fails(self): - """Test that subclassing of a delegate type fails.""" - from Python.Test import PublicDelegate + ob.stringDelegate = d2 + assert ob.CallStringDelegate(ob.stringDelegate) == "hello" + assert ob.stringDelegate() == "hello" - with self.assertRaises(TypeError): - class Boom(PublicDelegate): - pass - _ = Boom - def test_delegate_equality(self): - """Test delegate equality.""" +def test_delegate_with_invalid_args(): + """Test delegate instantiation with invalid (non-callable) args.""" - d = StringDelegate(hello_func) - ob = DelegateTest() - ob.stringDelegate = d - self.assertTrue(ob.stringDelegate == d) + with pytest.raises(TypeError): + _ = StringDelegate(None) - def test_bool_delegate(self): - """Test boolean delegate.""" - from Python.Test import BoolDelegate + with pytest.raises(TypeError): + _ = StringDelegate("spam") - def always_so_negative(): - return 0 + with pytest.raises(TypeError): + _ = StringDelegate(1) - d = BoolDelegate(always_so_negative) - ob = DelegateTest() - ob.CallBoolDelegate(d) - self.assertTrue(not d()) - self.assertTrue(not ob.CallBoolDelegate(d)) +def test_multicast_delegate(): + """Test multicast delegates.""" - # test async delegates + inst = MultipleHandler() + d1 = StringDelegate(inst.count) + d2 = StringDelegate(inst.count) - # test multicast delegates + md = System.Delegate.Combine(d1, d2) + ob = DelegateTest() - # test explicit op_ + assert ob.CallStringDelegate(md) == "ok" + assert inst.value == 2 - # test sig mismatch, both on managed and Python side + assert md() == "ok" + assert inst.value == 4 - # test return wrong type +def test_subclass_delegate_fails(): + """Test that subclassing of a delegate type fails.""" + from Python.Test import PublicDelegate -def test_suite(): - return unittest.makeSuite(DelegateTests) + with pytest.raises(TypeError): + class Boom(PublicDelegate): + pass + + _ = Boom + + +def test_delegate_equality(): + """Test delegate equality.""" + + d = StringDelegate(hello_func) + ob = DelegateTest() + ob.stringDelegate = d + assert ob.stringDelegate == d + + +def test_bool_delegate(): + """Test boolean delegate.""" + from Python.Test import BoolDelegate + + def always_so_negative(): + return 0 + + d = BoolDelegate(always_so_negative) + ob = DelegateTest() + ob.CallBoolDelegate(d) + + assert not d() + assert not ob.CallBoolDelegate(d) + + # test async delegates + + # test multicast delegates + + # test explicit op_ + + # test sig mismatch, both on managed and Python side + + # test return wrong type diff --git a/src/tests/test_docstring.py b/src/tests/test_docstring.py index f2bc3302b..640a61915 100644 --- a/src/tests/test_docstring.py +++ b/src/tests/test_docstring.py @@ -1,32 +1,27 @@ # -*- coding: utf-8 -*- -import unittest +"""Test doc strings support.""" -class DocStringTests(unittest.TestCase): - """Test doc strings support.""" +def test_doc_with_ctor(): + from Python.Test import DocWithCtorTest - def test_doc_with_ctor(self): - from Python.Test import DocWithCtorTest + assert DocWithCtorTest.__doc__ == 'DocWithCtorTest Class' + assert DocWithCtorTest.TestMethod.__doc__ == 'DocWithCtorTest TestMethod' + assert DocWithCtorTest.StaticTestMethod.__doc__ == 'DocWithCtorTest StaticTestMethod' - self.assertEqual(DocWithCtorTest.__doc__, 'DocWithCtorTest Class') - self.assertEqual(DocWithCtorTest.TestMethod.__doc__, 'DocWithCtorTest TestMethod') - self.assertEqual(DocWithCtorTest.StaticTestMethod.__doc__, 'DocWithCtorTest StaticTestMethod') - def test_doc_with_ctor_no_doc(self): - from Python.Test import DocWithCtorNoDocTest +def test_doc_with_ctor_no_doc(): + from Python.Test import DocWithCtorNoDocTest - self.assertEqual(DocWithCtorNoDocTest.__doc__, 'Void .ctor(Boolean)') - self.assertEqual(DocWithCtorNoDocTest.TestMethod.__doc__, 'Void TestMethod(Double, Int32)') - self.assertEqual(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(self): - from Python.Test import DocWithoutCtorTest - self.assertEqual(DocWithoutCtorTest.__doc__, 'DocWithoutCtorTest Class') - self.assertEqual(DocWithoutCtorTest.TestMethod.__doc__, 'DocWithoutCtorTest TestMethod') - self.assertEqual(DocWithoutCtorTest.StaticTestMethod.__doc__, 'DocWithoutCtorTest StaticTestMethod') +def test_doc_without_ctor(): + from Python.Test import DocWithoutCtorTest - -def test_suite(): - return unittest.makeSuite(DocStringTests) + assert DocWithoutCtorTest.__doc__ == 'DocWithoutCtorTest Class' + assert DocWithoutCtorTest.TestMethod.__doc__ == 'DocWithoutCtorTest TestMethod' + assert DocWithoutCtorTest.StaticTestMethod.__doc__ == 'DocWithoutCtorTest StaticTestMethod' diff --git a/src/tests/test_engine.py b/src/tests/test_engine.py index b605a3796..cca08a4d2 100644 --- a/src/tests/test_engine.py +++ b/src/tests/test_engine.py @@ -1,46 +1,43 @@ # -*- coding: utf-8 -*- +"""Test PythonEngine embedding APIs.""" + import sys -import unittest import System +import pytest from Python.Runtime import PythonEngine -class EngineTests(unittest.TestCase): - """Test PythonEngine embedding APIs.""" - - def test_multiple_calls_to_initialize(self): - """Test that multiple initialize calls are harmless.""" - try: - PythonEngine.Initialize() - PythonEngine.Initialize() - PythonEngine.Initialize() - except BaseException: - self.fail("Initialize() raise an exception.") +def test_multiple_calls_to_initialize(): + """Test that multiple initialize calls are harmless.""" + try: + PythonEngine.Initialize() + PythonEngine.Initialize() + PythonEngine.Initialize() + except BaseException: + self.fail("Initialize() raise an exception.") - @unittest.skip(reason="FIXME: test crashes") - def test_import_module(self): - """Test module import.""" - m = PythonEngine.ImportModule("sys") - n = m.GetAttr("__name__") - self.assertTrue(n.AsManagedObject(System.String) == "sys") - @unittest.skip(reason="FIXME: test freezes") - def test_run_string(self): - """Test the RunString method.""" - PythonEngine.AcquireLock() +@pytest.mark.skip(reason="FIXME: test crashes") +def test_import_module(): + """Test module import.""" + m = PythonEngine.ImportModule("sys") + n = m.GetAttr("__name__") + assert n.AsManagedObject(System.String) == "sys" - code = "import sys; sys.singleline_worked = 1" - PythonEngine.RunString(code) - self.assertTrue(sys.singleline_worked == 1) - code = "import sys\nsys.multiline_worked = 1" - PythonEngine.RunString(code) - self.assertTrue(sys.multiline_worked == 1) +@pytest.mark.skip(reason="FIXME: test freezes") +def test_run_string(): + """Test the RunString method.""" + PythonEngine.AcquireLock() - PythonEngine.ReleaseLock() + code = "import sys; sys.singleline_worked = 1" + PythonEngine.RunString(code) + assert sys.singleline_worked == 1 + code = "import sys\nsys.multiline_worked = 1" + PythonEngine.RunString(code) + assert sys.multiline_worked == 1 -def test_suite(): - return unittest.makeSuite(EngineTests) + PythonEngine.ReleaseLock() diff --git a/src/tests/test_enum.py b/src/tests/test_enum.py index e7147e69c..b31ce4ec5 100644 --- a/src/tests/test_enum.py +++ b/src/tests/test_enum.py @@ -1,136 +1,145 @@ # -*- coding: utf-8 -*- -import unittest +"""Test clr enum support.""" +import pytest import Python.Test as Test -from _compat import DictProxyType, long - - -class EnumTests(unittest.TestCase): - """Test CLR enum support.""" - - def test_enum_standard_attrs(self): - """Test standard enum attributes.""" - from System import DayOfWeek - - self.assertTrue(DayOfWeek.__name__ == 'DayOfWeek') - self.assertTrue(DayOfWeek.__module__ == 'System') - self.assertTrue(isinstance(DayOfWeek.__dict__, DictProxyType)) - self.assertTrue(DayOfWeek.__doc__ is None) - - def test_enum_get_member(self): - """Test access to enum members.""" - from System import DayOfWeek - - self.assertTrue(DayOfWeek.Sunday == 0) - self.assertTrue(DayOfWeek.Monday == 1) - self.assertTrue(DayOfWeek.Tuesday == 2) - self.assertTrue(DayOfWeek.Wednesday == 3) - self.assertTrue(DayOfWeek.Thursday == 4) - self.assertTrue(DayOfWeek.Friday == 5) - self.assertTrue(DayOfWeek.Saturday == 6) - - def test_byte_enum(self): - """Test byte enum.""" - self.assertTrue(Test.ByteEnum.Zero == 0) - self.assertTrue(Test.ByteEnum.One == 1) - self.assertTrue(Test.ByteEnum.Two == 2) - - def test_sbyte_enum(self): - """Test sbyte enum.""" - self.assertTrue(Test.SByteEnum.Zero == 0) - self.assertTrue(Test.SByteEnum.One == 1) - self.assertTrue(Test.SByteEnum.Two == 2) - - def test_short_enum(self): - """Test short enum.""" - self.assertTrue(Test.ShortEnum.Zero == 0) - self.assertTrue(Test.ShortEnum.One == 1) - self.assertTrue(Test.ShortEnum.Two == 2) - - def test_ushort_enum(self): - """Test ushort enum.""" - self.assertTrue(Test.UShortEnum.Zero == 0) - self.assertTrue(Test.UShortEnum.One == 1) - self.assertTrue(Test.UShortEnum.Two == 2) - - def test_int_enum(self): - """Test int enum.""" - self.assertTrue(Test.IntEnum.Zero == 0) - self.assertTrue(Test.IntEnum.One == 1) - self.assertTrue(Test.IntEnum.Two == 2) - - def test_uint_enum(self): - """Test uint enum.""" - self.assertTrue(Test.UIntEnum.Zero == long(0)) - self.assertTrue(Test.UIntEnum.One == long(1)) - self.assertTrue(Test.UIntEnum.Two == long(2)) - - def test_long_enum(self): - """Test long enum.""" - self.assertTrue(Test.LongEnum.Zero == long(0)) - self.assertTrue(Test.LongEnum.One == long(1)) - self.assertTrue(Test.LongEnum.Two == long(2)) - - def test_ulong_enum(self): - """Test ulong enum.""" - self.assertTrue(Test.ULongEnum.Zero == long(0)) - self.assertTrue(Test.ULongEnum.One == long(1)) - self.assertTrue(Test.ULongEnum.Two == long(2)) - - def test_instantiate_enum_fails(self): - """Test that instantiation of an enum class fails.""" - from System import DayOfWeek - - with self.assertRaises(TypeError): - _ = DayOfWeek() - - def test_subclass_enum_fails(self): - """Test that subclassing of an enumeration fails.""" - from System import DayOfWeek - - with self.assertRaises(TypeError): - class Boom(DayOfWeek): - pass - _ = Boom - - def test_enum_set_member_fails(self): - """Test that setattr operations on enumerations fail.""" - from System import DayOfWeek - - with self.assertRaises(TypeError): - DayOfWeek.Sunday = 13 - - with self.assertRaises(TypeError): - del DayOfWeek.Sunday - - def test_enum_with_flags_attr_conversion(self): - """Test enumeration conversion with FlagsAttribute set.""" - # This works because the FlagsField enum has FlagsAttribute. - Test.FieldTest().FlagsField = 99 - - # This should fail because our test enum doesn't have it. - with self.assertRaises(ValueError): - Test.FieldTest().EnumField = 99 - - def test_enum_conversion(self): - """Test enumeration conversion.""" - ob = Test.FieldTest() - self.assertTrue(ob.EnumField == 0) - - ob.EnumField = Test.ShortEnum.One - self.assertTrue(ob.EnumField == 1) - - with self.assertRaises(ValueError): - Test.FieldTest().EnumField = 20 - - with self.assertRaises(OverflowError): - Test.FieldTest().EnumField = 100000 - - with self.assertRaises(TypeError): - Test.FieldTest().EnumField = "str" - - -def test_suite(): - return unittest.makeSuite(EnumTests) +from ._compat import DictProxyType, long + + +def test_enum_standard_attrs(): + """Test standard enum attributes.""" + from System import DayOfWeek + + assert DayOfWeek.__name__ == 'DayOfWeek' + assert DayOfWeek.__module__ == 'System' + assert isinstance(DayOfWeek.__dict__, DictProxyType) + assert DayOfWeek.__doc__ is None + + +def test_enum_get_member(): + """Test access to enum members.""" + from System import DayOfWeek + + assert DayOfWeek.Sunday == 0 + assert DayOfWeek.Monday == 1 + assert DayOfWeek.Tuesday == 2 + assert DayOfWeek.Wednesday == 3 + assert DayOfWeek.Thursday == 4 + assert DayOfWeek.Friday == 5 + assert DayOfWeek.Saturday == 6 + + +def test_byte_enum(): + """Test byte enum.""" + assert Test.ByteEnum.Zero == 0 + assert Test.ByteEnum.One == 1 + assert Test.ByteEnum.Two == 2 + + +def test_sbyte_enum(): + """Test sbyte enum.""" + assert Test.SByteEnum.Zero == 0 + assert Test.SByteEnum.One == 1 + assert Test.SByteEnum.Two == 2 + + +def test_short_enum(): + """Test short enum.""" + assert Test.ShortEnum.Zero == 0 + assert Test.ShortEnum.One == 1 + assert Test.ShortEnum.Two == 2 + + +def test_ushort_enum(): + """Test ushort enum.""" + assert Test.UShortEnum.Zero == 0 + assert Test.UShortEnum.One == 1 + assert Test.UShortEnum.Two == 2 + + +def test_int_enum(): + """Test int enum.""" + assert Test.IntEnum.Zero == 0 + assert Test.IntEnum.One == 1 + assert Test.IntEnum.Two == 2 + + +def test_uint_enum(): + """Test uint enum.""" + assert Test.UIntEnum.Zero == long(0) + assert Test.UIntEnum.One == long(1) + assert Test.UIntEnum.Two == long(2) + + +def test_long_enum(): + """Test long enum.""" + assert Test.LongEnum.Zero == long(0) + assert Test.LongEnum.One == long(1) + assert Test.LongEnum.Two == long(2) + + +def test_ulong_enum(): + """Test ulong enum.""" + assert Test.ULongEnum.Zero == long(0) + assert Test.ULongEnum.One == long(1) + assert Test.ULongEnum.Two == long(2) + + +def test_instantiate_enum_fails(): + """Test that instantiation of an enum class fails.""" + from System import DayOfWeek + + with pytest.raises(TypeError): + _ = DayOfWeek() + + +def test_subclass_enum_fails(): + """Test that subclassing of an enumeration fails.""" + from System import DayOfWeek + + with pytest.raises(TypeError): + class Boom(DayOfWeek): + pass + + _ = Boom + + +def test_enum_set_member_fails(): + """Test that setattr operations on enumerations fail.""" + from System import DayOfWeek + + with pytest.raises(TypeError): + DayOfWeek.Sunday = 13 + + with pytest.raises(TypeError): + del DayOfWeek.Sunday + + +def test_enum_with_flags_attr_conversion(): + """Test enumeration conversion with FlagsAttribute set.""" + # This works because the FlagsField enum has FlagsAttribute. + Test.FieldTest().FlagsField = 99 + + # This should fail because our test enum doesn't have it. + with pytest.raises(ValueError): + Test.FieldTest().EnumField = 99 + + +def test_enum_conversion(): + """Test enumeration conversion.""" + ob = Test.FieldTest() + assert ob.EnumField == 0 + + ob.EnumField = Test.ShortEnum.One + assert ob.EnumField == 1 + + with pytest.raises(ValueError): + Test.FieldTest().EnumField = 20 + + with pytest.raises(OverflowError): + Test.FieldTest().EnumField = 100000 + + with pytest.raises(TypeError): + Test.FieldTest().EnumField = "str" diff --git a/src/tests/test_event.py b/src/tests/test_event.py index 047af47f3..624b83d44 100644 --- a/src/tests/test_event.py +++ b/src/tests/test_event.py @@ -1,563 +1,584 @@ # -*- coding: utf-8 -*- -import unittest +"""Test CLR event support.""" +import pytest from Python.Test import EventTest, EventArgsTest -from _compat import range -from utils import (CallableHandler, ClassMethodHandler, GenericHandler, - MultipleHandler, StaticMethodHandler, VarCallableHandler, - VariableArgsHandler) +from ._compat import range +from .utils import (CallableHandler, ClassMethodHandler, GenericHandler, + MultipleHandler, StaticMethodHandler, VarCallableHandler, + VariableArgsHandler) -class EventTests(unittest.TestCase): - """Test CLR event support.""" +def test_public_instance_event(): + """Test public instance events.""" + ob = EventTest() - def test_public_instance_event(self): - """Test public instance events.""" - ob = EventTest() + handler = GenericHandler() + assert handler.value is None - handler = GenericHandler() - self.assertTrue(handler.value is None) + ob.PublicEvent += handler.handler - ob.PublicEvent += handler.handler + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 10 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) + ob.PublicEvent -= handler.handler - ob.PublicEvent -= handler.handler - def test_public_static_event(self): - """Test public static events.""" - handler = GenericHandler() - self.assertTrue(handler.value is None) +def test_public_static_event(): + """Test public static events.""" + handler = GenericHandler() + assert handler.value is None - EventTest.PublicStaticEvent += handler.handler + EventTest.PublicStaticEvent += handler.handler - EventTest.OnPublicStaticEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) + EventTest.OnPublicStaticEvent(EventArgsTest(10)) + assert handler.value == 10 - def test_protected_instance_event(self): - """Test protected instance events.""" - ob = EventTest() - handler = GenericHandler() - self.assertTrue(handler.value is None) +def test_protected_instance_event(): + """Test protected instance events.""" + ob = EventTest() - ob.ProtectedEvent += handler.handler + handler = GenericHandler() + assert handler.value is None - ob.OnProtectedEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) + ob.ProtectedEvent += handler.handler - ob.ProtectedEvent -= handler.handler + ob.OnProtectedEvent(EventArgsTest(10)) + assert handler.value == 10 - def test_protected_static_event(self): - """Test protected static events.""" - handler = GenericHandler() - self.assertTrue(handler.value is None) + ob.ProtectedEvent -= handler.handler - EventTest.ProtectedStaticEvent += handler.handler - EventTest.OnProtectedStaticEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) +def test_protected_static_event(): + """Test protected static events.""" + handler = GenericHandler() + assert handler.value is None - EventTest.ProtectedStaticEvent -= handler.handler + EventTest.ProtectedStaticEvent += handler.handler - def test_internal_events(self): - """Test internal events.""" + EventTest.OnProtectedStaticEvent(EventArgsTest(10)) + assert handler.value == 10 - with self.assertRaises(AttributeError): - _ = EventTest().InternalEvent + EventTest.ProtectedStaticEvent -= handler.handler - with self.assertRaises(AttributeError): - _ = EventTest().InternalStaticEvent - with self.assertRaises(AttributeError): - _ = EventTest.InternalStaticEvent +def test_internal_events(): + """Test internal events.""" - def test_private_events(self): - """Test private events.""" + with pytest.raises(AttributeError): + _ = EventTest().InternalEvent - with self.assertRaises(AttributeError): - _ = EventTest().PrivateEvent + with pytest.raises(AttributeError): + _ = EventTest().InternalStaticEvent - with self.assertRaises(AttributeError): - _ = EventTest().PrivateStaticEvent + with pytest.raises(AttributeError): + _ = EventTest.InternalStaticEvent - with self.assertRaises(AttributeError): - _ = EventTest.PrivateStaticEvent - def test_multicast_event(self): - """Test multicast events.""" - ob = EventTest() +def test_private_events(): + """Test private events.""" - handler1 = GenericHandler() - handler2 = GenericHandler() - handler3 = GenericHandler() + with pytest.raises(AttributeError): + _ = EventTest().PrivateEvent - ob.PublicEvent += handler1.handler - ob.PublicEvent += handler2.handler - ob.PublicEvent += handler3.handler + with pytest.raises(AttributeError): + _ = EventTest().PrivateStaticEvent - ob.OnPublicEvent(EventArgsTest(10)) + with pytest.raises(AttributeError): + _ = EventTest.PrivateStaticEvent - self.assertTrue(handler1.value == 10) - self.assertTrue(handler2.value == 10) - self.assertTrue(handler3.value == 10) - ob.OnPublicEvent(EventArgsTest(20)) +def test_multicast_event(): + """Test multicast events.""" + ob = EventTest() - self.assertTrue(handler1.value == 20) - self.assertTrue(handler2.value == 20) - self.assertTrue(handler3.value == 20) + handler1 = GenericHandler() + handler2 = GenericHandler() + handler3 = GenericHandler() - ob.PublicEvent -= handler1.handler - ob.PublicEvent -= handler2.handler - ob.PublicEvent -= handler3.handler + ob.PublicEvent += handler1.handler + ob.PublicEvent += handler2.handler + ob.PublicEvent += handler3.handler - def test_instance_method_handler(self): - """Test instance method handlers.""" - ob = EventTest() - handler = GenericHandler() + ob.OnPublicEvent(EventArgsTest(10)) - ob.PublicEvent += handler.handler - self.assertTrue(handler.value is None) + assert handler1.value == 10 + assert handler2.value == 10 + assert handler3.value == 10 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) + ob.OnPublicEvent(EventArgsTest(20)) - ob.PublicEvent -= handler.handler - self.assertTrue(handler.value == 10) + assert handler1.value == 20 + assert handler2.value == 20 + assert handler3.value == 20 - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(handler.value == 10) + ob.PublicEvent -= handler1.handler + ob.PublicEvent -= handler2.handler + ob.PublicEvent -= handler3.handler - def test_var_args_instance_method_handler(self): - """Test vararg instance method handlers.""" - ob = EventTest() - handler = VariableArgsHandler() - ob.PublicEvent += handler.handler - self.assertTrue(handler.value is None) +def test_instance_method_handler(): + """Test instance method handlers.""" + ob = EventTest() + handler = GenericHandler() - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) + ob.PublicEvent += handler.handler + assert handler.value is None - ob.PublicEvent -= handler.handler - self.assertTrue(handler.value == 10) + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 10 - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(handler.value == 10) + ob.PublicEvent -= handler.handler + assert handler.value == 10 - def test_callableob_handler(self): - """Test callable ob handlers.""" - ob = EventTest() - handler = CallableHandler() + ob.OnPublicEvent(EventArgsTest(20)) + assert handler.value == 10 - ob.PublicEvent += handler - self.assertTrue(handler.value is None) - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) +def test_var_args_instance_method_handler(): + """Test vararg instance method handlers.""" + ob = EventTest() + handler = VariableArgsHandler() - ob.PublicEvent -= handler - self.assertTrue(handler.value == 10) + ob.PublicEvent += handler.handler + assert handler.value is None - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(handler.value == 10) + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 10 - def test_var_args_callable_handler(self): - """Test varargs callable handlers.""" - ob = EventTest() - handler = VarCallableHandler() + ob.PublicEvent -= handler.handler + assert handler.value == 10 - ob.PublicEvent += handler - self.assertTrue(handler.value is None) + ob.OnPublicEvent(EventArgsTest(20)) + assert handler.value == 10 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) - ob.PublicEvent -= handler - self.assertTrue(handler.value == 10) +def test_callableob_handler(): + """Test callable ob handlers.""" + ob = EventTest() + handler = CallableHandler() - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(handler.value == 10) + ob.PublicEvent += handler + assert handler.value is None - def test_static_method_handler(self): - """Test static method handlers.""" - ob = EventTest() - handler = StaticMethodHandler() - StaticMethodHandler.value = None + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 10 - ob.PublicEvent += handler.handler - self.assertTrue(handler.value is None) + ob.PublicEvent -= handler + assert handler.value == 10 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) + ob.OnPublicEvent(EventArgsTest(20)) + assert handler.value == 10 - ob.PublicEvent -= handler.handler - self.assertTrue(handler.value == 10) - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(handler.value == 10) +def test_var_args_callable_handler(): + """Test varargs callable handlers.""" + ob = EventTest() + handler = VarCallableHandler() - def test_class_method_handler(self): - """Test class method handlers.""" - ob = EventTest() - handler = ClassMethodHandler() - ClassMethodHandler.value = None + ob.PublicEvent += handler + assert handler.value is None - ob.PublicEvent += handler.handler - self.assertTrue(handler.value is None) + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 10 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) + ob.PublicEvent -= handler + assert handler.value == 10 - ob.PublicEvent -= handler.handler - self.assertTrue(handler.value == 10) + ob.OnPublicEvent(EventArgsTest(20)) + assert handler.value == 10 - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(handler.value == 10) - def test_managed_instance_method_handler(self): - """Test managed instance method handlers.""" - ob = EventTest() +def test_static_method_handler(): + """Test static method handlers.""" + ob = EventTest() + handler = StaticMethodHandler() + StaticMethodHandler.value = None - ob.PublicEvent += ob.GenericHandler - self.assertTrue(ob.value == 0) + ob.PublicEvent += handler.handler + assert handler.value is None - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(ob.value == 10) + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 10 - ob.PublicEvent -= ob.GenericHandler - self.assertTrue(ob.value == 10) + ob.PublicEvent -= handler.handler + assert handler.value == 10 - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(ob.value == 10) + ob.OnPublicEvent(EventArgsTest(20)) + assert handler.value == 10 - def test_managed_static_method_handler(self): - """Test managed static method handlers.""" - ob = EventTest() - EventTest.s_value = 0 - ob.PublicEvent += ob.StaticHandler - self.assertTrue(EventTest.s_value == 0) +def test_class_method_handler(): + """Test class method handlers.""" + ob = EventTest() + handler = ClassMethodHandler() + ClassMethodHandler.value = None - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(EventTest.s_value == 10) + ob.PublicEvent += handler.handler + assert handler.value is None - ob.PublicEvent -= ob.StaticHandler - self.assertTrue(EventTest.s_value == 10) + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 10 - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(EventTest.s_value == 10) + ob.PublicEvent -= handler.handler + assert handler.value == 10 - def test_unbound_method_handler(self): - """Test failure mode for unbound method handlers.""" - ob = EventTest() - ob.PublicEvent += GenericHandler.handler + ob.OnPublicEvent(EventArgsTest(20)) + assert handler.value == 10 - with self.assertRaises(TypeError): - ob.OnPublicEvent(EventArgsTest(10)) - ob.PublicEvent -= GenericHandler.handler +def test_managed_instance_method_handler(): + """Test managed instance method handlers.""" + ob = EventTest() - def test_function_handler(self): - """Test function handlers.""" - ob = EventTest() - dict_ = {'value': None} + ob.PublicEvent += ob.GenericHandler + assert ob.value == 0 + + ob.OnPublicEvent(EventArgsTest(10)) + assert ob.value == 10 - def handler(sender, args, dict_=dict_): - dict_['value'] = args.value + ob.PublicEvent -= ob.GenericHandler + assert ob.value == 10 - ob.PublicEvent += handler - self.assertTrue(dict_['value'] is None) + ob.OnPublicEvent(EventArgsTest(20)) + assert ob.value == 10 + +def test_managed_static_method_handler(): + """Test managed static method handlers.""" + ob = EventTest() + EventTest.s_value = 0 + + ob.PublicEvent += ob.StaticHandler + assert EventTest.s_value == 0 + + ob.OnPublicEvent(EventArgsTest(10)) + assert EventTest.s_value == 10 + + ob.PublicEvent -= ob.StaticHandler + assert EventTest.s_value == 10 + + ob.OnPublicEvent(EventArgsTest(20)) + assert EventTest.s_value == 10 + + +def test_unbound_method_handler(): + """Test failure mode for unbound method handlers.""" + ob = EventTest() + ob.PublicEvent += GenericHandler.handler + + with pytest.raises(TypeError): ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(dict_['value'] == 10) - ob.PublicEvent -= handler - self.assertTrue(dict_['value'] == 10) + ob.PublicEvent -= GenericHandler.handler + - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(dict_['value'] == 10) +def test_function_handler(): + """Test function handlers.""" + ob = EventTest() + dict_ = {'value': None} - def test_add_non_callable_handler(self): - """Test handling of attempts to add non-callable handlers.""" + def handler(sender, args, dict_=dict_): + dict_['value'] = args.value - with self.assertRaises(TypeError): - ob = EventTest() - ob.PublicEvent += 10 + ob.PublicEvent += handler + assert dict_['value'] is None - with self.assertRaises(TypeError): - ob = EventTest() - ob.PublicEvent += "spam" + ob.OnPublicEvent(EventArgsTest(10)) + assert dict_['value'] == 10 - with self.assertRaises(TypeError): - class Spam(object): - pass + ob.PublicEvent -= handler + assert dict_['value'] == 10 - ob = EventTest() - ob.PublicEvent += Spam() + ob.OnPublicEvent(EventArgsTest(20)) + assert dict_['value'] == 10 - def test_remove_multiple_handlers(self): - """Test removing multiple instances of the same handler.""" + +def test_add_non_callable_handler(): + """Test handling of attempts to add non-callable handlers.""" + + with pytest.raises(TypeError): ob = EventTest() - handler = MultipleHandler() + ob.PublicEvent += 10 - h1 = handler.handler - ob.PublicEvent += h1 + with pytest.raises(TypeError): + ob = EventTest() + ob.PublicEvent += "spam" - h2 = handler.handler - ob.PublicEvent += h2 + with pytest.raises(TypeError): + class Spam(object): + pass - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 20) + ob = EventTest() + ob.PublicEvent += Spam() - ob.PublicEvent -= h1 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 30) +def test_remove_multiple_handlers(): + """Test removing multiple instances of the same handler.""" + ob = EventTest() + handler = MultipleHandler() - ob.PublicEvent -= h2 + h1 = handler.handler + ob.PublicEvent += h1 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 30) + h2 = handler.handler + ob.PublicEvent += h2 - # try again, removing in a different order. + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 20 - ob = EventTest() - handler = MultipleHandler() + ob.PublicEvent -= h1 - h1 = handler.handler - ob.PublicEvent += h1 + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 30 - h2 = handler.handler - ob.PublicEvent += h2 + ob.PublicEvent -= h2 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 20) + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 30 - ob.PublicEvent -= h2 + # try again, removing in a different order. - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 30) + ob = EventTest() + handler = MultipleHandler() - ob.PublicEvent -= h1 + h1 = handler.handler + ob.PublicEvent += h1 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 30) + h2 = handler.handler + ob.PublicEvent += h2 - def test_remove_multiple_static_handlers(self): - """Test removing multiple instances of a static handler.""" - ob = EventTest() - handler = MultipleHandler() + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 20 - h1 = handler.handler - ob.PublicStaticEvent += h1 + ob.PublicEvent -= h2 - h2 = handler.handler - ob.PublicStaticEvent += h2 + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 30 - ob.OnPublicStaticEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 20) + ob.PublicEvent -= h1 - ob.PublicStaticEvent -= h1 + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 30 - ob.OnPublicStaticEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 30) - ob.PublicStaticEvent -= h2 +def test_remove_multiple_static_handlers(): + """Test removing multiple instances of a static handler.""" + ob = EventTest() + handler = MultipleHandler() - ob.OnPublicStaticEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 30) + h1 = handler.handler + ob.PublicStaticEvent += h1 - # try again, removing in a different order. + h2 = handler.handler + ob.PublicStaticEvent += h2 - ob = EventTest() - handler = MultipleHandler() + ob.OnPublicStaticEvent(EventArgsTest(10)) + assert handler.value == 20 - h1 = handler.handler - ob.PublicStaticEvent += h1 + ob.PublicStaticEvent -= h1 - h2 = handler.handler - ob.PublicStaticEvent += h2 + ob.OnPublicStaticEvent(EventArgsTest(10)) + assert handler.value == 30 - ob.OnPublicStaticEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 20) + ob.PublicStaticEvent -= h2 - ob.PublicStaticEvent -= h2 + ob.OnPublicStaticEvent(EventArgsTest(10)) + assert handler.value == 30 - ob.OnPublicStaticEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 30) + # try again, removing in a different order. - ob.PublicStaticEvent -= h1 + ob = EventTest() + handler = MultipleHandler() - ob.OnPublicStaticEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 30) + h1 = handler.handler + ob.PublicStaticEvent += h1 - def test_random_multiple_handlers(self): - """Test random subscribe / unsubscribe of the same handlers.""" - import random - ob = EventTest() - handler = MultipleHandler() - handler2 = MultipleHandler() + h2 = handler.handler + ob.PublicStaticEvent += h2 - ob.PublicEvent += handler2.handler - ob.PublicEvent += handler2.handler + ob.OnPublicStaticEvent(EventArgsTest(10)) + assert handler.value == 20 - handlers = [] - for _ in range(30): - method = handler.handler - ob.PublicEvent += method - handlers.append(method) + ob.PublicStaticEvent -= h2 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 300) - self.assertTrue(handler2.value == 20) - handler.value = 0 - handler2.value = 0 - - for i in range(30): - item = random.choice(handlers) - handlers.remove(item) - ob.PublicEvent -= item - handler.value = 0 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == (len(handlers) * 10)) - self.assertTrue(handler2.value == ((i + 1) * 20)) - - handler2.value = 0 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler2.value == 20) + ob.OnPublicStaticEvent(EventArgsTest(10)) + assert handler.value == 30 - ob.PublicEvent -= handler2.handler + ob.PublicStaticEvent -= h1 - handler2.value = 0 - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler2.value == 10) + ob.OnPublicStaticEvent(EventArgsTest(10)) + assert handler.value == 30 + + +def test_random_multiple_handlers(): + """Test random subscribe / unsubscribe of the same handlers.""" + import random + ob = EventTest() + handler = MultipleHandler() + handler2 = MultipleHandler() + + ob.PublicEvent += handler2.handler + ob.PublicEvent += handler2.handler - ob.PublicEvent -= handler2.handler + handlers = [] + for _ in range(30): + method = handler.handler + ob.PublicEvent += method + handlers.append(method) - handler2.value = 0 + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 300 + assert handler2.value == 20 + handler.value = 0 + handler2.value = 0 + + for i in range(30): + item = random.choice(handlers) + handlers.remove(item) + ob.PublicEvent -= item + handler.value = 0 ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler2.value == 0) + assert handler.value == (len(handlers) * 10) + assert handler2.value == ((i + 1) * 20) - def test_remove_internal_call_handler(self): - """Test remove on an event sink implemented w/internalcall.""" - ob = EventTest() + handler2.value = 0 + ob.OnPublicEvent(EventArgsTest(10)) + assert handler2.value == 20 - def h(sender, args): - pass + ob.PublicEvent -= handler2.handler - ob.PublicEvent += h - ob.PublicEvent -= h + handler2.value = 0 + ob.OnPublicEvent(EventArgsTest(10)) + assert handler2.value == 10 - def test_remove_unknown_handler(self): - """Test removing an event handler that was never added.""" + ob.PublicEvent -= handler2.handler - with self.assertRaises(ValueError): - ob = EventTest() - handler = GenericHandler() + handler2.value = 0 + ob.OnPublicEvent(EventArgsTest(10)) + assert handler2.value == 0 - ob.PublicEvent -= handler.handler - def test_handler_callback_failure(self): - """Test failure mode for inappropriate handlers.""" +def test_remove_internal_call_handler(): + """Test remove on an event sink implemented w/internalcall.""" + ob = EventTest() - class BadHandler(object): - def handler(self, one): - return 'too many' + def h(sender, args): + pass + + ob.PublicEvent += h + ob.PublicEvent -= h - ob = EventTest() - handler = BadHandler() - with self.assertRaises(TypeError): - ob.PublicEvent += handler.handler - ob.OnPublicEvent(EventArgsTest(10)) +def test_remove_unknown_handler(): + """Test removing an event handler that was never added.""" + + with pytest.raises(ValueError): + ob = EventTest() + handler = GenericHandler() ob.PublicEvent -= handler.handler - class BadHandler(object): - def handler(self, one, two, three, four, five): - return 'not enough' - ob = EventTest() - handler = BadHandler() +def test_handler_callback_failure(): + """Test failure mode for inappropriate handlers.""" - with self.assertRaises(TypeError): - ob.PublicEvent += handler.handler - ob.OnPublicEvent(EventArgsTest(10)) + class BadHandler(object): + def handler(self, one): + return 'too many' - ob.PublicEvent -= handler.handler + ob = EventTest() + handler = BadHandler() - def test_incorrect_invokation(self): - """Test incorrect invocation of events.""" - ob = EventTest() + with pytest.raises(TypeError): + ob.PublicEvent += handler.handler + ob.OnPublicEvent(EventArgsTest(10)) - handler = GenericHandler() + ob.PublicEvent -= handler.handler + + class BadHandler(object): + def handler(self, one, two, three, four, five): + return 'not enough' + + ob = EventTest() + handler = BadHandler() + + with pytest.raises(TypeError): ob.PublicEvent += handler.handler + ob.OnPublicEvent(EventArgsTest(10)) - with self.assertRaises(TypeError): - ob.OnPublicEvent() + ob.PublicEvent -= handler.handler - with self.assertRaises(TypeError): - ob.OnPublicEvent(32) - ob.PublicEvent -= handler.handler +def test_incorrect_invokation(): + """Test incorrect invocation of events.""" + ob = EventTest() - def test_explicit_cls_event_registration(self): - """Test explicit CLS event registration.""" - from Python.Test import EventHandlerTest + handler = GenericHandler() + ob.PublicEvent += handler.handler - ob = EventTest() - handler = GenericHandler() + with pytest.raises(TypeError): + ob.OnPublicEvent() - delegate = EventHandlerTest(handler.handler) - ob.add_PublicEvent(delegate) - self.assertTrue(handler.value is None) + with pytest.raises(TypeError): + ob.OnPublicEvent(32) - ob.OnPublicEvent(EventArgsTest(10)) - self.assertTrue(handler.value == 10) + ob.PublicEvent -= handler.handler + + +def test_explicit_cls_event_registration(): + """Test explicit CLS event registration.""" + from Python.Test import EventHandlerTest - ob.remove_PublicEvent(delegate) - self.assertTrue(handler.value == 10) + ob = EventTest() + handler = GenericHandler() - ob.OnPublicEvent(EventArgsTest(20)) - self.assertTrue(handler.value == 10) + delegate = EventHandlerTest(handler.handler) + ob.add_PublicEvent(delegate) + assert handler.value is None - def test_implicit_cls_event_registration(self): - """Test implicit CLS event registration.""" + ob.OnPublicEvent(EventArgsTest(10)) + assert handler.value == 10 - with self.assertRaises(TypeError): - ob = EventTest() - handler = GenericHandler() - ob.add_PublicEvent(handler.handler) + ob.remove_PublicEvent(delegate) + assert handler.value == 10 - def test_event_descriptor_abuse(self): - """Test event descriptor abuse.""" + ob.OnPublicEvent(EventArgsTest(20)) + assert handler.value == 10 - with self.assertRaises(TypeError): - del EventTest.PublicEvent - with self.assertRaises(TypeError): - del EventTest.__dict__['PublicEvent'] +def test_implicit_cls_event_registration(): + """Test implicit CLS event registration.""" + + with pytest.raises(TypeError): + ob = EventTest() + handler = GenericHandler() + ob.add_PublicEvent(handler.handler) - desc = EventTest.__dict__['PublicEvent'] - with self.assertRaises(TypeError): - desc.__get__(0, 0) +def test_event_descriptor_abuse(): + """Test event descriptor abuse.""" - with self.assertRaises(TypeError): - desc.__set__(0, 0) + with pytest.raises(TypeError): + del EventTest.PublicEvent - with self.assertRaises(TypeError): - ob = EventTest() - ob.PublicEvent = 0 + with pytest.raises(TypeError): + del EventTest.__dict__['PublicEvent'] - with self.assertRaises(TypeError): - EventTest.PublicStaticEvent = 0 + desc = EventTest.__dict__['PublicEvent'] + with pytest.raises(TypeError): + desc.__get__(0, 0) + + with pytest.raises(TypeError): + desc.__set__(0, 0) + + with pytest.raises(TypeError): + ob = EventTest() + ob.PublicEvent = 0 -def test_suite(): - return unittest.makeSuite(EventTests) + with pytest.raises(TypeError): + EventTest.PublicStaticEvent = 0 diff --git a/src/tests/test_exceptions.py b/src/tests/test_exceptions.py index 2fb55589c..f47209f6d 100644 --- a/src/tests/test_exceptions.py +++ b/src/tests/test_exceptions.py @@ -1,328 +1,347 @@ # -*- coding: utf-8 -*- +"""Test exception support.""" + import sys -import unittest import System +import pytest + +from ._compat import PY2, PY3, pickle, text_type + + +def test_unified_exception_semantics(): + """Test unified exception semantics.""" + e = System.Exception('Something bad happened') + assert isinstance(e, Exception) + assert isinstance(e, System.Exception) + + +def test_standard_exception_attributes(): + """Test accessing standard exception attributes.""" + from System import OverflowException + from Python.Test import ExceptionTest + + e = ExceptionTest.GetExplicitException() + assert isinstance(e, OverflowException) + + assert e.Message == 'error' + + e.Source = 'Test Suite' + assert e.Source == 'Test Suite' + + v = e.ToString() + assert len(v) > 0 + + +def test_extended_exception_attributes(): + """Test accessing extended exception attributes.""" + from Python.Test import ExceptionTest, ExtendedException + from System import OverflowException + + e = ExceptionTest.GetExtendedException() + assert isinstance(e, ExtendedException) + assert isinstance(e, OverflowException) + assert isinstance(e, System.Exception) + + assert e.Message == 'error' + + 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.GetExtraInfo() == 'changed' + + +def test_raise_class_exception(): + """Test class exception propagation.""" + from System import NullReferenceException + + with pytest.raises(NullReferenceException) as cm: + raise NullReferenceException + + exc = cm.value + assert isinstance(exc, NullReferenceException) + + +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: + type_, value, tb = sys.exc_info() + assert type_ is NullReferenceException + assert value.Message == "message" + assert exc.Message == "message" + # FIXME: Lower-case message isn't implemented + # self.assertTrue(exc.message == "message") + assert value is exc + + +def test_raise_class_exception_with_value(): + """Test class exception propagation with associated value.""" + from System import NullReferenceException + + with pytest.raises(NullReferenceException) as cm: + raise NullReferenceException('Aiiieee!') + + exc = cm.value + assert isinstance(exc, NullReferenceException) + assert exc.Message == 'Aiiieee!' + + +def test_raise_instance_exception(): + """Test instance exception propagation.""" + from System import NullReferenceException + + with pytest.raises(NullReferenceException) as cm: + raise NullReferenceException() + + exc = cm.value + assert isinstance(exc, NullReferenceException) + assert len(exc.Message) > 0 + + +def test_raise_instance_exception_with_args(): + """Test instance exception propagation with args.""" + from System import NullReferenceException -from _compat import PY2, PY3, pickle, text_type + with pytest.raises(NullReferenceException) as cm: + raise NullReferenceException("Aiiieee!") + exc = cm.value + assert isinstance(exc, NullReferenceException) + assert exc.Message == 'Aiiieee!' -class ExceptionTests(unittest.TestCase): - """Test exception support.""" - def test_unified_exception_semantics(self): - """Test unified exception semantics.""" - e = System.Exception('Something bad happened') - self.assertTrue(isinstance(e, Exception)) - self.assertTrue(isinstance(e, System.Exception)) +def test_managed_exception_propagation(): + """Test propagation of exceptions raised in managed code.""" + from System import Decimal, OverflowException - def test_standard_exception_attributes(self): - """Test accessing standard exception attributes.""" - from System import OverflowException - from Python.Test import ExceptionTest + with pytest.raises(OverflowException): + Decimal.ToInt64(Decimal.MaxValue) - e = ExceptionTest.GetExplicitException() - self.assertTrue(isinstance(e, OverflowException)) - self.assertTrue(e.Message == 'error') +def test_managed_exception_conversion(): + """Test conversion of managed exceptions.""" + from System import OverflowException + from Python.Test import ExceptionTest - e.Source = 'Test Suite' - self.assertTrue(e.Source == 'Test Suite') + e = ExceptionTest.GetBaseException() + assert isinstance(e, System.Exception) - v = e.ToString() - self.assertTrue(len(v) > 0) + e = ExceptionTest.GetExplicitException() + assert isinstance(e, OverflowException) + assert isinstance(e, System.Exception) - def test_extended_exception_attributes(self): - """Test accessing extended exception attributes.""" - from Python.Test import ExceptionTest, ExtendedException - from System import OverflowException + e = ExceptionTest.GetWidenedException() + assert isinstance(e, OverflowException) + assert isinstance(e, System.Exception) - e = ExceptionTest.GetExtendedException() - self.assertTrue(isinstance(e, ExtendedException)) - self.assertTrue(isinstance(e, OverflowException)) - self.assertTrue(isinstance(e, System.Exception)) + v = ExceptionTest.SetBaseException(System.Exception('error')) + assert v - self.assertTrue(e.Message == 'error') + v = ExceptionTest.SetExplicitException(OverflowException('error')) + assert v - e.Source = 'Test Suite' - self.assertTrue(e.Source == 'Test Suite') + v = ExceptionTest.SetWidenedException(OverflowException('error')) + assert v - v = e.ToString() - self.assertTrue(len(v) > 0) - self.assertTrue(e.ExtraProperty == 'extra') - e.ExtraProperty = 'changed' - self.assertTrue(e.ExtraProperty == 'changed') +def test_catch_exception_from_managed_method(): + """Test catching an exception from a managed method.""" + from Python.Test import ExceptionTest + from System import OverflowException - self.assertTrue(e.GetExtraInfo() == 'changed') + with pytest.raises(OverflowException) as cm: + ExceptionTest().ThrowException() - def test_raise_class_exception(self): - """Test class exception propagation.""" - from System import NullReferenceException + e = cm.value + assert isinstance(e, OverflowException) - with self.assertRaises(NullReferenceException) as cm: - raise NullReferenceException - exc = cm.exception - self.assertTrue(isinstance(exc, NullReferenceException)) +def test_catch_exception_from_managed_property(): + """Test catching an exception from a managed property.""" + from Python.Test import ExceptionTest + from System import OverflowException - def test_exc_info(self): - """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: - type_, value, tb = sys.exc_info() - self.assertTrue(type_ is NullReferenceException) - self.assertTrue(value.Message == "message") - self.assertTrue(exc.Message == "message") - # FIXME: Lower-case message isn't implemented - # self.assertTrue(exc.message == "message") - self.assertTrue(value is exc) + with pytest.raises(OverflowException) as cm: + _ = ExceptionTest().ThrowProperty - def test_raise_class_exception_with_value(self): - """Test class exception propagation with associated value.""" - from System import NullReferenceException + e = cm.value + assert isinstance(e, OverflowException) - with self.assertRaises(NullReferenceException) as cm: - raise NullReferenceException('Aiiieee!') + with pytest.raises(OverflowException) as cm: + ExceptionTest().ThrowProperty = 1 - exc = cm.exception - self.assertTrue(isinstance(exc, NullReferenceException)) - self.assertTrue(exc.Message == 'Aiiieee!') + e = cm.value + assert isinstance(e, OverflowException) - def test_raise_instance_exception(self): - """Test instance exception propagation.""" - from System import NullReferenceException - with self.assertRaises(NullReferenceException) as cm: - raise NullReferenceException() +def test_catch_exception_managed_class(): + """Test catching the managed class of an exception.""" + from System import OverflowException - exc = cm.exception - self.assertTrue(isinstance(exc, NullReferenceException)) - self.assertTrue(len(exc.Message) > 0) + with pytest.raises(OverflowException): + raise OverflowException('overflow') - def test_raise_instance_exception_with_args(self): - """Test instance exception propagation with args.""" - from System import NullReferenceException - with self.assertRaises(NullReferenceException) as cm: - raise NullReferenceException("Aiiieee!") +def test_catch_exception_python_class(): + """Test catching the python class of an exception.""" + from System import OverflowException - exc = cm.exception - self.assertTrue(isinstance(exc, NullReferenceException)) - self.assertTrue(exc.Message == 'Aiiieee!') + with pytest.raises(Exception): + raise OverflowException('overflow') - def test_managed_exception_propagation(self): - """Test propagation of exceptions raised in managed code.""" - from System import Decimal, OverflowException - with self.assertRaises(OverflowException): - Decimal.ToInt64(Decimal.MaxValue) +def test_catch_exception_base_class(): + """Test catching the base of an exception.""" + from System import OverflowException, ArithmeticException - def test_managed_exception_conversion(self): - """Test conversion of managed exceptions.""" - from System import OverflowException - from Python.Test import ExceptionTest + with pytest.raises(ArithmeticException): + raise OverflowException('overflow') - e = ExceptionTest.GetBaseException() - self.assertTrue(isinstance(e, System.Exception)) - e = ExceptionTest.GetExplicitException() - self.assertTrue(isinstance(e, OverflowException)) - self.assertTrue(isinstance(e, System.Exception)) +def test_catch_exception_nested_base_class(): + """Test catching the nested base of an exception.""" + from System import OverflowException, SystemException - e = ExceptionTest.GetWidenedException() - self.assertTrue(isinstance(e, OverflowException)) - self.assertTrue(isinstance(e, System.Exception)) + with pytest.raises(SystemException): + raise OverflowException('overflow') - v = ExceptionTest.SetBaseException(System.Exception('error')) - self.assertTrue(v) - v = ExceptionTest.SetExplicitException(OverflowException('error')) - self.assertTrue(v) +def test_catch_exception_with_assignment(): + """Test catching an exception with assignment.""" + from System import OverflowException - v = ExceptionTest.SetWidenedException(OverflowException('error')) - self.assertTrue(v) + with pytest.raises(OverflowException) as cm: + raise OverflowException('overflow') - def test_catch_exception_from_managed_method(self): - """Test catching an exception from a managed method.""" - from Python.Test import ExceptionTest - from System import OverflowException + e = cm.value + assert isinstance(e, OverflowException) - with self.assertRaises(OverflowException) as cm: - ExceptionTest().ThrowException() - e = cm.exception - self.assertTrue(isinstance(e, OverflowException)) +def test_catch_exception_unqualified(): + """Test catching an unqualified exception.""" + from System import OverflowException - def test_catch_exception_from_managed_property(self): - """Test catching an exception from a managed property.""" - from Python.Test import ExceptionTest - from System import OverflowException + try: + raise OverflowException('overflow') + except: + pass + else: + self.fail("failed to catch unqualified exception") - with self.assertRaises(OverflowException) as cm: - _ = ExceptionTest().ThrowProperty - e = cm.exception - self.assertTrue(isinstance(e, OverflowException)) +def test_catch_baseexception(): + """Test catching an unqualified exception with BaseException.""" + from System import OverflowException - with self.assertRaises(OverflowException) as cm: - ExceptionTest().ThrowProperty = 1 + with pytest.raises(BaseException): + raise OverflowException('overflow') - e = cm.exception - self.assertTrue(isinstance(e, OverflowException)) - def test_catch_exception_managed_class(self): - """Test catching the managed class of an exception.""" - from System import OverflowException +def test_apparent_module_of_exception(): + """Test the apparent module of an exception.""" + from System import OverflowException - with self.assertRaises(OverflowException): - raise OverflowException('overflow') + assert System.Exception.__module__ == 'System' + assert OverflowException.__module__ == 'System' - def test_catch_exception_python_class(self): - """Test catching the python class of an exception.""" - from System import OverflowException - with self.assertRaises(Exception): - raise OverflowException('overflow') +def test_str_of_exception(): + """Test the str() representation of an exception.""" + from System import NullReferenceException, Convert, FormatException - def test_catch_exception_base_class(self): - """Test catching the base of an exception.""" - from System import OverflowException, ArithmeticException + e = NullReferenceException('') + assert str(e) == '' - with self.assertRaises(ArithmeticException): - raise OverflowException('overflow') + e = NullReferenceException('Something bad happened') + assert str(e).startswith('Something bad happened') - def test_catch_exception_nested_base_class(self): - """Test catching the nested base of an exception.""" - from System import OverflowException, SystemException + with pytest.raises(FormatException) as cm: + Convert.ToDateTime('this will fail') - with self.assertRaises(SystemException): - raise OverflowException('overflow') + e = cm.value + # fix for international installation + msg = text_type(e).encode("utf8") + fnd = text_type('System.Convert.ToDateTime').encode("utf8") + assert msg.find(fnd) > -1, msg - def test_catch_exception_with_assignment(self): - """Test catching an exception with assignment.""" - from System import OverflowException - with self.assertRaises(OverflowException) as cm: - raise OverflowException('overflow') +def test_python_compat_of_managed_exceptions(): + """Test managed exceptions compatible with Python's implementation""" + from System import OverflowException + msg = "Simple message" - e = cm.exception - self.assertTrue(isinstance(e, OverflowException)) + e = OverflowException(msg) + assert str(e) == msg + assert text_type(e) == msg - def test_catch_exception_unqualified(self): - """Test catching an unqualified exception.""" - from System import OverflowException + assert e.args == (msg,) + assert isinstance(e.args, tuple) + if PY3: + assert repr(e) == "OverflowException('Simple message',)" + elif PY2: + assert repr(e) == "OverflowException(u'Simple message',)" - try: - raise OverflowException('overflow') - except: - pass - else: - self.fail("failed to catch unqualified exception") - def test_catch_baseexception(self): - """Test catching an unqualified exception with BaseException.""" - from System import OverflowException +def test_exception_is_instance_of_system_object(): + """Test behavior of isinstance(, System.Object).""" + # This is an anti-test, in that this is a caveat of the current + # implementation. Because exceptions are not allowed to be new-style + # classes, we wrap managed exceptions in a general-purpose old-style + # class that delegates to the wrapped object. This makes _almost_ + # everything work as expected, except that an isinstance check against + # CLR.System.Object will fail for a managed exception (because a new + # style class cannot appear in the __bases__ of an old-style class + # without causing a crash in the CPython interpreter). This test is + # here mainly to remind me to update the caveat in the documentation + # one day when when exceptions can be new-style classes. - with self.assertRaises(BaseException): - raise OverflowException('overflow') + # This behavior is now over-shadowed by the implementation of + # __instancecheck__ (i.e., overloading isinstance), so for all Python + # version >= 2.6 we expect isinstance(, Object) to + # be true, even though it does not really subclass Object. + from System import OverflowException, Object - def test_apparent_module_of_exception(self): - """Test the apparent module of an exception.""" - from System import OverflowException + o = OverflowException('error') - self.assertTrue(System.Exception.__module__ == 'System') - self.assertTrue(OverflowException.__module__ == 'System') + if sys.version_info >= (2, 6): + assert isinstance(o, Object) + else: + assert not isinstance(o, Object) - def test_str_of_exception(self): - """Test the str() representation of an exception.""" - from System import NullReferenceException, Convert, FormatException - e = NullReferenceException('') - self.assertEqual(str(e), '') +def test_pickling_exceptions(): + exc = System.Exception("test") + dumped = pickle.dumps(exc) + loaded = pickle.loads(dumped) - e = NullReferenceException('Something bad happened') - self.assertTrue(str(e).startswith('Something bad happened')) + assert exc.args == loaded.args - with self.assertRaises(FormatException) as cm: - Convert.ToDateTime('this will fail') - e = cm.exception - # fix for international installation - msg = text_type(e).encode("utf8") - fnd = text_type('System.Convert.ToDateTime').encode("utf8") - self.assertTrue(msg.find(fnd) > -1, msg) +@pytest.mark.skipif(PY2, reason="__cause__ isn't implemented in PY2") +def test_chained_exceptions(): + from Python.Test import ExceptionTest - def test_python_compat_of_managed_exceptions(self): - """Test managed exceptions compatible with Python's implementation""" - from System import OverflowException - msg = "Simple message" + with pytest.raises(Exception) as cm: + ExceptionTest.ThrowChainedExceptions() - e = OverflowException(msg) - self.assertEqual(str(e), msg) - self.assertEqual(text_type(e), msg) + exc = cm.value - self.assertEqual(e.args, (msg,)) - self.assertTrue(isinstance(e.args, tuple)) - if PY3: - self.assertEqual(repr(e), "OverflowException('Simple message',)") - elif PY2: - self.assertEqual(repr(e), "OverflowException(u'Simple message',)") - - def test_exception_is_instance_of_system_object(self): - """Test behavior of isinstance(, System.Object).""" - # This is an anti-test, in that this is a caveat of the current - # implementation. Because exceptions are not allowed to be new-style - # classes, we wrap managed exceptions in a general-purpose old-style - # class that delegates to the wrapped object. This makes _almost_ - # everything work as expected, except that an isinstance check against - # CLR.System.Object will fail for a managed exception (because a new - # style class cannot appear in the __bases__ of an old-style class - # without causing a crash in the CPython interpreter). This test is - # here mainly to remind me to update the caveat in the documentation - # one day when when exceptions can be new-style classes. - - # This behavior is now over-shadowed by the implementation of - # __instancecheck__ (i.e., overloading isinstance), so for all Python - # version >= 2.6 we expect isinstance(, Object) to - # be true, even though it does not really subclass Object. - from System import OverflowException, Object - - o = OverflowException('error') - - if sys.version_info >= (2, 6): - self.assertTrue(isinstance(o, Object)) - else: - self.assertFalse(isinstance(o, Object)) - - def test_pickling_exceptions(self): - exc = System.Exception("test") - dumped = pickle.dumps(exc) - loaded = pickle.loads(dumped) - - self.assertEqual(exc.args, loaded.args) - - @unittest.skipIf(PY2, "__cause__ isn't implemented in PY2") - def test_chained_exceptions(self): - from Python.Test import ExceptionTest - - with self.assertRaises(Exception) as cm: - ExceptionTest.ThrowChainedExceptions() - - exc = cm.exception - - msgs = ("Outer exception", - "Inner exception", - "Innermost exception",) - for msg in msgs: - self.assertEqual(exc.Message, msg) - self.assertEqual(exc.__cause__, exc.InnerException) - exc = exc.__cause__ - - -def test_suite(): - return unittest.makeSuite(ExceptionTests) + msgs = ("Outer exception", + "Inner exception", + "Innermost exception",) + for msg in msgs: + assert exc.Message == msg + assert exc.__cause__ == exc.InnerException + exc = exc.__cause__ diff --git a/src/tests/test_field.py b/src/tests/test_field.py index b1d596fea..d187de5d2 100644 --- a/src/tests/test_field.py +++ b/src/tests/test_field.py @@ -1,369 +1,392 @@ # -*- coding: utf-8 -*- -import unittest +"""Test CLR field support.""" import System +import pytest from Python.Test import FieldTest -class FieldTests(unittest.TestCase): - """Test CLR field support.""" +def test_public_instance_field(): + """Test public instance fields.""" + ob = FieldTest() + assert ob.PublicField == 0 - def test_public_instance_field(self): - """Test public instance fields.""" - ob = FieldTest() - self.assertTrue(ob.PublicField == 0) + ob.PublicField = 1 + assert ob.PublicField == 1 - ob.PublicField = 1 - self.assertTrue(ob.PublicField == 1) + with pytest.raises(TypeError): + del FieldTest().PublicField - with self.assertRaises(TypeError): - del FieldTest().PublicField - def test_public_static_field(self): - """Test public static fields.""" - ob = FieldTest() - self.assertTrue(FieldTest.PublicStaticField == 0) +def test_public_static_field(): + """Test public static fields.""" + ob = FieldTest() + assert FieldTest.PublicStaticField == 0 - FieldTest.PublicStaticField = 1 - self.assertTrue(FieldTest.PublicStaticField == 1) + FieldTest.PublicStaticField = 1 + assert FieldTest.PublicStaticField == 1 - self.assertTrue(ob.PublicStaticField == 1) - ob.PublicStaticField = 0 - self.assertTrue(ob.PublicStaticField == 0) + assert ob.PublicStaticField == 1 + ob.PublicStaticField = 0 + assert ob.PublicStaticField == 0 - with self.assertRaises(TypeError): - del FieldTest.PublicStaticField + with pytest.raises(TypeError): + del FieldTest.PublicStaticField - with self.assertRaises(TypeError): - del FieldTest().PublicStaticField + with pytest.raises(TypeError): + del FieldTest().PublicStaticField - def test_protected_instance_field(self): - """Test protected instance fields.""" - ob = FieldTest() - self.assertTrue(ob.ProtectedField == 0) - ob.ProtectedField = 1 - self.assertTrue(ob.ProtectedField == 1) +def test_protected_instance_field(): + """Test protected instance fields.""" + ob = FieldTest() + assert ob.ProtectedField == 0 - with self.assertRaises(TypeError): - del FieldTest().ProtectedField + ob.ProtectedField = 1 + assert ob.ProtectedField == 1 - def test_protected_static_field(self): - """Test protected static fields.""" - ob = FieldTest() - self.assertTrue(FieldTest.ProtectedStaticField == 0) + with pytest.raises(TypeError): + del FieldTest().ProtectedField - FieldTest.ProtectedStaticField = 1 - self.assertTrue(FieldTest.ProtectedStaticField == 1) - self.assertTrue(ob.ProtectedStaticField == 1) - ob.ProtectedStaticField = 0 - self.assertTrue(ob.ProtectedStaticField == 0) +def test_protected_static_field(): + """Test protected static fields.""" + ob = FieldTest() + assert FieldTest.ProtectedStaticField == 0 - with self.assertRaises(TypeError): - del FieldTest.ProtectedStaticField + FieldTest.ProtectedStaticField = 1 + assert FieldTest.ProtectedStaticField == 1 - with self.assertRaises(TypeError): - del FieldTest().ProtectedStaticField + assert ob.ProtectedStaticField == 1 + ob.ProtectedStaticField = 0 + assert ob.ProtectedStaticField == 0 - def test_read_only_instance_field(self): - """Test readonly instance fields.""" - self.assertTrue(FieldTest().ReadOnlyField == 0) + with pytest.raises(TypeError): + del FieldTest.ProtectedStaticField - with self.assertRaises(TypeError): - FieldTest().ReadOnlyField = 1 + with pytest.raises(TypeError): + del FieldTest().ProtectedStaticField - with self.assertRaises(TypeError): - del FieldTest().ReadOnlyField - def test_read_only_static_field(self): - """Test readonly static fields.""" - ob = FieldTest() +def test_read_only_instance_field(): + """Test readonly instance fields.""" + assert FieldTest().ReadOnlyField == 0 - self.assertTrue(FieldTest.ReadOnlyStaticField == 0) - self.assertTrue(ob.ReadOnlyStaticField == 0) + with pytest.raises(TypeError): + FieldTest().ReadOnlyField = 1 - with self.assertRaises(TypeError): - FieldTest.ReadOnlyStaticField = 1 + with pytest.raises(TypeError): + del FieldTest().ReadOnlyField - with self.assertRaises(TypeError): - FieldTest().ReadOnlyStaticField = 1 - with self.assertRaises(TypeError): - del FieldTest.ReadOnlyStaticField +def test_read_only_static_field(): + """Test readonly static fields.""" + ob = FieldTest() - with self.assertRaises(TypeError): - del FieldTest().ReadOnlyStaticField + assert FieldTest.ReadOnlyStaticField == 0 + assert ob.ReadOnlyStaticField == 0 - def test_constant_field(self): - """Test const fields.""" - ob = FieldTest() + with pytest.raises(TypeError): + FieldTest.ReadOnlyStaticField = 1 - self.assertTrue(FieldTest.ConstField == 0) - self.assertTrue(ob.ConstField == 0) + with pytest.raises(TypeError): + FieldTest().ReadOnlyStaticField = 1 - with self.assertRaises(TypeError): - FieldTest().ConstField = 1 + with pytest.raises(TypeError): + del FieldTest.ReadOnlyStaticField - with self.assertRaises(TypeError): - FieldTest.ConstField = 1 + with pytest.raises(TypeError): + del FieldTest().ReadOnlyStaticField - with self.assertRaises(TypeError): - del FieldTest().ConstField - with self.assertRaises(TypeError): - del FieldTest.ConstField +def test_constant_field(): + """Test const fields.""" + ob = FieldTest() - def test_internal_field(self): - """Test internal fields.""" + assert FieldTest.ConstField == 0 + assert ob.ConstField == 0 - with self.assertRaises(AttributeError): - _ = FieldTest().InternalField + with pytest.raises(TypeError): + FieldTest().ConstField = 1 - with self.assertRaises(AttributeError): - _ = FieldTest().InternalStaticField + with pytest.raises(TypeError): + FieldTest.ConstField = 1 - with self.assertRaises(AttributeError): - _ = FieldTest.InternalStaticField + with pytest.raises(TypeError): + del FieldTest().ConstField - def test_private_field(self): - """Test private fields.""" + with pytest.raises(TypeError): + del FieldTest.ConstField - with self.assertRaises(AttributeError): - _ = FieldTest().PrivateField - with self.assertRaises(AttributeError): - _ = FieldTest().PrivateStaticField +def test_internal_field(): + """Test internal fields.""" - with self.assertRaises(AttributeError): - _ = FieldTest.PrivateStaticField + with pytest.raises(AttributeError): + _ = FieldTest().InternalField - def test_field_descriptor_get_set(self): - """Test field descriptor get / set.""" + with pytest.raises(AttributeError): + _ = FieldTest().InternalStaticField - # This test ensures that setting an attribute implemented with - # a descriptor actually goes through the descriptor (rather than - # silently replacing the descriptor in the instance or type dict. + with pytest.raises(AttributeError): + _ = FieldTest.InternalStaticField - ob = FieldTest() - self.assertTrue(FieldTest.PublicStaticField == 0) - self.assertTrue(ob.PublicStaticField == 0) +def test_private_field(): + """Test private fields.""" - descriptor = FieldTest.__dict__['PublicStaticField'] - self.assertTrue(type(descriptor) != int) + with pytest.raises(AttributeError): + _ = FieldTest().PrivateField - ob.PublicStaticField = 0 - descriptor = FieldTest.__dict__['PublicStaticField'] - self.assertTrue(type(descriptor) != int) + with pytest.raises(AttributeError): + _ = FieldTest().PrivateStaticField - FieldTest.PublicStaticField = 0 - descriptor = FieldTest.__dict__['PublicStaticField'] - self.assertTrue(type(descriptor) != int) + with pytest.raises(AttributeError): + _ = FieldTest.PrivateStaticField - def test_field_descriptor_wrong_type(self): - """Test setting a field using a value of the wrong type.""" - with self.assertRaises(TypeError): - FieldTest().PublicField = "spam" +def test_field_descriptor_get_set(): + """Test field descriptor get / set.""" - def test_field_descriptor_abuse(self): - """Test field descriptor abuse.""" - desc = FieldTest.__dict__['PublicField'] + # This test ensures that setting an attribute implemented with + # a descriptor actually goes through the descriptor (rather than + # silently replacing the descriptor in the instance or type dict. - with self.assertRaises(TypeError): - desc.__get__(0, 0) + ob = FieldTest() - with self.assertRaises(TypeError): - desc.__set__(0, 0) + assert FieldTest.PublicStaticField == 0 + assert ob.PublicStaticField == 0 - def test_boolean_field(self): - """Test boolean fields.""" - # change this to true / false later for Python 2.3? - ob = FieldTest() - self.assertTrue(ob.BooleanField is False) + descriptor = FieldTest.__dict__['PublicStaticField'] + assert type(descriptor) != int - ob.BooleanField = True - self.assertTrue(ob.BooleanField is True) + ob.PublicStaticField = 0 + descriptor = FieldTest.__dict__['PublicStaticField'] + assert type(descriptor) != int - ob.BooleanField = False - self.assertTrue(ob.BooleanField is False) + FieldTest.PublicStaticField = 0 + descriptor = FieldTest.__dict__['PublicStaticField'] + assert type(descriptor) != int - ob.BooleanField = 1 - self.assertTrue(ob.BooleanField is True) - ob.BooleanField = 0 - self.assertTrue(ob.BooleanField is False) +def test_field_descriptor_wrong_type(): + """Test setting a field using a value of the wrong type.""" - def test_sbyte_field(self): - """Test sbyte fields.""" - ob = FieldTest() - self.assertTrue(ob.SByteField == 0) + with pytest.raises(TypeError): + FieldTest().PublicField = "spam" - ob.SByteField = 1 - self.assertTrue(ob.SByteField == 1) - def test_byte_field(self): - """Test byte fields.""" - ob = FieldTest() - self.assertTrue(ob.ByteField == 0) +def test_field_descriptor_abuse(): + """Test field descriptor abuse.""" + desc = FieldTest.__dict__['PublicField'] - ob.ByteField = 1 - self.assertTrue(ob.ByteField == 1) + with pytest.raises(TypeError): + desc.__get__(0, 0) - def test_char_field(self): - """Test char fields.""" - ob = FieldTest() - self.assertTrue(ob.CharField == u'A') - self.assertTrue(ob.CharField == 'A') + with pytest.raises(TypeError): + desc.__set__(0, 0) - ob.CharField = 'B' - self.assertTrue(ob.CharField == u'B') - self.assertTrue(ob.CharField == 'B') - ob.CharField = u'C' - self.assertTrue(ob.CharField == u'C') - self.assertTrue(ob.CharField == 'C') +def test_boolean_field(): + """Test boolean fields.""" + # change this to true / false later for Python 2.3? + ob = FieldTest() + assert ob.BooleanField is False - def test_int16_field(self): - """Test int16 fields.""" - ob = FieldTest() - self.assertTrue(ob.Int16Field == 0) + ob.BooleanField = True + assert ob.BooleanField is True - ob.Int16Field = 1 - self.assertTrue(ob.Int16Field == 1) + ob.BooleanField = False + assert ob.BooleanField is False - def test_int32_field(self): - """Test int32 fields.""" - ob = FieldTest() - self.assertTrue(ob.Int32Field == 0) + ob.BooleanField = 1 + assert ob.BooleanField is True - ob.Int32Field = 1 - self.assertTrue(ob.Int32Field == 1) + ob.BooleanField = 0 + assert ob.BooleanField is False - def test_int64_field(self): - """Test int64 fields.""" - ob = FieldTest() - self.assertTrue(ob.Int64Field == 0) - ob.Int64Field = 1 - self.assertTrue(ob.Int64Field == 1) +def test_sbyte_field(): + """Test sbyte fields.""" + ob = FieldTest() + assert ob.SByteField == 0 - def test_uint16_field(self): - """Test uint16 fields.""" - ob = FieldTest() - self.assertTrue(ob.UInt16Field == 0) + ob.SByteField = 1 + assert ob.SByteField == 1 - ob.UInt16Field = 1 - self.assertTrue(ob.UInt16Field == 1) - def test_uint32_field(self): - """Test uint32 fields.""" - ob = FieldTest() - self.assertTrue(ob.UInt32Field == 0) +def test_byte_field(): + """Test byte fields.""" + ob = FieldTest() + assert ob.ByteField == 0 - ob.UInt32Field = 1 - self.assertTrue(ob.UInt32Field == 1) + ob.ByteField = 1 + assert ob.ByteField == 1 - def test_uint64_field(self): - """Test uint64 fields.""" - ob = FieldTest() - self.assertTrue(ob.UInt64Field == 0) - ob.UInt64Field = 1 - self.assertTrue(ob.UInt64Field == 1) +def test_char_field(): + """Test char fields.""" + ob = FieldTest() + assert ob.CharField == u'A' + assert ob.CharField == 'A' - def test_single_field(self): - """Test single fields.""" - ob = FieldTest() - self.assertTrue(ob.SingleField == 0.0) + ob.CharField = 'B' + assert ob.CharField == u'B' + assert ob.CharField == 'B' - ob.SingleField = 1.1 - self.assertTrue(ob.SingleField == 1.1) + ob.CharField = u'C' + assert ob.CharField == u'C' + assert ob.CharField == 'C' - def test_double_field(self): - """Test double fields.""" - ob = FieldTest() - self.assertTrue(ob.DoubleField == 0.0) - ob.DoubleField = 1.1 - self.assertTrue(ob.DoubleField == 1.1) +def test_int16_field(): + """Test int16 fields.""" + ob = FieldTest() + assert ob.Int16Field == 0 - def test_decimal_field(self): - """Test decimal fields.""" - ob = FieldTest() - self.assertTrue(ob.DecimalField == System.Decimal(0)) + ob.Int16Field = 1 + assert ob.Int16Field == 1 - ob.DecimalField = System.Decimal(1) - self.assertTrue(ob.DecimalField == System.Decimal(1)) - def test_string_field(self): - """Test string fields.""" - ob = FieldTest() - self.assertTrue(ob.StringField == "spam") +def test_int32_field(): + """Test int32 fields.""" + ob = FieldTest() + assert ob.Int32Field == 0 - ob.StringField = "eggs" - self.assertTrue(ob.StringField == "eggs") + ob.Int32Field = 1 + assert ob.Int32Field == 1 - def test_interface_field(self): - """Test interface fields.""" - from Python.Test import Spam, ISpam - ob = FieldTest() +def test_int64_field(): + """Test int64 fields.""" + ob = FieldTest() + assert ob.Int64Field == 0 - self.assertTrue(ISpam(ob.SpamField).GetValue() == "spam") - self.assertTrue(ob.SpamField.GetValue() == "spam") + ob.Int64Field = 1 + assert ob.Int64Field == 1 - ob.SpamField = Spam("eggs") - self.assertTrue(ISpam(ob.SpamField).GetValue() == "eggs") - self.assertTrue(ob.SpamField.GetValue() == "eggs") - def test_object_field(self): - """Test ob fields.""" - ob = FieldTest() - self.assertTrue(ob.ObjectField is None) +def test_uint16_field(): + """Test uint16 fields.""" + ob = FieldTest() + assert ob.UInt16Field == 0 - ob.ObjectField = System.String("spam") - self.assertTrue(ob.ObjectField == "spam") + ob.UInt16Field = 1 + assert ob.UInt16Field == 1 - ob.ObjectField = System.Int32(1) - self.assertTrue(ob.ObjectField == 1) - ob.ObjectField = None - self.assertTrue(ob.ObjectField is None) +def test_uint32_field(): + """Test uint32 fields.""" + ob = FieldTest() + assert ob.UInt32Field == 0 - def test_enum_field(self): - """Test enum fields.""" - from Python.Test import ShortEnum + ob.UInt32Field = 1 + assert ob.UInt32Field == 1 - ob = FieldTest() - self.assertTrue(ob.EnumField == ShortEnum.Zero) - ob.EnumField = ShortEnum.One - self.assertTrue(ob.EnumField == ShortEnum.One) +def test_uint64_field(): + """Test uint64 fields.""" + ob = FieldTest() + assert ob.UInt64Field == 0 - def test_nullable_field(self): - """Test nullable fields.""" - ob = FieldTest() + ob.UInt64Field = 1 + assert ob.UInt64Field == 1 - ob.StringField = None - self.assertTrue(ob.StringField is None) - ob.ObjectField = None - self.assertTrue(ob.ObjectField is None) +def test_single_field(): + """Test single fields.""" + ob = FieldTest() + assert ob.SingleField == 0.0 - ob.SpamField = None - self.assertTrue(ob.SpamField is None) + ob.SingleField = 1.1 + assert ob.SingleField == 1.1 - # Primitive types and enums should not be set to null. - with self.assertRaises(TypeError): - FieldTest().Int32Field = None +def test_double_field(): + """Test double fields.""" + ob = FieldTest() + assert ob.DoubleField == 0.0 - with self.assertRaises(TypeError): - FieldTest().EnumField = None + ob.DoubleField = 1.1 + assert ob.DoubleField == 1.1 -def test_suite(): - return unittest.makeSuite(FieldTests) +def test_decimal_field(): + """Test decimal fields.""" + ob = FieldTest() + assert ob.DecimalField == System.Decimal(0) + + ob.DecimalField = System.Decimal(1) + assert ob.DecimalField == System.Decimal(1) + + +def test_string_field(): + """Test string fields.""" + ob = FieldTest() + assert ob.StringField == "spam" + + ob.StringField = "eggs" + assert ob.StringField == "eggs" + + +def test_interface_field(): + """Test interface fields.""" + from Python.Test import Spam, ISpam + + ob = FieldTest() + + assert ISpam(ob.SpamField).GetValue() == "spam" + assert ob.SpamField.GetValue() == "spam" + + ob.SpamField = Spam("eggs") + assert ISpam(ob.SpamField).GetValue() == "eggs" + assert ob.SpamField.GetValue() == "eggs" + + +def test_object_field(): + """Test ob fields.""" + ob = FieldTest() + assert ob.ObjectField is None + + ob.ObjectField = System.String("spam") + assert ob.ObjectField == "spam" + + ob.ObjectField = System.Int32(1) + assert ob.ObjectField == 1 + + ob.ObjectField = None + assert ob.ObjectField is None + + +def test_enum_field(): + """Test enum fields.""" + from Python.Test import ShortEnum + + ob = FieldTest() + assert ob.EnumField == ShortEnum.Zero + + ob.EnumField = ShortEnum.One + assert ob.EnumField == ShortEnum.One + + +def test_nullable_field(): + """Test nullable fields.""" + ob = FieldTest() + + ob.StringField = None + assert ob.StringField is None + + ob.ObjectField = None + assert ob.ObjectField is None + + ob.SpamField = None + assert ob.SpamField is None + + # Primitive types and enums should not be set to null. + + with pytest.raises(TypeError): + FieldTest().Int32Field = None + + with pytest.raises(TypeError): + FieldTest().EnumField = None diff --git a/src/tests/test_generic.py b/src/tests/test_generic.py index 8d5ea4c4c..69cd4ee7f 100644 --- a/src/tests/test_generic.py +++ b/src/tests/test_generic.py @@ -1,767 +1,778 @@ # -*- coding: utf-8 -*- +"""Test CLR generics support.""" + import clr -import unittest import System +import pytest + +from ._compat import PY2, long, unicode, unichr, zip + + +def assert_generic_wrapper_by_type(ptype, value): + """Test Helper""" + from Python.Test import GenericWrapper + import System + + inst = GenericWrapper[ptype](value) + assert inst.value == value + + atype = System.Array[ptype] + items = atype([value, value, value]) + inst = GenericWrapper[atype](items) + assert len(inst.value) == 3 + assert inst.value[0] == value + assert inst.value[1] == value + + +def assert_generic_method_by_type(ptype, value, test_type=0): + """Test Helper""" + from Python.Test import GenericMethodTest, GenericStaticMethodTest + import System + + itype = GenericMethodTest[System.Type] + stype = GenericStaticMethodTest[System.Type] + + # Explicit selection (static method) + result = stype.Overloaded[ptype](value) + if test_type: + assert result.__class__ == value.__class__ + else: + assert result == value + + # Type inference (static method) + result = stype.Overloaded(value) + assert result == value + if test_type: + assert result.__class__ == value.__class__ + else: + assert result == value + + # Explicit selection (instance method) + result = itype().Overloaded[ptype](value) + assert result == value + if test_type: + assert result.__class__ == value.__class__ + else: + assert result == value + + # Type inference (instance method) + result = itype().Overloaded(value) + assert result == value + if test_type: + assert result.__class__ == value.__class__ + else: + assert result == value + + atype = System.Array[ptype] + items = atype([value, value, value]) + + # Explicit selection (static method) + result = stype.Overloaded[atype](items) + if test_type: + assert len(result) == 3 + assert result[0].__class__ == value.__class__ + assert result[1].__class__ == value.__class__ + else: + assert len(result) == 3 + assert result[0] == value + assert result[1] == value + + # Type inference (static method) + result = stype.Overloaded(items) + if test_type: + assert len(result) == 3 + assert result[0].__class__ == value.__class__ + assert result[1].__class__ == value.__class__ + else: + assert len(result) == 3 + assert result[0] == value + assert result[1] == value + + # Explicit selection (instance method) + result = itype().Overloaded[atype](items) + if test_type: + assert len(result) == 3 + assert result[0].__class__ == value.__class__ + assert result[1].__class__ == value.__class__ + else: + assert len(result) == 3 + assert result[0] == value + assert result[1] == value + + # Type inference (instance method) + result = itype().Overloaded(items) + if test_type: + assert len(result) == 3 + assert result[0].__class__ == value.__class__ + assert result[1].__class__ == value.__class__ + else: + assert len(result) == 3 + assert result[0] == value + assert result[1] == value + + +def test_python_type_aliasing(): + """Test python type alias support with generics.""" + from System.Collections.Generic import Dictionary + + dict_ = Dictionary[str, str]() + assert dict_.Count == 0 + dict_.Add("one", "one") + assert dict_["one"] == "one" + + dict_ = Dictionary[System.String, System.String]() + assert dict_.Count == 0 + dict_.Add("one", "one") + assert dict_["one"] == "one" + + dict_ = Dictionary[int, int]() + assert dict_.Count == 0 + dict_.Add(1, 1) + assert dict_[1] == 1 + + dict_ = Dictionary[System.Int32, System.Int32]() + assert dict_.Count == 0 + dict_.Add(1, 1) + assert dict_[1] == 1 + + dict_ = Dictionary[long, long]() + assert dict_.Count == 0 + dict_.Add(long(1), long(1)) + assert dict_[long(1)] == long(1) + + dict_ = Dictionary[System.Int64, System.Int64]() + assert dict_.Count == 0 + dict_.Add(long(1), long(1)) + assert dict_[long(1)] == long(1) + + dict_ = Dictionary[float, float]() + assert dict_.Count == 0 + dict_.Add(1.5, 1.5) + assert dict_[1.5] == 1.5 + + dict_ = Dictionary[System.Double, System.Double]() + assert dict_.Count == 0 + dict_.Add(1.5, 1.5) + assert dict_[1.5] == 1.5 + + dict_ = Dictionary[bool, bool]() + assert dict_.Count == 0 + dict_.Add(True, False) + assert dict_[True] is False + + dict_ = Dictionary[System.Boolean, System.Boolean]() + assert dict_.Count == 0 + dict_.Add(True, False) + assert dict_[True] is False + + +def test_generic_reference_type(): + """Test usage of generic reference type definitions.""" + from Python.Test import GenericTypeDefinition + + inst = GenericTypeDefinition[System.String, System.Int32]("one", 2) + assert inst.value1 == "one" + assert inst.value2 == 2 + + +def test_generic_value_type(): + """Test usage of generic value type definitions.""" + inst = System.Nullable[System.Int32](10) + assert inst.HasValue + assert inst.Value == 10 + + +def test_generic_interface(): + # TODO NotImplemented + pass + + +def test_generic_delegate(): + # TODO NotImplemented + pass + + +def test_open_generic_type(): + """Test behavior of reflected open constructed generic types.""" + from Python.Test import DerivedFromOpenGeneric + + open_generic_type = DerivedFromOpenGeneric.__bases__[0] + + with pytest.raises(TypeError): + _ = open_generic_type() + + with pytest.raises(TypeError): + _ = open_generic_type[System.String] + + +def test_derived_from_open_generic_type(): + """Test a generic type derived from an open generic type.""" + from Python.Test import DerivedFromOpenGeneric + + type_ = DerivedFromOpenGeneric[System.String, System.String] + inst = type_(1, 'two', 'three') + + assert inst.value1 == 1 + assert inst.value2 == 'two' + assert inst.value3 == 'three' + + +def test_generic_type_name_resolution(): + """Test the ability to disambiguate generic type names.""" + from Python.Test import GenericNameTest1, GenericNameTest2 + + # If both a non-generic and generic type exist for a name, the + # unadorned name always resolves to the non-generic type. + _class = GenericNameTest1 + assert _class().value == 0 + assert _class.value == 0 + + # If no non-generic type exists for a name, the unadorned name + # cannot be instantiated. It can only be used to bind a generic. + + with pytest.raises(TypeError): + _ = GenericNameTest2() + + _class = GenericNameTest2[int] + assert _class().value == 1 + assert _class.value == 1 + + _class = GenericNameTest2[int, int] + assert _class().value == 2 + assert _class.value == 2 + + +def test_generic_type_binding(): + """Test argument conversion / binding for generic methods.""" + from Python.Test import InterfaceTest, ISayHello1, ShortEnum + import System + + assert_generic_wrapper_by_type(System.Boolean, True) + 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.Int16, 32767) + assert_generic_wrapper_by_type(System.Int32, 2147483647) + assert_generic_wrapper_by_type(int, 2147483647) + assert_generic_wrapper_by_type(System.Int64, long(9223372036854775807)) + # Python 3 has no explicit long type, use System.Int64 instead + if PY2: + assert_generic_wrapper_by_type(long, long(9223372036854775807)) + assert_generic_wrapper_by_type(System.UInt16, 65000) + assert_generic_wrapper_by_type(System.UInt32, long(4294967295)) + assert_generic_wrapper_by_type(System.UInt64, long(18446744073709551615)) + assert_generic_wrapper_by_type(System.Single, 3.402823e38) + assert_generic_wrapper_by_type(System.Double, 1.7976931348623157e308) + assert_generic_wrapper_by_type(float, 1.7976931348623157e308) + assert_generic_wrapper_by_type(System.Decimal, System.Decimal.One) + assert_generic_wrapper_by_type(System.String, "test") + assert_generic_wrapper_by_type(unicode, "test") + assert_generic_wrapper_by_type(str, "test") + assert_generic_wrapper_by_type(ShortEnum, ShortEnum.Zero) + assert_generic_wrapper_by_type(System.Object, InterfaceTest()) + assert_generic_wrapper_by_type(InterfaceTest, InterfaceTest()) + assert_generic_wrapper_by_type(ISayHello1, InterfaceTest()) + + +def test_generic_method_binding(): + from Python.Test import GenericMethodTest, GenericStaticMethodTest + from System import InvalidOperationException + + # Can invoke a static member on a closed generic type. + value = GenericStaticMethodTest[str].Overloaded() + assert value == 1 + + with pytest.raises(InvalidOperationException): + # Cannot invoke a static member on an open type. + GenericStaticMethodTest.Overloaded() + + # Can invoke an instance member on a closed generic type. + value = GenericMethodTest[str]().Overloaded() + assert value == 1 + + with pytest.raises(TypeError): + # Cannot invoke an instance member on an open type, + # because the open type cannot be instantiated. + GenericMethodTest().Overloaded() + + +def test_generic_method_type_handling(): + """Test argument conversion / binding for generic methods.""" + from Python.Test import InterfaceTest, ISayHello1, ShortEnum + import System + + # FIXME: The value doesn't fit into Int64 and PythonNet doesn't + # recognize it as UInt64 for unknown reasons. + # assert_generic_method_by_type(System.UInt64, 18446744073709551615L) + assert_generic_method_by_type(System.Boolean, True) + 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.Int16, 32767) + assert_generic_method_by_type(System.Int32, 2147483647) + assert_generic_method_by_type(int, 2147483647) + # Python 3 has no explicit long type, use System.Int64 instead + if PY2: + assert_generic_method_by_type(System.Int64, long(9223372036854775807)) + assert_generic_method_by_type(long, long(9223372036854775807)) + assert_generic_method_by_type(System.UInt32, long(4294967295)) + assert_generic_method_by_type(System.Int64, long(1844674407370955161)) + assert_generic_method_by_type(System.UInt16, 65000) + assert_generic_method_by_type(System.Single, 3.402823e38) + assert_generic_method_by_type(System.Double, 1.7976931348623157e308) + assert_generic_method_by_type(float, 1.7976931348623157e308) + assert_generic_method_by_type(System.Decimal, System.Decimal.One) + assert_generic_method_by_type(System.String, "test") + assert_generic_method_by_type(unicode, "test") + assert_generic_method_by_type(str, "test") + assert_generic_method_by_type(ShortEnum, ShortEnum.Zero) + assert_generic_method_by_type(System.Object, InterfaceTest()) + assert_generic_method_by_type(InterfaceTest, InterfaceTest(), 1) + assert_generic_method_by_type(ISayHello1, InterfaceTest(), 1) + + +def test_correct_overload_selection(): + """Test correct overloading selection for common types.""" + 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, 3) == substr.Substring.__overloads__[Int32, Int32]( + 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]): + 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)) + if PY2 and atype is Int64: + value2 = long(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) + + +def test_generic_method_overload_selection(): + """Test explicit overload selection with generic methods.""" + from Python.Test import GenericMethodTest, GenericStaticMethodTest + + type = GenericStaticMethodTest[str] + inst = GenericMethodTest[str]() + + # public static int Overloaded() + value = type.Overloaded() + assert value == 1 + + # public int Overloaded() + value = inst.Overloaded() + assert value == 1 + + # public static T Overloaded(T arg) (inferred) + value = type.Overloaded("test") + assert value == "test" + + # public T Overloaded(T arg) (inferred) + value = inst.Overloaded("test") + assert value == "test" + + # public static T Overloaded(T arg) (explicit) + value = type.Overloaded[str]("test") + assert value == "test" + + # public T Overloaded(T arg) (explicit) + value = inst.Overloaded[str]("test") + assert value == "test" + + # public static Q Overloaded(Q arg) + value = type.Overloaded[float](2.2) + assert value == 2.2 + + # public Q Overloaded(Q arg) + value = inst.Overloaded[float](2.2) + assert value == 2.2 + + # public static Q Overloaded(Q arg) + value = type.Overloaded[bool](True) + assert value is True + + # public Q Overloaded(Q arg) + value = inst.Overloaded[bool](True) + assert value is True + + # public static U Overloaded(Q arg1, U arg2) + value = type.Overloaded[bool, str](True, "true") + assert value == "true" + + # public U Overloaded(Q arg1, U arg2) + value = inst.Overloaded[bool, str](True, "true") + assert value == "true" + + # public static U Overloaded(Q arg1, U arg2) + value = type.Overloaded[str, bool]("true", True) + assert value is True + + # public U Overloaded(Q arg1, U arg2) + value = inst.Overloaded[str, bool]("true", True) + assert value is True + + # public static string Overloaded(int arg1, int arg2, string arg3) + value = type.Overloaded[str](123, 456, "success") + assert value == "success" + + # public string Overloaded(int arg1, int arg2, string arg3) + value = inst.Overloaded[str](123, 456, "success") + assert value == "success" + + with pytest.raises(TypeError): + _ = type.Overloaded[str, bool, int]("true", True, 1) + + with pytest.raises(TypeError): + _ = inst.Overloaded[str, bool, int]("true", True, 1) + + +def test_method_overload_selection_with_generic_types(): + """Check method overload selection using generic types.""" + from Python.Test import ISayHello1, InterfaceTest, ShortEnum + from Python.Test import MethodTest, GenericWrapper + + inst = InterfaceTest() + + vtype = GenericWrapper[System.Boolean] + input_ = vtype(True) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value is True + + vtype = GenericWrapper[bool] + input_ = vtype(True) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value is True + + vtype = GenericWrapper[System.Byte] + input_ = vtype(255) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == 255 -from _compat import PY2, long, unicode, unichr, zip - - -class GenericTests(unittest.TestCase): - """Test CLR generics support.""" - - def _assert_generic_wrapper_by_type(self, ptype, value): - """Test Helper""" - from Python.Test import GenericWrapper - import System - - inst = GenericWrapper[ptype](value) - self.assertTrue(inst.value == value) - - atype = System.Array[ptype] - items = atype([value, value, value]) - inst = GenericWrapper[atype](items) - self.assertTrue(len(inst.value) == 3) - self.assertTrue(inst.value[0] == value) - self.assertTrue(inst.value[1] == value) - - def _assert_generic_method_by_type(self, ptype, value, test_type=0): - """Test Helper""" - from Python.Test import GenericMethodTest, GenericStaticMethodTest - import System - - itype = GenericMethodTest[System.Type] - stype = GenericStaticMethodTest[System.Type] - - # Explicit selection (static method) - result = stype.Overloaded[ptype](value) - if test_type: - self.assertTrue(result.__class__ == value.__class__) - else: - self.assertTrue(result == value) - - # Type inference (static method) - result = stype.Overloaded(value) - self.assertTrue(result == value) - if test_type: - self.assertTrue(result.__class__ == value.__class__) - else: - self.assertTrue(result == value) - - # Explicit selection (instance method) - result = itype().Overloaded[ptype](value) - self.assertTrue(result == value) - if test_type: - self.assertTrue(result.__class__ == value.__class__) - else: - self.assertTrue(result == value) - - # Type inference (instance method) - result = itype().Overloaded(value) - self.assertTrue(result == value) - if test_type: - self.assertTrue(result.__class__ == value.__class__) - else: - self.assertTrue(result == value) - - atype = System.Array[ptype] - items = atype([value, value, value]) - - # Explicit selection (static method) - result = stype.Overloaded[atype](items) - if test_type: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0].__class__ == value.__class__) - self.assertTrue(result[1].__class__ == value.__class__) - else: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0] == value) - self.assertTrue(result[1] == value) - - # Type inference (static method) - result = stype.Overloaded(items) - if test_type: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0].__class__ == value.__class__) - self.assertTrue(result[1].__class__ == value.__class__) - else: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0] == value) - self.assertTrue(result[1] == value) - - # Explicit selection (instance method) - result = itype().Overloaded[atype](items) - if test_type: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0].__class__ == value.__class__) - self.assertTrue(result[1].__class__ == value.__class__) - else: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0] == value) - self.assertTrue(result[1] == value) - - # Type inference (instance method) - result = itype().Overloaded(items) - if test_type: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0].__class__ == value.__class__) - self.assertTrue(result[1].__class__ == value.__class__) - else: - self.assertTrue(len(result) == 3) - self.assertTrue(result[0] == value) - self.assertTrue(result[1] == value) - - def test_python_type_aliasing(self): - """Test python type alias support with generics.""" - from System.Collections.Generic import Dictionary - - dict_ = Dictionary[str, str]() - self.assertEquals(dict_.Count, 0) - dict_.Add("one", "one") - self.assertTrue(dict_["one"] == "one") - - dict_ = Dictionary[System.String, System.String]() - self.assertEquals(dict_.Count, 0) - dict_.Add("one", "one") - self.assertTrue(dict_["one"] == "one") - - dict_ = Dictionary[int, int]() - self.assertEquals(dict_.Count, 0) - dict_.Add(1, 1) - self.assertTrue(dict_[1] == 1) - - dict_ = Dictionary[System.Int32, System.Int32]() - self.assertEquals(dict_.Count, 0) - dict_.Add(1, 1) - self.assertTrue(dict_[1] == 1) - - dict_ = Dictionary[long, long]() - self.assertEquals(dict_.Count, 0) - dict_.Add(long(1), long(1)) - self.assertTrue(dict_[long(1)] == long(1)) - - dict_ = Dictionary[System.Int64, System.Int64]() - self.assertEquals(dict_.Count, 0) - dict_.Add(long(1), long(1)) - self.assertTrue(dict_[long(1)] == long(1)) - - dict_ = Dictionary[float, float]() - self.assertEquals(dict_.Count, 0) - dict_.Add(1.5, 1.5) - self.assertTrue(dict_[1.5] == 1.5) - - dict_ = Dictionary[System.Double, System.Double]() - self.assertEquals(dict_.Count, 0) - dict_.Add(1.5, 1.5) - self.assertTrue(dict_[1.5] == 1.5) - - dict_ = Dictionary[bool, bool]() - self.assertEquals(dict_.Count, 0) - dict_.Add(True, False) - self.assertTrue(dict_[True] is False) - - dict_ = Dictionary[System.Boolean, System.Boolean]() - self.assertEquals(dict_.Count, 0) - dict_.Add(True, False) - self.assertTrue(dict_[True] is False) - - def test_generic_reference_type(self): - """Test usage of generic reference type definitions.""" - from Python.Test import GenericTypeDefinition - - inst = GenericTypeDefinition[System.String, System.Int32]("one", 2) - self.assertTrue(inst.value1 == "one") - self.assertTrue(inst.value2 == 2) - - def test_generic_value_type(self): - """Test usage of generic value type definitions.""" - inst = System.Nullable[System.Int32](10) - self.assertTrue(inst.HasValue) - self.assertTrue(inst.Value == 10) - - def test_generic_interface(self): - # TODO NotImplemented - pass - - def test_generic_delegate(self): - # TODO NotImplemented - pass - - def test_open_generic_type(self): - """Test behavior of reflected open constructed generic types.""" - from Python.Test import DerivedFromOpenGeneric - - open_generic_type = DerivedFromOpenGeneric.__bases__[0] - - with self.assertRaises(TypeError): - _ = open_generic_type() - - with self.assertRaises(TypeError): - _ = open_generic_type[System.String] - - def test_derived_from_open_generic_type(self): - """Test a generic type derived from an open generic type.""" - from Python.Test import DerivedFromOpenGeneric - - type_ = DerivedFromOpenGeneric[System.String, System.String] - inst = type_(1, 'two', 'three') - - self.assertTrue(inst.value1 == 1) - self.assertTrue(inst.value2 == 'two') - self.assertTrue(inst.value3 == 'three') - - def test_generic_type_name_resolution(self): - """Test the ability to disambiguate generic type names.""" - from Python.Test import GenericNameTest1, GenericNameTest2 - - # If both a non-generic and generic type exist for a name, the - # unadorned name always resolves to the non-generic type. - _class = GenericNameTest1 - self.assertTrue(_class().value == 0) - self.assertTrue(_class.value == 0) - - # If no non-generic type exists for a name, the unadorned name - # cannot be instantiated. It can only be used to bind a generic. - - with self.assertRaises(TypeError): - _ = GenericNameTest2() - - _class = GenericNameTest2[int] - self.assertTrue(_class().value == 1) - self.assertTrue(_class.value == 1) - - _class = GenericNameTest2[int, int] - self.assertTrue(_class().value == 2) - self.assertTrue(_class.value == 2) - - def test_generic_type_binding(self): - """Test argument conversion / binding for generic methods.""" - from Python.Test import InterfaceTest, ISayHello1, ShortEnum - import System - - self._assert_generic_wrapper_by_type(System.Boolean, True) - self._assert_generic_wrapper_by_type(bool, True) - self._assert_generic_wrapper_by_type(System.Byte, 255) - self._assert_generic_wrapper_by_type(System.SByte, 127) - self._assert_generic_wrapper_by_type(System.Char, u'A') - self._assert_generic_wrapper_by_type(System.Int16, 32767) - self._assert_generic_wrapper_by_type(System.Int32, 2147483647) - self._assert_generic_wrapper_by_type(int, 2147483647) - self._assert_generic_wrapper_by_type(System.Int64, long(9223372036854775807)) - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - self._assert_generic_wrapper_by_type(long, long(9223372036854775807)) - self._assert_generic_wrapper_by_type(System.UInt16, 65000) - self._assert_generic_wrapper_by_type(System.UInt32, long(4294967295)) - self._assert_generic_wrapper_by_type(System.UInt64, long(18446744073709551615)) - self._assert_generic_wrapper_by_type(System.Single, 3.402823e38) - self._assert_generic_wrapper_by_type(System.Double, 1.7976931348623157e308) - self._assert_generic_wrapper_by_type(float, 1.7976931348623157e308) - self._assert_generic_wrapper_by_type(System.Decimal, System.Decimal.One) - self._assert_generic_wrapper_by_type(System.String, "test") - self._assert_generic_wrapper_by_type(unicode, "test") - self._assert_generic_wrapper_by_type(str, "test") - self._assert_generic_wrapper_by_type(ShortEnum, ShortEnum.Zero) - self._assert_generic_wrapper_by_type(System.Object, InterfaceTest()) - self._assert_generic_wrapper_by_type(InterfaceTest, InterfaceTest()) - self._assert_generic_wrapper_by_type(ISayHello1, InterfaceTest()) - - def test_generic_method_binding(self): - from Python.Test import GenericMethodTest, GenericStaticMethodTest - from System import InvalidOperationException - - # Can invoke a static member on a closed generic type. - value = GenericStaticMethodTest[str].Overloaded() - self.assertTrue(value == 1) - - with self.assertRaises(InvalidOperationException): - # Cannot invoke a static member on an open type. - GenericStaticMethodTest.Overloaded() - - # Can invoke an instance member on a closed generic type. - value = GenericMethodTest[str]().Overloaded() - self.assertTrue(value == 1) - - with self.assertRaises(TypeError): - # Cannot invoke an instance member on an open type, - # because the open type cannot be instantiated. - GenericMethodTest().Overloaded() - - def test_generic_method_type_handling(self): - """Test argument conversion / binding for generic methods.""" - from Python.Test import InterfaceTest, ISayHello1, ShortEnum - import System - - # FIXME: The value doesn't fit into Int64 and PythonNet doesn't - # recognize it as UInt64 for unknown reasons. - # self._assert_generic_method_by_type(System.UInt64, 18446744073709551615L) - self._assert_generic_method_by_type(System.Boolean, True) - self._assert_generic_method_by_type(bool, True) - self._assert_generic_method_by_type(System.Byte, 255) - self._assert_generic_method_by_type(System.SByte, 127) - self._assert_generic_method_by_type(System.Char, u'A') - self._assert_generic_method_by_type(System.Int16, 32767) - self._assert_generic_method_by_type(System.Int32, 2147483647) - self._assert_generic_method_by_type(int, 2147483647) - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - self._assert_generic_method_by_type(System.Int64, long(9223372036854775807)) - self._assert_generic_method_by_type(long, long(9223372036854775807)) - self._assert_generic_method_by_type(System.UInt32, long(4294967295)) - self._assert_generic_method_by_type(System.Int64, long(1844674407370955161)) - self._assert_generic_method_by_type(System.UInt16, 65000) - self._assert_generic_method_by_type(System.Single, 3.402823e38) - self._assert_generic_method_by_type(System.Double, 1.7976931348623157e308) - self._assert_generic_method_by_type(float, 1.7976931348623157e308) - self._assert_generic_method_by_type(System.Decimal, System.Decimal.One) - self._assert_generic_method_by_type(System.String, "test") - self._assert_generic_method_by_type(unicode, "test") - self._assert_generic_method_by_type(str, "test") - self._assert_generic_method_by_type(ShortEnum, ShortEnum.Zero) - self._assert_generic_method_by_type(System.Object, InterfaceTest()) - self._assert_generic_method_by_type(InterfaceTest, InterfaceTest(), 1) - self._assert_generic_method_by_type(ISayHello1, InterfaceTest(), 1) - - def test_correct_overload_selection(self): - """Test correct overloading selection for common types.""" - from System import (String, Double, Single, - Int16, Int32, Int64) - from System import Math - - substr = String("substring") - self.assertTrue(substr.Substring(2) == substr.Substring.__overloads__[Int32]( - Int32(2))) - self.assertTrue(substr.Substring(2, 3) == substr.Substring.__overloads__[Int32, Int32]( - 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]): - self.assertTrue(Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype(value1))) - self.assertTrue(Math.Abs(value1) == Math.Abs.__overloads__[atype](atype(value1))) - self.assertTrue( - Math.Max(atype(value1), - atype(value2)) == Math.Max.__overloads__[atype, atype]( - atype(value1), atype(value2))) - if PY2 and atype is Int64: - value2 = long(value2) - self.assertTrue( - 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) - - def test_generic_method_overload_selection(self): - """Test explicit overload selection with generic methods.""" - from Python.Test import GenericMethodTest, GenericStaticMethodTest - - type = GenericStaticMethodTest[str] - inst = GenericMethodTest[str]() - - # public static int Overloaded() - value = type.Overloaded() - self.assertTrue(value == 1) - - # public int Overloaded() - value = inst.Overloaded() - self.assertTrue(value == 1) - - # public static T Overloaded(T arg) (inferred) - value = type.Overloaded("test") - self.assertTrue(value == "test") - - # public T Overloaded(T arg) (inferred) - value = inst.Overloaded("test") - self.assertTrue(value == "test") - - # public static T Overloaded(T arg) (explicit) - value = type.Overloaded[str]("test") - self.assertTrue(value == "test") - - # public T Overloaded(T arg) (explicit) - value = inst.Overloaded[str]("test") - self.assertTrue(value == "test") - - # public static Q Overloaded(Q arg) - value = type.Overloaded[float](2.2) - self.assertTrue(value == 2.2) - - # public Q Overloaded(Q arg) - value = inst.Overloaded[float](2.2) - self.assertTrue(value == 2.2) - - # public static Q Overloaded(Q arg) - value = type.Overloaded[bool](True) - self.assertTrue(value is True) - - # public Q Overloaded(Q arg) - value = inst.Overloaded[bool](True) - self.assertTrue(value is True) - - # public static U Overloaded(Q arg1, U arg2) - value = type.Overloaded[bool, str](True, "true") - self.assertTrue(value == "true") - - # public U Overloaded(Q arg1, U arg2) - value = inst.Overloaded[bool, str](True, "true") - self.assertTrue(value == "true") - - # public static U Overloaded(Q arg1, U arg2) - value = type.Overloaded[str, bool]("true", True) - self.assertTrue(value is True) - - # public U Overloaded(Q arg1, U arg2) - value = inst.Overloaded[str, bool]("true", True) - self.assertTrue(value is True) - - # public static string Overloaded(int arg1, int arg2, string arg3) - value = type.Overloaded[str](123, 456, "success") - self.assertTrue(value == "success") - - # public string Overloaded(int arg1, int arg2, string arg3) - value = inst.Overloaded[str](123, 456, "success") - self.assertTrue(value == "success") - - with self.assertRaises(TypeError): - _ = type.Overloaded[str, bool, int]("true", True, 1) - - with self.assertRaises(TypeError): - _ = inst.Overloaded[str, bool, int]("true", True, 1) - - def test_method_overload_selection_with_generic_types(self): - """Check method overload selection using generic types.""" - from Python.Test import ISayHello1, InterfaceTest, ShortEnum - from Python.Test import MethodTest, GenericWrapper - - inst = InterfaceTest() - - vtype = GenericWrapper[System.Boolean] - input_ = vtype(True) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value is True) - - vtype = GenericWrapper[bool] - input_ = vtype(True) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value is True) - - vtype = GenericWrapper[System.Byte] - input_ = vtype(255) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == 255) - - vtype = GenericWrapper[System.SByte] - input_ = vtype(127) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == 127) - - vtype = GenericWrapper[System.Char] - input_ = vtype(u'A') - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == u'A') - - vtype = GenericWrapper[System.Char] - input_ = vtype(65535) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == unichr(65535)) - - vtype = GenericWrapper[System.Int16] - input_ = vtype(32767) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == 32767) - - vtype = GenericWrapper[System.Int32] - input_ = vtype(2147483647) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == 2147483647) - - vtype = GenericWrapper[int] - input_ = vtype(2147483647) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == 2147483647) - - vtype = GenericWrapper[System.Int64] + vtype = GenericWrapper[System.SByte] + input_ = vtype(127) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == 127 + + vtype = GenericWrapper[System.Char] + input_ = vtype(u'A') + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == u'A' + + vtype = GenericWrapper[System.Char] + input_ = vtype(65535) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == unichr(65535) + + vtype = GenericWrapper[System.Int16] + input_ = vtype(32767) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == 32767 + + vtype = GenericWrapper[System.Int32] + input_ = vtype(2147483647) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == 2147483647 + + vtype = GenericWrapper[int] + input_ = vtype(2147483647) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == 2147483647 + + vtype = GenericWrapper[System.Int64] + input_ = vtype(long(9223372036854775807)) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == long(9223372036854775807) + + # Python 3 has no explicit long type, use System.Int64 instead + if PY2: + vtype = GenericWrapper[long] input_ = vtype(long(9223372036854775807)) value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == long(9223372036854775807)) - - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - vtype = GenericWrapper[long] - input_ = vtype(long(9223372036854775807)) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == long(9223372036854775807)) - - vtype = GenericWrapper[System.UInt16] - input_ = vtype(65000) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == 65000) - - vtype = GenericWrapper[System.UInt32] - input_ = vtype(long(4294967295)) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == long(4294967295)) - - vtype = GenericWrapper[System.UInt64] - input_ = vtype(long(18446744073709551615)) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == long(18446744073709551615)) - - vtype = GenericWrapper[System.Single] - input_ = vtype(3.402823e38) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == 3.402823e38) - - vtype = GenericWrapper[System.Double] - input_ = vtype(1.7976931348623157e308) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == 1.7976931348623157e308) - - vtype = GenericWrapper[float] - input_ = vtype(1.7976931348623157e308) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == 1.7976931348623157e308) - - vtype = GenericWrapper[System.Decimal] - input_ = vtype(System.Decimal.One) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == System.Decimal.One) - - vtype = GenericWrapper[System.String] - input_ = vtype("spam") - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == "spam") - - vtype = GenericWrapper[str] - input_ = vtype("spam") - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == "spam") - - vtype = GenericWrapper[ShortEnum] - input_ = vtype(ShortEnum.Zero) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value == ShortEnum.Zero) - - vtype = GenericWrapper[System.Object] - input_ = vtype(inst) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value.__class__ == inst.__class__) - - vtype = GenericWrapper[InterfaceTest] - input_ = vtype(inst) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value.__class__ == inst.__class__) - - vtype = GenericWrapper[ISayHello1] - input_ = vtype(inst) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value.value.__class__ == inst.__class__) - - vtype = System.Array[GenericWrapper[int]] - input_ = vtype([GenericWrapper[int](0), GenericWrapper[int](1)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 0) - self.assertTrue(value[1].value == 1) - - def test_overload_selection_with_arrays_of_generic_types(self): - """Check overload selection using arrays of generic types.""" - from Python.Test import ISayHello1, InterfaceTest, ShortEnum - from Python.Test import MethodTest, GenericWrapper - - inst = InterfaceTest() - - gtype = GenericWrapper[System.Boolean] - vtype = System.Array[gtype] - input_ = vtype([gtype(True), gtype(True)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value is True) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[bool] - vtype = System.Array[gtype] - input_ = vtype([gtype(True), gtype(True)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value is True) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Byte] - vtype = System.Array[gtype] - input_ = vtype([gtype(255), gtype(255)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 255) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.SByte] - vtype = System.Array[gtype] - input_ = vtype([gtype(127), gtype(127)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 127) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Char] - vtype = System.Array[gtype] - input_ = vtype([gtype(u'A'), gtype(u'A')]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == u'A') - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Char] - vtype = System.Array[gtype] - input_ = vtype([gtype(65535), gtype(65535)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == unichr(65535)) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Int16] - vtype = System.Array[gtype] - input_ = vtype([gtype(32767), gtype(32767)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 32767) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Int32] - vtype = System.Array[gtype] - input_ = vtype([gtype(2147483647), gtype(2147483647)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 2147483647) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[int] - vtype = System.Array[gtype] - input_ = vtype([gtype(2147483647), gtype(2147483647)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 2147483647) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Int64] + assert value.value == long(9223372036854775807) + + vtype = GenericWrapper[System.UInt16] + input_ = vtype(65000) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == 65000 + + vtype = GenericWrapper[System.UInt32] + input_ = vtype(long(4294967295)) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == long(4294967295) + + vtype = GenericWrapper[System.UInt64] + input_ = vtype(long(18446744073709551615)) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == long(18446744073709551615) + + vtype = GenericWrapper[System.Single] + input_ = vtype(3.402823e38) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == 3.402823e38 + + vtype = GenericWrapper[System.Double] + input_ = vtype(1.7976931348623157e308) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == 1.7976931348623157e308 + + vtype = GenericWrapper[float] + input_ = vtype(1.7976931348623157e308) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == 1.7976931348623157e308 + + vtype = GenericWrapper[System.Decimal] + input_ = vtype(System.Decimal.One) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == System.Decimal.One + + vtype = GenericWrapper[System.String] + input_ = vtype("spam") + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == "spam" + + vtype = GenericWrapper[str] + input_ = vtype("spam") + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == "spam" + + vtype = GenericWrapper[ShortEnum] + input_ = vtype(ShortEnum.Zero) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value == ShortEnum.Zero + + vtype = GenericWrapper[System.Object] + input_ = vtype(inst) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value.__class__ == inst.__class__ + + vtype = GenericWrapper[InterfaceTest] + input_ = vtype(inst) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value.__class__ == inst.__class__ + + vtype = GenericWrapper[ISayHello1] + input_ = vtype(inst) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value.value.__class__ == inst.__class__ + + vtype = System.Array[GenericWrapper[int]] + input_ = vtype([GenericWrapper[int](0), GenericWrapper[int](1)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == 0 + assert value[1].value == 1 + + +def test_overload_selection_with_arrays_of_generic_types(): + """Check overload selection using arrays of generic types.""" + from Python.Test import ISayHello1, InterfaceTest, ShortEnum + from Python.Test import MethodTest, GenericWrapper + + inst = InterfaceTest() + + gtype = GenericWrapper[System.Boolean] + vtype = System.Array[gtype] + input_ = vtype([gtype(True), gtype(True)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value is True + assert value.Length == 2 + + gtype = GenericWrapper[bool] + vtype = System.Array[gtype] + input_ = vtype([gtype(True), gtype(True)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value is True + assert value.Length == 2 + + gtype = GenericWrapper[System.Byte] + vtype = System.Array[gtype] + input_ = vtype([gtype(255), gtype(255)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == 255 + assert value.Length == 2 + + gtype = GenericWrapper[System.SByte] + vtype = System.Array[gtype] + input_ = vtype([gtype(127), gtype(127)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == 127 + assert value.Length == 2 + + gtype = GenericWrapper[System.Char] + vtype = System.Array[gtype] + input_ = vtype([gtype(u'A'), gtype(u'A')]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == u'A' + assert value.Length == 2 + + gtype = GenericWrapper[System.Char] + vtype = System.Array[gtype] + input_ = vtype([gtype(65535), gtype(65535)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == unichr(65535) + assert value.Length == 2 + + gtype = GenericWrapper[System.Int16] + vtype = System.Array[gtype] + input_ = vtype([gtype(32767), gtype(32767)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == 32767 + assert value.Length == 2 + + gtype = GenericWrapper[System.Int32] + vtype = System.Array[gtype] + input_ = vtype([gtype(2147483647), gtype(2147483647)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == 2147483647 + assert value.Length == 2 + + gtype = GenericWrapper[int] + vtype = System.Array[gtype] + input_ = vtype([gtype(2147483647), gtype(2147483647)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == 2147483647 + assert value.Length == 2 + + gtype = GenericWrapper[System.Int64] + vtype = System.Array[gtype] + input_ = vtype([gtype(long(9223372036854775807)), + gtype(long(9223372036854775807))]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == long(9223372036854775807) + assert value.Length == 2 + + # Python 3 has no explicit long type, use System.Int64 instead + if PY2: + gtype = GenericWrapper[long] vtype = System.Array[gtype] input_ = vtype([gtype(long(9223372036854775807)), - gtype(long(9223372036854775807))]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == long(9223372036854775807)) - self.assertTrue(value.Length == 2) - - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - gtype = GenericWrapper[long] - vtype = System.Array[gtype] - input_ = vtype([gtype(long(9223372036854775807)), - gtype(long(9223372036854775807))]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == long(9223372036854775807)) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.UInt16] - vtype = System.Array[gtype] - input_ = vtype([gtype(65000), gtype(65000)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 65000) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.UInt32] - vtype = System.Array[gtype] - input_ = vtype([gtype(long(4294967295)), gtype(long(4294967295))]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == long(4294967295)) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.UInt64] - vtype = System.Array[gtype] - input_ = vtype([gtype(long(18446744073709551615)), - gtype(long(18446744073709551615))]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == long(18446744073709551615)) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Single] - vtype = System.Array[gtype] - input_ = vtype([gtype(3.402823e38), gtype(3.402823e38)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 3.402823e38) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Double] - vtype = System.Array[gtype] - input_ = vtype([gtype(1.7976931348623157e308), - gtype(1.7976931348623157e308)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 1.7976931348623157e308) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[float] - vtype = System.Array[gtype] - input_ = vtype([gtype(1.7976931348623157e308), - gtype(1.7976931348623157e308)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == 1.7976931348623157e308) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Decimal] - vtype = System.Array[gtype] - input_ = vtype([gtype(System.Decimal.One), - gtype(System.Decimal.One)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == System.Decimal.One) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.String] - vtype = System.Array[gtype] - input_ = vtype([gtype("spam"), gtype("spam")]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == "spam") - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[str] - vtype = System.Array[gtype] - input_ = vtype([gtype("spam"), gtype("spam")]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == "spam") - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[ShortEnum] - vtype = System.Array[gtype] - input_ = vtype([gtype(ShortEnum.Zero), gtype(ShortEnum.Zero)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value == ShortEnum.Zero) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[System.Object] - vtype = System.Array[gtype] - input_ = vtype([gtype(inst), gtype(inst)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value.__class__ == inst.__class__) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[InterfaceTest] - vtype = System.Array[gtype] - input_ = vtype([gtype(inst), gtype(inst)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value.__class__ == inst.__class__) - self.assertTrue(value.Length == 2) - - gtype = GenericWrapper[ISayHello1] - vtype = System.Array[gtype] - input_ = vtype([gtype(inst), gtype(inst)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].value.__class__ == inst.__class__) - self.assertTrue(value.Length == 2) - - def test_generic_overload_selection_magic_name_only(self): - """Test using only __overloads__ to select on type & sig""" - # TODO NotImplemented - pass - - def test_nested_generic_class(self): - """Check nested generic classes.""" - # TODO NotImplemented - pass - - -def test_suite(): - return unittest.makeSuite(GenericTests) + gtype(long(9223372036854775807))]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == long(9223372036854775807) + assert value.Length == 2 + + gtype = GenericWrapper[System.UInt16] + vtype = System.Array[gtype] + input_ = vtype([gtype(65000), gtype(65000)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == 65000 + assert value.Length == 2 + + gtype = GenericWrapper[System.UInt32] + vtype = System.Array[gtype] + input_ = vtype([gtype(long(4294967295)), gtype(long(4294967295))]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == long(4294967295) + assert value.Length == 2 + + gtype = GenericWrapper[System.UInt64] + vtype = System.Array[gtype] + input_ = vtype([gtype(long(18446744073709551615)), + gtype(long(18446744073709551615))]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == long(18446744073709551615) + assert value.Length == 2 + + gtype = GenericWrapper[System.Single] + vtype = System.Array[gtype] + input_ = vtype([gtype(3.402823e38), gtype(3.402823e38)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == 3.402823e38 + assert value.Length == 2 + + gtype = GenericWrapper[System.Double] + vtype = System.Array[gtype] + 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)]) + 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)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == System.Decimal.One + assert value.Length == 2 + + gtype = GenericWrapper[System.String] + vtype = System.Array[gtype] + input_ = vtype([gtype("spam"), gtype("spam")]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == "spam" + assert value.Length == 2 + + gtype = GenericWrapper[str] + vtype = System.Array[gtype] + input_ = vtype([gtype("spam"), gtype("spam")]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == "spam" + assert value.Length == 2 + + gtype = GenericWrapper[ShortEnum] + vtype = System.Array[gtype] + input_ = vtype([gtype(ShortEnum.Zero), gtype(ShortEnum.Zero)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value == ShortEnum.Zero + assert value.Length == 2 + + gtype = GenericWrapper[System.Object] + vtype = System.Array[gtype] + input_ = vtype([gtype(inst), gtype(inst)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value.__class__ == inst.__class__ + assert value.Length == 2 + + gtype = GenericWrapper[InterfaceTest] + vtype = System.Array[gtype] + input_ = vtype([gtype(inst), gtype(inst)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value.__class__ == inst.__class__ + assert value.Length == 2 + + gtype = GenericWrapper[ISayHello1] + vtype = System.Array[gtype] + input_ = vtype([gtype(inst), gtype(inst)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].value.__class__ == inst.__class__ + assert value.Length == 2 + + +def test_generic_overload_selection_magic_name_only(): + """Test using only __overloads__ to select on type & sig""" + # TODO NotImplemented + pass + + +def test_nested_generic_class(): + """Check nested generic classes.""" + # TODO NotImplemented + pass diff --git a/src/tests/test_import.py b/src/tests/test_import.py new file mode 100644 index 000000000..42cafc4df --- /dev/null +++ b/src/tests/test_import.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- + +"""Test the import statement.""" + +import pytest + + +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 diff --git a/src/tests/test_indexer.py b/src/tests/test_indexer.py index 422f7282e..6f18550d9 100644 --- a/src/tests/test_indexer.py +++ b/src/tests/test_indexer.py @@ -1,577 +1,599 @@ # -*- coding: utf-8 -*- -import unittest +"""Test support for indexer properties.""" import Python.Test as Test +import pytest -from _compat import long, unichr +from ._compat import long, unichr -class IndexerTests(unittest.TestCase): - """Test support for indexer properties.""" +def test_public_indexer(): + """Test public indexers.""" + ob = Test.PublicIndexerTest() - def test_public_indexer(self): - """Test public indexers.""" - ob = Test.PublicIndexerTest() + ob[0] = "zero" + assert ob[0] == "zero" - ob[0] = "zero" - self.assertTrue(ob[0] == "zero") + ob[1] = "one" + assert ob[1] == "one" + + assert ob[10] is None + + +def test_protected_indexer(): + """Test protected indexers.""" + ob = Test.ProtectedIndexerTest() + + ob[0] = "zero" + assert ob[0] == "zero" + + ob[1] = "one" + assert ob[1] == "one" - ob[1] = "one" - self.assertTrue(ob[1] == "one") + assert ob[10] is None - self.assertTrue(ob[10] is None) - def test_protected_indexer(self): - """Test protected indexers.""" - ob = Test.ProtectedIndexerTest() +def test_internal_indexer(): + """Test internal indexers.""" + ob = Test.InternalIndexerTest() + with pytest.raises(TypeError): ob[0] = "zero" - self.assertTrue(ob[0] == "zero") - ob[1] = "one" - self.assertTrue(ob[1] == "one") + with pytest.raises(TypeError): + Test.InternalIndexerTest.__getitem__(ob, 0) - self.assertTrue(ob[10] is None) + with pytest.raises(TypeError): + ob.__getitem__(0) - def test_internal_indexer(self): - """Test internal indexers.""" - ob = Test.InternalIndexerTest() - with self.assertRaises(TypeError): - ob[0] = "zero" +def test_private_indexer(): + """Test private indexers.""" + ob = Test.PrivateIndexerTest() + + with pytest.raises(TypeError): + ob[0] = "zero" + + with pytest.raises(TypeError): + Test.PrivateIndexerTest.__getitem__(ob, 0) + + with pytest.raises(TypeError): + ob.__getitem__(0) - with self.assertRaises(TypeError): - Test.InternalIndexerTest.__getitem__(ob, 0) - with self.assertRaises(TypeError): - ob.__getitem__(0) +def test_boolean_indexer(): + """Test boolean indexers.""" + ob = Test.BooleanIndexerTest() - def test_private_indexer(self): - """Test private indexers.""" - ob = Test.PrivateIndexerTest() + assert ob[True] is None + assert ob[1] is None - with self.assertRaises(TypeError): - ob[0] = "zero" + ob[0] = "false" + assert ob[0] == "false" - with self.assertRaises(TypeError): - Test.PrivateIndexerTest.__getitem__(ob, 0) + ob[1] = "true" + assert ob[1] == "true" - with self.assertRaises(TypeError): - ob.__getitem__(0) + ob[False] = "false" + assert ob[False] == "false" - def test_boolean_indexer(self): - """Test boolean indexers.""" - ob = Test.BooleanIndexerTest() + ob[True] = "true" + assert ob[True] == "true" - self.assertTrue(ob[True] is None) - self.assertTrue(ob[1] is None) - ob[0] = "false" - self.assertTrue(ob[0] == "false") +def test_byte_indexer(): + """Test byte indexers.""" + ob = Test.ByteIndexerTest() + max_ = 255 + min_ = 0 - ob[1] = "true" - self.assertTrue(ob[1] == "true") + assert ob[max_] is None - ob[False] = "false" - self.assertTrue(ob[False] == "false") + ob[max_] = str(max_) + assert ob[max_] == str(max_) - ob[True] = "true" - self.assertTrue(ob[True] == "true") + ob[min_] = str(min_) + assert ob[min_] == str(min_) - def test_byte_indexer(self): - """Test byte indexers.""" + with pytest.raises(TypeError): ob = Test.ByteIndexerTest() - max_ = 255 - min_ = 0 + ob["wrong"] + + with pytest.raises(TypeError): + ob = Test.ByteIndexerTest() + ob["wrong"] = "wrong" - self.assertTrue(ob[max_] is None) - ob[max_] = str(max_) - self.assertTrue(ob[max_] == str(max_)) +def test_sbyte_indexer(): + """Test sbyte indexers.""" + ob = Test.SByteIndexerTest() + max_ = 127 + min_ = -128 - ob[min_] = str(min_) - self.assertTrue(ob[min_] == str(min_)) + assert ob[max_] is None - with self.assertRaises(TypeError): - ob = Test.ByteIndexerTest() - ob["wrong"] + ob[max_] = str(max_) + assert ob[max_] == str(max_) - with self.assertRaises(TypeError): - ob = Test.ByteIndexerTest() - ob["wrong"] = "wrong" + ob[min_] = str(min_) + assert ob[min_] == str(min_) - def test_sbyte_indexer(self): - """Test sbyte indexers.""" + with pytest.raises(TypeError): ob = Test.SByteIndexerTest() - max_ = 127 - min_ = -128 + ob["wrong"] - self.assertTrue(ob[max_] is None) + with pytest.raises(TypeError): + ob = Test.SByteIndexerTest() + ob["wrong"] = "wrong" - ob[max_] = str(max_) - self.assertTrue(ob[max_] == str(max_)) - ob[min_] = str(min_) - self.assertTrue(ob[min_] == str(min_)) +def test_char_indexer(): + """Test char indexers.""" + ob = Test.CharIndexerTest() + max_ = unichr(65535) + min_ = unichr(0) - with self.assertRaises(TypeError): - ob = Test.SByteIndexerTest() - ob["wrong"] + assert ob[max_] is None - with self.assertRaises(TypeError): - ob = Test.SByteIndexerTest() - ob["wrong"] = "wrong" + ob[max_] = "max_" + assert ob[max_] == "max_" - def test_char_indexer(self): - """Test char indexers.""" + ob[min_] = "min_" + assert ob[min_] == "min_" + + with pytest.raises(TypeError): + ob = Test.CharIndexerTest() + ob["wrong"] + + with pytest.raises(TypeError): ob = Test.CharIndexerTest() - max_ = unichr(65535) - min_ = unichr(0) + ob["wrong"] = "wrong" - self.assertTrue(ob[max_] is None) - ob[max_] = "max_" - self.assertTrue(ob[max_] == "max_") +def test_int16_indexer(): + """Test Int16 indexers.""" + ob = Test.Int16IndexerTest() + max_ = 32767 + min_ = -32768 - ob[min_] = "min_" - self.assertTrue(ob[min_] == "min_") + assert ob[max_] is None - with self.assertRaises(TypeError): - ob = Test.CharIndexerTest() - ob["wrong"] + ob[max_] = str(max_) + assert ob[max_] == str(max_) - with self.assertRaises(TypeError): - ob = Test.CharIndexerTest() - ob["wrong"] = "wrong" + ob[min_] = str(min_) + assert ob[min_] == str(min_) - def test_int16_indexer(self): - """Test Int16 indexers.""" + with pytest.raises(TypeError): ob = Test.Int16IndexerTest() - max_ = 32767 - min_ = -32768 + ob["wrong"] - self.assertTrue(ob[max_] is None) + with pytest.raises(TypeError): + ob = Test.Int16IndexerTest() + ob["wrong"] = "wrong" - ob[max_] = str(max_) - self.assertTrue(ob[max_] == str(max_)) - ob[min_] = str(min_) - self.assertTrue(ob[min_] == str(min_)) +def test_int32_indexer(): + """Test Int32 indexers.""" + ob = Test.Int32IndexerTest() + max_ = 2147483647 + min_ = -2147483648 - with self.assertRaises(TypeError): - ob = Test.Int16IndexerTest() - ob["wrong"] + assert ob[max_] is None - with self.assertRaises(TypeError): - ob = Test.Int16IndexerTest() - ob["wrong"] = "wrong" + ob[max_] = str(max_) + assert ob[max_] == str(max_) + + ob[min_] = str(min_) + assert ob[min_] == str(min_) + + with pytest.raises(TypeError): + ob = Test.Int32IndexerTest() + ob["wrong"] - def test_int32_indexer(self): - """Test Int32 indexers.""" + with pytest.raises(TypeError): ob = Test.Int32IndexerTest() - max_ = 2147483647 - min_ = -2147483648 + ob["wrong"] = "wrong" - self.assertTrue(ob[max_] is None) - ob[max_] = str(max_) - self.assertTrue(ob[max_] == str(max_)) +def test_int64_indexer(): + """Test Int64 indexers.""" + ob = Test.Int64IndexerTest() + max_ = long(9223372036854775807) + min_ = long(-9223372036854775808) - ob[min_] = str(min_) - self.assertTrue(ob[min_] == str(min_)) + assert ob[max_] is None - with self.assertRaises(TypeError): - ob = Test.Int32IndexerTest() - ob["wrong"] + ob[max_] = str(max_) + assert ob[max_] == str(max_) - with self.assertRaises(TypeError): - ob = Test.Int32IndexerTest() - ob["wrong"] = "wrong" + ob[min_] = str(min_) + assert ob[min_] == str(min_) - def test_int64_indexer(self): - """Test Int64 indexers.""" + with pytest.raises(TypeError): ob = Test.Int64IndexerTest() - max_ = long(9223372036854775807) - min_ = long(-9223372036854775808) + ob["wrong"] - self.assertTrue(ob[max_] is None) + with pytest.raises(TypeError): + ob = Test.Int64IndexerTest() + ob["wrong"] = "wrong" + + +def test_uint16_indexer(): + """Test UInt16 indexers.""" + ob = Test.UInt16IndexerTest() + max_ = 65535 + min_ = 0 - ob[max_] = str(max_) - self.assertTrue(ob[max_] == str(max_)) + assert ob[max_] is None - ob[min_] = str(min_) - self.assertTrue(ob[min_] == str(min_)) + ob[max_] = str(max_) + assert ob[max_] == str(max_) - with self.assertRaises(TypeError): - ob = Test.Int64IndexerTest() - ob["wrong"] + ob[min_] = str(min_) + assert ob[min_] == str(min_) - with self.assertRaises(TypeError): - ob = Test.Int64IndexerTest() - ob["wrong"] = "wrong" + with pytest.raises(TypeError): + ob = Test.UInt16IndexerTest() + ob["wrong"] - def test_uint16_indexer(self): - """Test UInt16 indexers.""" + with pytest.raises(TypeError): ob = Test.UInt16IndexerTest() - max_ = 65535 - min_ = 0 + ob["wrong"] = "wrong" + - self.assertTrue(ob[max_] is None) +def test_uint32_indexer(): + """Test UInt32 indexers.""" + ob = Test.UInt32IndexerTest() + max_ = long(4294967295) + min_ = 0 - ob[max_] = str(max_) - self.assertTrue(ob[max_] == str(max_)) + assert ob[max_] is None - ob[min_] = str(min_) - self.assertTrue(ob[min_] == str(min_)) + ob[max_] = str(max_) + assert ob[max_] == str(max_) - with self.assertRaises(TypeError): - ob = Test.UInt16IndexerTest() - ob["wrong"] + ob[min_] = str(min_) + assert ob[min_] == str(min_) - with self.assertRaises(TypeError): - ob = Test.UInt16IndexerTest() - ob["wrong"] = "wrong" + with pytest.raises(TypeError): + ob = Test.UInt32IndexerTest() + ob["wrong"] - def test_uint32_indexer(self): - """Test UInt32 indexers.""" + with pytest.raises(TypeError): ob = Test.UInt32IndexerTest() - max_ = long(4294967295) - min_ = 0 + ob["wrong"] = "wrong" - self.assertTrue(ob[max_] is None) - ob[max_] = str(max_) - self.assertTrue(ob[max_] == str(max_)) +def test_uint64_indexer(): + """Test UInt64 indexers.""" + ob = Test.UInt64IndexerTest() + max_ = long(18446744073709551615) + min_ = 0 - ob[min_] = str(min_) - self.assertTrue(ob[min_] == str(min_)) + assert ob[max_] is None - with self.assertRaises(TypeError): - ob = Test.UInt32IndexerTest() - ob["wrong"] + ob[max_] = str(max_) + assert ob[max_] == str(max_) - with self.assertRaises(TypeError): - ob = Test.UInt32IndexerTest() - ob["wrong"] = "wrong" + ob[min_] = str(min_) + assert ob[min_] == str(min_) - def test_uint64_indexer(self): - """Test UInt64 indexers.""" + with pytest.raises(TypeError): ob = Test.UInt64IndexerTest() - max_ = long(18446744073709551615) - min_ = 0 + ob["wrong"] + + with pytest.raises(TypeError): + ob = Test.UInt64IndexerTest() + ob["wrong"] = "wrong" - self.assertTrue(ob[max_] is None) - ob[max_] = str(max_) - self.assertTrue(ob[max_] == str(max_)) +def test_single_indexer(): + """Test Single indexers.""" + ob = Test.SingleIndexerTest() + max_ = 3.402823e38 + min_ = -3.402823e38 - ob[min_] = str(min_) - self.assertTrue(ob[min_] == str(min_)) + assert ob[max_] is None - with self.assertRaises(TypeError): - ob = Test.UInt64IndexerTest() - ob["wrong"] + ob[max_] = "max_" + assert ob[max_] == "max_" - with self.assertRaises(TypeError): - ob = Test.UInt64IndexerTest() - ob["wrong"] = "wrong" + ob[min_] = "min_" + assert ob[min_] == "min_" + + with pytest.raises(TypeError): + ob = Test.SingleIndexerTest() + ob["wrong"] - def test_single_indexer(self): - """Test Single indexers.""" + with pytest.raises(TypeError): ob = Test.SingleIndexerTest() - max_ = 3.402823e38 - min_ = -3.402823e38 + ob["wrong"] = "wrong" - self.assertTrue(ob[max_] is None) - ob[max_] = "max_" - self.assertTrue(ob[max_] == "max_") +def test_double_indexer(): + """Test Double indexers.""" + ob = Test.DoubleIndexerTest() + max_ = 1.7976931348623157e308 + min_ = -1.7976931348623157e308 - ob[min_] = "min_" - self.assertTrue(ob[min_] == "min_") + assert ob[max_] is None - with self.assertRaises(TypeError): - ob = Test.SingleIndexerTest() - ob["wrong"] + ob[max_] = "max_" + assert ob[max_] == "max_" - with self.assertRaises(TypeError): - ob = Test.SingleIndexerTest() - ob["wrong"] = "wrong" + ob[min_] = "min_" + assert ob[min_] == "min_" - def test_double_indexer(self): - """Test Double indexers.""" + with pytest.raises(TypeError): ob = Test.DoubleIndexerTest() - max_ = 1.7976931348623157e308 - min_ = -1.7976931348623157e308 + ob["wrong"] + + with pytest.raises(TypeError): + ob = Test.DoubleIndexerTest() + ob["wrong"] = "wrong" + - self.assertTrue(ob[max_] is None) +def test_decimal_indexer(): + """Test Decimal indexers.""" + ob = Test.DecimalIndexerTest() - ob[max_] = "max_" - self.assertTrue(ob[max_] == "max_") + from System import Decimal + max_d = Decimal.Parse("79228162514264337593543950335") + min_d = Decimal.Parse("-79228162514264337593543950335") - ob[min_] = "min_" - self.assertTrue(ob[min_] == "min_") + assert ob[max_d] is None - with self.assertRaises(TypeError): - ob = Test.DoubleIndexerTest() - ob["wrong"] + ob[max_d] = "max_" + assert ob[max_d] == "max_" - with self.assertRaises(TypeError): - ob = Test.DoubleIndexerTest() - ob["wrong"] = "wrong" + ob[min_d] = "min_" + assert ob[min_d] == "min_" - def test_decimal_indexer(self): - """Test Decimal indexers.""" + with pytest.raises(TypeError): ob = Test.DecimalIndexerTest() + ob["wrong"] + + with pytest.raises(TypeError): + ob = Test.DecimalIndexerTest() + ob["wrong"] = "wrong" - from System import Decimal - max_d = Decimal.Parse("79228162514264337593543950335") - min_d = Decimal.Parse("-79228162514264337593543950335") - self.assertTrue(ob[max_d] is None) +def test_string_indexer(): + """Test String indexers.""" + ob = Test.StringIndexerTest() - ob[max_d] = "max_" - self.assertTrue(ob[max_d] == "max_") + assert ob["spam"] is None + assert ob[u"spam"] is None - ob[min_d] = "min_" - self.assertTrue(ob[min_d] == "min_") + ob["spam"] = "spam" + assert ob["spam"] == "spam" + assert ob["spam"] == u"spam" + assert ob[u"spam"] == "spam" + assert ob[u"spam"] == u"spam" - with self.assertRaises(TypeError): - ob = Test.DecimalIndexerTest() - ob["wrong"] + ob[u"eggs"] = u"eggs" + assert ob["eggs"] == "eggs" + assert ob["eggs"] == u"eggs" + assert ob[u"eggs"] == "eggs" + assert ob[u"eggs"] == u"eggs" - with self.assertRaises(TypeError): - ob = Test.DecimalIndexerTest() - ob["wrong"] = "wrong" + with pytest.raises(TypeError): + ob = Test.StringIndexerTest() + ob[1] - def test_string_indexer(self): - """Test String indexers.""" + with pytest.raises(TypeError): ob = Test.StringIndexerTest() + ob[1] = "wrong" + + +def test_enum_indexer(): + """Test enum indexers.""" + ob = Test.EnumIndexerTest() + + key = Test.ShortEnum.One - self.assertTrue(ob["spam"] is None) - self.assertTrue(ob[u"spam"] is None) + assert ob[key] is None - ob["spam"] = "spam" - self.assertTrue(ob["spam"] == "spam") - self.assertTrue(ob["spam"] == u"spam") - self.assertTrue(ob[u"spam"] == "spam") - self.assertTrue(ob[u"spam"] == u"spam") + ob[key] = "spam" + assert ob[key] == "spam" - ob[u"eggs"] = u"eggs" - self.assertTrue(ob["eggs"] == "eggs") - self.assertTrue(ob["eggs"] == u"eggs") - self.assertTrue(ob[u"eggs"] == "eggs") - self.assertTrue(ob[u"eggs"] == u"eggs") + ob[key] = "eggs" + assert ob[key] == "eggs" - with self.assertRaises(TypeError): - ob = Test.StringIndexerTest() - ob[1] + ob[1] = "spam" + assert ob[1] == "spam" - with self.assertRaises(TypeError): - ob = Test.StringIndexerTest() - ob[1] = "wrong" + with pytest.raises(TypeError): + ob = Test.EnumIndexerTest() + ob["wrong"] - def test_enum_indexer(self): - """Test enum indexers.""" + with pytest.raises(TypeError): ob = Test.EnumIndexerTest() + ob["wrong"] = "wrong" - key = Test.ShortEnum.One - self.assertTrue(ob[key] is None) +def test_object_indexer(): + """Test ob indexers.""" + ob = Test.ObjectIndexerTest() - ob[key] = "spam" - self.assertTrue(ob[key] == "spam") + from Python.Test import Spam + spam = Spam("spam") - ob[key] = "eggs" - self.assertTrue(ob[key] == "eggs") + assert ob[spam] is None + assert ob["spam"] is None + assert ob[1] is None + assert ob[None] is None - ob[1] = "spam" - self.assertTrue(ob[1] == "spam") + ob[spam] = "spam" + assert ob[spam] == "spam" - with self.assertRaises(TypeError): - ob = Test.EnumIndexerTest() - ob["wrong"] + ob["spam"] = "eggs" + assert ob["spam"] == "eggs" - with self.assertRaises(TypeError): - ob = Test.EnumIndexerTest() - ob["wrong"] = "wrong" + ob[1] = "one" + assert ob[1] == "one" - def test_object_indexer(self): - """Test ob indexers.""" - ob = Test.ObjectIndexerTest() + ob[long(1)] = "long" + assert ob[long(1)] == "long" - from Python.Test import Spam - spam = Spam("spam") + with pytest.raises(TypeError): + class Eggs(object): + pass - self.assertTrue(ob[spam] is None) - self.assertTrue(ob["spam"] is None) - self.assertTrue(ob[1] is None) - self.assertTrue(ob[None] is None) + key = Eggs() + ob = Test.ObjectIndexerTest() + ob[key] = "wrong" - ob[spam] = "spam" - self.assertTrue(ob[spam] == "spam") - ob["spam"] = "eggs" - self.assertTrue(ob["spam"] == "eggs") +def test_interface_indexer(): + """Test interface indexers.""" + ob = Test.InterfaceIndexerTest() - ob[1] = "one" - self.assertTrue(ob[1] == "one") + from Python.Test import Spam + spam = Spam("spam") - ob[long(1)] = "long" - self.assertTrue(ob[long(1)] == "long") + assert ob[spam] is None - with self.assertRaises(TypeError): - class Eggs(object): - pass + ob[spam] = "spam" + assert ob[spam] == "spam" - key = Eggs() - ob = Test.ObjectIndexerTest() - ob[key] = "wrong" + ob[spam] = "eggs" + assert ob[spam] == "eggs" - def test_interface_indexer(self): - """Test interface indexers.""" + with pytest.raises(TypeError): ob = Test.InterfaceIndexerTest() + ob["wrong"] - from Python.Test import Spam - spam = Spam("spam") + with pytest.raises(TypeError): + ob = Test.InterfaceIndexerTest() + ob["wrong"] = "wrong" - self.assertTrue(ob[spam] is None) - ob[spam] = "spam" - self.assertTrue(ob[spam] == "spam") +def test_typed_indexer(): + """Test typed indexers.""" + ob = Test.TypedIndexerTest() - ob[spam] = "eggs" - self.assertTrue(ob[spam] == "eggs") + from Python.Test import Spam + spam = Spam("spam") - with self.assertRaises(TypeError): - ob = Test.InterfaceIndexerTest() - ob["wrong"] + assert ob[spam] is None - with self.assertRaises(TypeError): - ob = Test.InterfaceIndexerTest() - ob["wrong"] = "wrong" + ob[spam] = "spam" + assert ob[spam] == "spam" - def test_typed_indexer(self): - """Test typed indexers.""" + ob[spam] = "eggs" + assert ob[spam] == "eggs" + + with pytest.raises(TypeError): ob = Test.TypedIndexerTest() + ob["wrong"] - from Python.Test import Spam - spam = Spam("spam") + with pytest.raises(TypeError): + ob = Test.TypedIndexerTest() + ob["wrong"] = "wrong" - self.assertTrue(ob[spam] is None) - ob[spam] = "spam" - self.assertTrue(ob[spam] == "spam") +def test_multi_arg_indexer(): + """Test indexers that take multiple index arguments.""" + ob = Test.MultiArgIndexerTest() - ob[spam] = "eggs" - self.assertTrue(ob[spam] == "eggs") + ob[0, 1] = "zero one" + assert ob[0, 1] == "zero one" - with self.assertRaises(TypeError): - ob = Test.TypedIndexerTest() - ob["wrong"] + ob[1, 9] = "one nine" + assert ob[1, 9] == "one nine" - with self.assertRaises(TypeError): - ob = Test.TypedIndexerTest() - ob["wrong"] = "wrong" + assert ob[10, 50] is None - def test_multi_arg_indexer(self): - """Test indexers that take multiple index arguments.""" + with pytest.raises(TypeError): ob = Test.MultiArgIndexerTest() + _ = ob[0, "one"] - ob[0, 1] = "zero one" - self.assertTrue(ob[0, 1] == "zero one") + with pytest.raises(TypeError): + ob = Test.MultiArgIndexerTest() + ob[0, "one"] = "wrong" - ob[1, 9] = "one nine" - self.assertTrue(ob[1, 9] == "one nine") - self.assertTrue(ob[10, 50] is None) +def test_multi_type_indexer(): + """Test indexers that take multiple indices of different types.""" + ob = Test.MultiTypeIndexerTest() + spam = Test.Spam("spam") - with self.assertRaises(TypeError): - ob = Test.MultiArgIndexerTest() - _ = ob[0, "one"] + ob[0, "one", spam] = "zero one spam" + assert ob[0, "one", spam] == "zero one spam" - with self.assertRaises(TypeError): - ob = Test.MultiArgIndexerTest() - ob[0, "one"] = "wrong" + ob[1, "nine", spam] = "one nine spam" + assert ob[1, "nine", spam] == "one nine spam" - def test_multi_type_indexer(self): - """Test indexers that take multiple indices of different types.""" + with pytest.raises(TypeError): ob = Test.MultiTypeIndexerTest() - spam = Test.Spam("spam") + _ = ob[0, 1, spam] - ob[0, "one", spam] = "zero one spam" - self.assertTrue(ob[0, "one", spam] == "zero one spam") - - ob[1, "nine", spam] = "one nine spam" - self.assertTrue(ob[1, "nine", spam] == "one nine spam") + with pytest.raises(TypeError): + ob = Test.MultiTypeIndexerTest() + ob[0, 1, spam] = "wrong" - with self.assertRaises(TypeError): - ob = Test.MultiTypeIndexerTest() - _ = ob[0, 1, spam] - with self.assertRaises(TypeError): - ob = Test.MultiTypeIndexerTest() - ob[0, 1, spam] = "wrong" +def test_multi_default_key_indexer(): + """Test indexers that take multiple indices with a default + key arguments.""" + # default argument is 2 in the MultiDefaultKeyIndexerTest object + ob = Test.MultiDefaultKeyIndexerTest() + ob[0, 2] = "zero one spam" + assert ob[0] == "zero one spam" - def test_multi_default_key_indexer(self): - """Test indexers that take multiple indices with a default - key arguments.""" - # default argument is 2 in the MultiDefaultKeyIndexerTest object - ob = Test.MultiDefaultKeyIndexerTest() - ob[0, 2] = "zero one spam" - self.assertTrue(ob[0] == "zero one spam") + ob[1] = "one nine spam" + assert ob[1, 2] == "one nine spam" - ob[1] = "one nine spam" - self.assertTrue(ob[1, 2] == "one nine spam") - def test_indexer_wrong_key_type(self): - """Test calling an indexer using a key of the wrong type.""" +def test_indexer_wrong_key_type(): + """Test calling an indexer using a key of the wrong type.""" - with self.assertRaises(TypeError): - ob = Test.PublicIndexerTest() - _ = ob["wrong"] + with pytest.raises(TypeError): + ob = Test.PublicIndexerTest() + _ = ob["wrong"] - with self.assertRaises(TypeError): - ob = Test.PublicIndexerTest() - ob["wrong"] = "spam" + with pytest.raises(TypeError): + ob = Test.PublicIndexerTest() + ob["wrong"] = "spam" - def test_indexer_wrong_value_type(self): - """Test calling an indexer using a value of the wrong type.""" - with self.assertRaises(TypeError): - ob = Test.PublicIndexerTest() - ob[1] = 9993.9 +def test_indexer_wrong_value_type(): + """Test calling an indexer using a value of the wrong type.""" - def test_unbound_indexer(self): - """Test calling an unbound indexer.""" + with pytest.raises(TypeError): ob = Test.PublicIndexerTest() + ob[1] = 9993.9 - Test.PublicIndexerTest.__setitem__(ob, 0, "zero") - self.assertTrue(ob[0] == "zero") - Test.PublicIndexerTest.__setitem__(ob, 1, "one") - self.assertTrue(ob[1] == "one") +def test_unbound_indexer(): + """Test calling an unbound indexer.""" + ob = Test.PublicIndexerTest() - self.assertTrue(ob[10] is None) + Test.PublicIndexerTest.__setitem__(ob, 0, "zero") + assert ob[0] == "zero" - def test_indexer_abuse(self): - """Test indexer abuse.""" - _class = Test.PublicIndexerTest - ob = Test.PublicIndexerTest() + Test.PublicIndexerTest.__setitem__(ob, 1, "one") + assert ob[1] == "one" + + assert ob[10] is None - with self.assertRaises(AttributeError): - del _class.__getitem__ - with self.assertRaises(AttributeError): - del ob.__getitem__ +def test_indexer_abuse(): + """Test indexer abuse.""" + _class = Test.PublicIndexerTest + ob = Test.PublicIndexerTest() - with self.assertRaises(AttributeError): - del _class.__setitem__ + with pytest.raises(AttributeError): + del _class.__getitem__ - with self.assertRaises(AttributeError): - del ob.__setitem__ + with pytest.raises(AttributeError): + del ob.__getitem__ + with pytest.raises(AttributeError): + del _class.__setitem__ -def test_suite(): - return unittest.makeSuite(IndexerTests) + with pytest.raises(AttributeError): + del ob.__setitem__ diff --git a/src/tests/test_interface.py b/src/tests/test_interface.py index 1fac36eb8..997f17264 100644 --- a/src/tests/test_interface.py +++ b/src/tests/test_interface.py @@ -1,72 +1,69 @@ # -*- coding: utf-8 -*- -import unittest +"""Test CLR interface support.""" import Python.Test as Test +import pytest -from _compat import DictProxyType +from ._compat import DictProxyType -class InterfaceTests(unittest.TestCase): - """Test CLR interface support.""" +def test_interface_standard_attrs(): + """Test standard class attributes.""" + from Python.Test import IPublicInterface - def test_interface_standard_attrs(self): - """Test standard class attributes.""" - from Python.Test import IPublicInterface + assert IPublicInterface.__name__ == 'IPublicInterface' + assert IPublicInterface.__module__ == 'Python.Test' + assert isinstance(IPublicInterface.__dict__, DictProxyType) - self.assertTrue(IPublicInterface.__name__ == 'IPublicInterface') - self.assertTrue(IPublicInterface.__module__ == 'Python.Test') - self.assertTrue(isinstance(IPublicInterface.__dict__, DictProxyType)) - def test_global_interface_visibility(self): - """Test visibility of module-level interfaces.""" - from Python.Test import IPublicInterface +def test_global_interface_visibility(): + """Test visibility of module-level interfaces.""" + from Python.Test import IPublicInterface - self.assertTrue(IPublicInterface.__name__ == 'IPublicInterface') + assert IPublicInterface.__name__ == 'IPublicInterface' - with self.assertRaises(ImportError): - from Python.Test import IInternalInterface - _ = IInternalInterface + with pytest.raises(ImportError): + from Python.Test import IInternalInterface + _ = IInternalInterface - with self.assertRaises(AttributeError): - _ = Test.IInternalInterface + with pytest.raises(AttributeError): + _ = Test.IInternalInterface - def test_nested_interface_visibility(self): - """Test visibility of nested interfaces.""" - from Python.Test import InterfaceTest - ob = InterfaceTest.IPublic - self.assertTrue(ob.__name__ == 'IPublic') +def test_nested_interface_visibility(): + """Test visibility of nested interfaces.""" + from Python.Test import InterfaceTest - ob = InterfaceTest.IProtected - self.assertTrue(ob.__name__ == 'IProtected') + ob = InterfaceTest.IPublic + assert ob.__name__ == 'IPublic' - with self.assertRaises(AttributeError): - _ = InterfaceTest.IInternal + ob = InterfaceTest.IProtected + assert ob.__name__ == 'IProtected' - with self.assertRaises(AttributeError): - _ = InterfaceTest.IPrivate + with pytest.raises(AttributeError): + _ = InterfaceTest.IInternal - def test_explicit_cast_to_interface(self): - """Test explicit cast to an interface.""" - from Python.Test import InterfaceTest + with pytest.raises(AttributeError): + _ = InterfaceTest.IPrivate - ob = InterfaceTest() - self.assertTrue(type(ob).__name__ == 'InterfaceTest') - self.assertTrue(hasattr(ob, 'HelloProperty')) - i1 = Test.ISayHello1(ob) - self.assertTrue(type(i1).__name__ == 'ISayHello1') - self.assertTrue(hasattr(i1, 'SayHello')) - self.assertTrue(i1.SayHello() == 'hello 1') - self.assertFalse(hasattr(i1, 'HelloProperty')) +def test_explicit_cast_to_interface(): + """Test explicit cast to an interface.""" + from Python.Test import InterfaceTest - i2 = Test.ISayHello2(ob) - self.assertTrue(type(i2).__name__ == 'ISayHello2') - self.assertTrue(i2.SayHello() == 'hello 2') - self.assertTrue(hasattr(i2, 'SayHello')) - self.assertFalse(hasattr(i2, 'HelloProperty')) + ob = InterfaceTest() + 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') -def test_suite(): - return unittest.makeSuite(InterfaceTests) + i2 = Test.ISayHello2(ob) + assert type(i2).__name__ == 'ISayHello2' + assert i2.SayHello() == 'hello 2' + assert hasattr(i2, 'SayHello') + assert not hasattr(i2, 'HelloProperty') diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 6c4454004..f8b2acf09 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -1,713 +1,745 @@ # -*- coding: utf-8 -*- -import unittest +"""Test CLR method support.""" import System +import pytest from Python.Test import MethodTest -from _compat import PY2, long, unichr +from ._compat import PY2, long, unichr -class MethodTests(unittest.TestCase): - """Test CLR method support.""" +def test_instance_method_descriptor(): + """Test instance method descriptor behavior.""" - def test_instance_method_descriptor(self): - """Test instance method descriptor behavior.""" + with pytest.raises(AttributeError): + MethodTest().PublicMethod = 0 - with self.assertRaises(AttributeError): - MethodTest().PublicMethod = 0 + with pytest.raises(AttributeError): + MethodTest.PublicMethod = 0 - with self.assertRaises(AttributeError): - MethodTest.PublicMethod = 0 + with pytest.raises(AttributeError): + del MethodTest().PublicMethod - with self.assertRaises(AttributeError): - del MethodTest().PublicMethod + with pytest.raises(AttributeError): + del MethodTest.PublicMethod - with self.assertRaises(AttributeError): - del MethodTest.PublicMethod - def test_static_method_descriptor(self): - """Test static method descriptor behavior.""" +def test_static_method_descriptor(): + """Test static method descriptor behavior.""" - with self.assertRaises(AttributeError): - MethodTest().PublicStaticMethod = 0 + with pytest.raises(AttributeError): + MethodTest().PublicStaticMethod = 0 - with self.assertRaises(AttributeError): - MethodTest.PublicStaticMethod = 0 + with pytest.raises(AttributeError): + MethodTest.PublicStaticMethod = 0 - with self.assertRaises(AttributeError): - del MethodTest().PublicStaticMethod + with pytest.raises(AttributeError): + del MethodTest().PublicStaticMethod - with self.assertRaises(AttributeError): - del MethodTest.PublicStaticMethod + with pytest.raises(AttributeError): + del MethodTest.PublicStaticMethod - def test_public_instance_method(self): - """Test public instance method visibility.""" - ob = MethodTest() - self.assertTrue(ob.PublicMethod() == "public") - def test_public_static_method(self): - """Test public static method visibility.""" - ob = MethodTest() - self.assertTrue(MethodTest.PublicStaticMethod() == "public static") - self.assertTrue(ob.PublicStaticMethod() == "public static") +def test_public_instance_method(): + """Test public instance method visibility.""" + ob = MethodTest() + assert ob.PublicMethod() == "public" - def test_protected_instance_method(self): - """Test protected instance method visibility.""" - ob = MethodTest() - self.assertTrue(ob.ProtectedMethod() == "protected") - def test_protected_static_method(self): - """Test protected static method visibility.""" - ob = MethodTest() - result = "protected static" - self.assertTrue(MethodTest.ProtectedStaticMethod() == result) - self.assertTrue(ob.ProtectedStaticMethod() == result) +def test_public_static_method(): + """Test public static method visibility.""" + ob = MethodTest() + assert MethodTest.PublicStaticMethod() == "public static" + assert ob.PublicStaticMethod() == "public static" - def test_internal_method(self): - """Test internal method visibility.""" - with self.assertRaises(AttributeError): - _ = MethodTest().InternalMethod +def test_protected_instance_method(): + """Test protected instance method visibility.""" + ob = MethodTest() + assert ob.ProtectedMethod() == "protected" - with self.assertRaises(AttributeError): - _ = MethodTest.InternalMethod - with self.assertRaises(AttributeError): - _ = MethodTest().InternalStaticMethod +def test_protected_static_method(): + """Test protected static method visibility.""" + ob = MethodTest() + result = "protected static" + assert MethodTest.ProtectedStaticMethod() == result + assert ob.ProtectedStaticMethod() == result - with self.assertRaises(AttributeError): - _ = MethodTest.InternalStaticMethod - def test_private_method(self): - """Test private method visibility.""" +def test_internal_method(): + """Test internal method visibility.""" - with self.assertRaises(AttributeError): - _ = MethodTest().PrivateMethod + with pytest.raises(AttributeError): + _ = MethodTest().InternalMethod - with self.assertRaises(AttributeError): - _ = MethodTest.PrivateMethod + with pytest.raises(AttributeError): + _ = MethodTest.InternalMethod - with self.assertRaises(AttributeError): - _ = MethodTest().PrivateStaticMethod + with pytest.raises(AttributeError): + _ = MethodTest().InternalStaticMethod - with self.assertRaises(AttributeError): - _ = MethodTest.PrivateStaticMethod + with pytest.raises(AttributeError): + _ = MethodTest.InternalStaticMethod - def test_unbound_managed_method_call(self): - """Test calling unbound managed methods.""" - from Python.Test import MethodTestSub - ob = MethodTest() - self.assertTrue(MethodTest.PublicMethod(ob) == "public") +def test_private_method(): + """Test private method visibility.""" - with self.assertRaises(TypeError): - MethodTest.PublicMethod() + with pytest.raises(AttributeError): + _ = MethodTest().PrivateMethod - ob = MethodTestSub() - self.assertTrue(MethodTestSub.PublicMethod(ob) == "public") - self.assertTrue(MethodTestSub.PublicMethod(ob, "echo") == "echo") + with pytest.raises(AttributeError): + _ = MethodTest.PrivateMethod - with self.assertRaises(TypeError): - MethodTestSub.PublicMethod("echo") + with pytest.raises(AttributeError): + _ = MethodTest().PrivateStaticMethod - def test_overloaded_method_inheritance(self): - """Test that overloads are inherited properly.""" - from Python.Test import MethodTestSub + with pytest.raises(AttributeError): + _ = MethodTest.PrivateStaticMethod - ob = MethodTest() - self.assertTrue(ob.PublicMethod() == "public") - with self.assertRaises(TypeError): - ob = MethodTest() - ob.PublicMethod("echo") +def test_unbound_managed_method_call(): + """Test calling unbound managed methods.""" + from Python.Test import MethodTestSub - ob = MethodTestSub() - self.assertTrue(ob.PublicMethod() == "public") + ob = MethodTest() + assert MethodTest.PublicMethod(ob) == "public" - self.assertTrue(ob.PublicMethod("echo") == "echo") + with pytest.raises(TypeError): + MethodTest.PublicMethod() - def test_method_descriptor_abuse(self): - """Test method descriptor abuse.""" - desc = MethodTest.__dict__['PublicMethod'] + ob = MethodTestSub() + assert MethodTestSub.PublicMethod(ob) == "public" + assert MethodTestSub.PublicMethod(ob, "echo") == "echo" - with self.assertRaises(TypeError): - desc.__get__(0, 0) + with pytest.raises(TypeError): + MethodTestSub.PublicMethod("echo") - with self.assertRaises(AttributeError): - desc.__set__(0, 0) - def test_method_docstrings(self): - """Test standard method docstring generation""" - method = MethodTest.GetType - value = 'System.Type GetType()' - self.assertTrue(method.__doc__ == value) +def test_overloaded_method_inheritance(): + """Test that overloads are inherited properly.""" + from Python.Test import MethodTestSub - # ====================================================================== - # Tests of specific argument and result conversion scenarios - # ====================================================================== - - def test_method_call_enum_conversion(self): - """Test enum conversion in method call.""" - from System import TypeCode + ob = MethodTest() + assert ob.PublicMethod() == "public" + with pytest.raises(TypeError): ob = MethodTest() - r = ob.TestEnumConversion(TypeCode.Int32) - self.assertTrue(r == TypeCode.Int32) + ob.PublicMethod("echo") - def test_method_call_flags_conversion(self): - """Test flags conversion in method call.""" - from System.IO import FileAccess + ob = MethodTestSub() + assert ob.PublicMethod() == "public" - ob = MethodTest() - flags = FileAccess.Read | FileAccess.Write - r = ob.TestFlagsConversion(flags) - self.assertTrue(r == flags) + assert ob.PublicMethod("echo") == "echo" - def test_method_call_struct_conversion(self): - """Test struct conversion in method call.""" - from System import Guid - ob = MethodTest() - guid = Guid.NewGuid() - temp = guid.ToString() - r = ob.TestStructConversion(guid) - self.assertTrue(r.ToString() == temp) +def test_method_descriptor_abuse(): + """Test method descriptor abuse.""" + desc = MethodTest.__dict__['PublicMethod'] - def test_subclass_instance_conversion(self): - """Test subclass instance conversion in method call.""" + with pytest.raises(TypeError): + desc.__get__(0, 0) - class TestSubException(System.Exception): - pass + with pytest.raises(AttributeError): + desc.__set__(0, 0) - ob = MethodTest() - instance = TestSubException() - result = ob.TestSubclassConversion(instance) - self.assertTrue(isinstance(result, System.Exception)) - def test_null_array_conversion(self): - """Test null array conversion in method call.""" - ob = MethodTest() - r = ob.TestNullArrayConversion(None) - self.assertTrue(r is None) - - def test_string_params_args(self): - """Test use of string params.""" - result = MethodTest.TestStringParamsArg('one', 'two', 'three') - self.assertEqual(result.Length, 3) - self.assertEqual(len(result), 3, result) - self.assertTrue(result[0] == 'one') - self.assertTrue(result[1] == 'two') - self.assertTrue(result[2] == 'three') - - result = MethodTest.TestStringParamsArg(['one', 'two', 'three']) - self.assertTrue(len(result) == 3) - self.assertTrue(result[0] == 'one') - self.assertTrue(result[1] == 'two') - self.assertTrue(result[2] == 'three') - - def test_object_params_args(self): - """Test use of object params.""" - result = MethodTest.TestObjectParamsArg('one', 'two', 'three') - self.assertEqual(len(result), 3, result) - self.assertTrue(result[0] == 'one') - self.assertTrue(result[1] == 'two') - self.assertTrue(result[2] == 'three') - - result = MethodTest.TestObjectParamsArg(['one', 'two', 'three']) - self.assertEqual(len(result), 3, result) - self.assertTrue(result[0] == 'one') - self.assertTrue(result[1] == 'two') - self.assertTrue(result[2] == 'three') - - def test_value_params_args(self): - """Test use of value type params.""" - result = MethodTest.TestValueParamsArg(1, 2, 3) - self.assertEqual(len(result), 3) - self.assertTrue(result[0] == 1) - self.assertTrue(result[1] == 2) - self.assertTrue(result[2] == 3) - - result = MethodTest.TestValueParamsArg([1, 2, 3]) - self.assertEqual(len(result), 3) - self.assertTrue(result[0] == 1) - self.assertTrue(result[1] == 2) - self.assertTrue(result[2] == 3) - - def test_non_params_array_in_last_place(self): - """Test overload resolution with of non-"params" array as - last parameter.""" - result = MethodTest.TestNonParamsArrayInLastPlace(1, 2, 3) - self.assertTrue(result) - - def test_string_out_params(self): - """Test use of string out-parameters.""" - result = MethodTest.TestStringOutParams("hi", "there") - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == "output string") - - result = MethodTest.TestStringOutParams("hi", None) - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == "output string") - - def test_string_ref_params(self): - """Test use of string byref parameters.""" - result = MethodTest.TestStringRefParams("hi", "there") - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == "output string") - - result = MethodTest.TestStringRefParams("hi", None) - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == "output string") - - def test_value_out_params(self): - """Test use of value type out-parameters.""" - result = MethodTest.TestValueOutParams("hi", 1) - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == 42) - - # None cannot be converted to a value type like int, long, etc. - with self.assertRaises(TypeError): - MethodTest.TestValueOutParams("hi", None) - - def test_value_ref_params(self): - """Test use of value type byref parameters.""" - result = MethodTest.TestValueRefParams("hi", 1) - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == 42) - - # None cannot be converted to a value type like int, long, etc. - with self.assertRaises(TypeError): - MethodTest.TestValueRefParams("hi", None) - - def test_object_out_params(self): - """Test use of object out-parameters.""" - result = MethodTest.TestObjectOutParams("hi", MethodTest()) - self.assertTrue(isinstance(result, tuple)) - self.assertTrue(len(result) == 2) - self.assertTrue(result[0] is True) - self.assertTrue(isinstance(result[1], System.Exception)) - - result = MethodTest.TestObjectOutParams("hi", None) - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(isinstance(result[1], System.Exception)) - - def test_object_ref_params(self): - """Test use of object byref parameters.""" - result = MethodTest.TestObjectRefParams("hi", MethodTest()) - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(isinstance(result[1], System.Exception)) - - result = MethodTest.TestObjectRefParams("hi", None) - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(isinstance(result[1], System.Exception)) - - def test_struct_out_params(self): - """Test use of struct out-parameters.""" - result = MethodTest.TestStructOutParams("hi", System.Guid.NewGuid()) - self.assertTrue(isinstance(result, tuple)) - self.assertEqual(len(result), 2) - self.assertTrue(result[0] is True) - self.assertTrue(isinstance(result[1], System.Guid)) - - # None cannot be converted to a value type like a struct - with self.assertRaises(TypeError): - MethodTest.TestValueRefParams("hi", None) - - def test_struct_ref_params(self): - """Test use of struct byref parameters.""" - result = MethodTest.TestStructRefParams("hi", System.Guid.NewGuid()) - self.assertTrue(isinstance(result, tuple)) - self.assertTrue(len(result) == 2) - self.assertTrue(result[0] is True) - self.assertTrue(isinstance(result[1], System.Guid)) - - # None cannot be converted to a value type like a struct - with self.assertRaises(TypeError): - MethodTest.TestValueRefParams("hi", None) - - def test_void_single_out_param(self): - """Test void method with single out-parameter.""" - result = MethodTest.TestVoidSingleOutParam(9) - self.assertTrue(result == 42) - - # None cannot be converted to a value type - with self.assertRaises(TypeError): - MethodTest.TestVoidSingleOutParam(None) - - def test_void_single_ref_param(self): - """Test void method with single ref-parameter.""" - result = MethodTest.TestVoidSingleRefParam(9) - self.assertTrue(result == 42) - - # None cannot be converted to a value type - with self.assertRaises(TypeError): - MethodTest.TestVoidSingleRefParam(None) - - def test_single_default_param(self): - """Test void method with single ref-parameter.""" - result = MethodTest.TestSingleDefaultParam() - self.assertTrue(result == 5) - - def test_one_arg_and_two_default_param(self): - """Test void method with single ref-parameter.""" - result = MethodTest.TestOneArgAndTwoDefaultParam(11) - self.assertTrue(result == 22) - - result = MethodTest.TestOneArgAndTwoDefaultParam(15) - self.assertTrue(result == 26) - - result = MethodTest.TestOneArgAndTwoDefaultParam(20) - self.assertTrue(result == 31) - - def test_two_default_param(self): - """Test void method with single ref-parameter.""" - result = MethodTest.TestTwoDefaultParam() - self.assertTrue(result == 11) - - def test_explicit_selection_with_out_modifier(self): - """Check explicit overload selection with out modifiers.""" - refstr = System.String("").GetType().MakeByRefType() - result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( - "hi", "there") - self.assertTrue(isinstance(result, tuple)) - self.assertTrue(len(result) == 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == "output string") - - result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( - "hi", None) - self.assertTrue(isinstance(result, tuple)) - self.assertTrue(len(result) == 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == "output string") - - def test_explicit_selection_with_ref_modifier(self): - """Check explicit overload selection with ref modifiers.""" - refstr = System.String("").GetType().MakeByRefType() - result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( - "hi", "there") - self.assertTrue(isinstance(result, tuple)) - self.assertTrue(len(result) == 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == "output string") - - result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( - "hi", None) - self.assertTrue(isinstance(result, tuple)) - self.assertTrue(len(result) == 2) - self.assertTrue(result[0] is True) - self.assertTrue(result[1] == "output string") - - def test_explicit_overload_selection(self): - """Check explicit overload selection using [] syntax.""" - from Python.Test import ISayHello1, InterfaceTest, ShortEnum - from System import Array - - inst = InterfaceTest() - - value = MethodTest.Overloaded.__overloads__[System.Boolean](True) - self.assertTrue(value is True) - - value = MethodTest.Overloaded.__overloads__[bool](True) - self.assertTrue(value is True) - - value = MethodTest.Overloaded.__overloads__[System.Byte](255) - self.assertTrue(value == 255) - - value = MethodTest.Overloaded.__overloads__[System.SByte](127) - self.assertTrue(value == 127) - - value = MethodTest.Overloaded.__overloads__[System.Char](u'A') - self.assertTrue(value == u'A') - - value = MethodTest.Overloaded.__overloads__[System.Char](65535) - self.assertTrue(value == unichr(65535)) - - value = MethodTest.Overloaded.__overloads__[System.Int16](32767) - self.assertTrue(value == 32767) - - value = MethodTest.Overloaded.__overloads__[System.Int32](2147483647) - self.assertTrue(value == 2147483647) - - value = MethodTest.Overloaded.__overloads__[int](2147483647) - self.assertTrue(value == 2147483647) - - value = MethodTest.Overloaded.__overloads__[System.Int64]( - long(9223372036854775807)) - self.assertTrue(value == long(9223372036854775807)) +def test_method_docstrings(): + """Test standard method docstring generation""" + method = MethodTest.GetType + value = 'System.Type GetType()' + assert method.__doc__ == value - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - value = MethodTest.Overloaded.__overloads__[long]( - long(9223372036854775807)) - self.assertTrue(value == long(9223372036854775807)) - value = MethodTest.Overloaded.__overloads__[System.UInt16](65000) - self.assertTrue(value == 65000) +# ====================================================================== +# Tests of specific argument and result conversion scenarios +# ====================================================================== +def test_method_call_enum_conversion(): + """Test enum conversion in method call.""" + from System import TypeCode - value = MethodTest.Overloaded.__overloads__[System.UInt32]( - long(4294967295)) - self.assertTrue(value == long(4294967295)) + ob = MethodTest() + r = ob.TestEnumConversion(TypeCode.Int32) + assert r == TypeCode.Int32 - value = MethodTest.Overloaded.__overloads__[System.UInt64]( - long(18446744073709551615)) - self.assertTrue(value == long(18446744073709551615)) - value = MethodTest.Overloaded.__overloads__[System.Single](3.402823e38) - self.assertTrue(value == 3.402823e38) +def test_method_call_flags_conversion(): + """Test flags conversion in method call.""" + from System.IO import FileAccess - value = MethodTest.Overloaded.__overloads__[System.Double]( - 1.7976931348623157e308) - self.assertTrue(value == 1.7976931348623157e308) + ob = MethodTest() + flags = FileAccess.Read | FileAccess.Write + r = ob.TestFlagsConversion(flags) + assert r == flags - value = MethodTest.Overloaded.__overloads__[float]( - 1.7976931348623157e308) - self.assertTrue(value == 1.7976931348623157e308) - value = MethodTest.Overloaded.__overloads__[System.Decimal]( - System.Decimal.One) - self.assertTrue(value == System.Decimal.One) +def test_method_call_struct_conversion(): + """Test struct conversion in method call.""" + from System import Guid - value = MethodTest.Overloaded.__overloads__[System.String]("spam") - self.assertTrue(value == "spam") + ob = MethodTest() + guid = Guid.NewGuid() + temp = guid.ToString() + r = ob.TestStructConversion(guid) + assert r.ToString() == temp - value = MethodTest.Overloaded.__overloads__[str]("spam") - self.assertTrue(value == "spam") - value = MethodTest.Overloaded.__overloads__[ShortEnum](ShortEnum.Zero) - self.assertTrue(value == ShortEnum.Zero) +def test_subclass_instance_conversion(): + """Test subclass instance conversion in method call.""" - value = MethodTest.Overloaded.__overloads__[System.Object](inst) - self.assertTrue(value.__class__ == inst.__class__) + class TestSubException(System.Exception): + pass - value = MethodTest.Overloaded.__overloads__[InterfaceTest](inst) - self.assertTrue(value.__class__ == inst.__class__) + ob = MethodTest() + instance = TestSubException() + result = ob.TestSubclassConversion(instance) + assert isinstance(result, System.Exception) - value = MethodTest.Overloaded.__overloads__[ISayHello1](inst) - self.assertTrue(value.__class__ == inst.__class__) - atype = Array[System.Object] - value = MethodTest.Overloaded.__overloads__[str, int, atype]( - "one", 1, atype([1, 2, 3])) - self.assertTrue(value == 3) +def test_null_array_conversion(): + """Test null array conversion in method call.""" + ob = MethodTest() + r = ob.TestNullArrayConversion(None) + assert r is None - value = MethodTest.Overloaded.__overloads__[str, int]("one", 1) - self.assertTrue(value == 1) - value = MethodTest.Overloaded.__overloads__[int, str](1, "one") - self.assertTrue(value == 1) +def test_string_params_args(): + """Test use of string params.""" + result = MethodTest.TestStringParamsArg('one', 'two', 'three') + assert result.Length == 3 + assert len(result) == 3, result + assert result[0] == 'one' + assert result[1] == 'two' + assert result[2] == 'three' - def test_overload_selection_with_array_types(self): - """Check overload selection using array types.""" - from Python.Test import ISayHello1, InterfaceTest, ShortEnum - from System import Array + result = MethodTest.TestStringParamsArg(['one', 'two', 'three']) + assert len(result) == 3 + assert result[0] == 'one' + assert result[1] == 'two' + assert result[2] == 'three' - inst = InterfaceTest() - vtype = Array[System.Boolean] - input_ = vtype([True, True]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] is True) - self.assertTrue(value[1] is True) +def test_object_params_args(): + """Test use of object params.""" + result = MethodTest.TestObjectParamsArg('one', 'two', 'three') + assert len(result) == 3, result + assert result[0] == 'one' + assert result[1] == 'two' + assert result[2] == 'three' - vtype = Array[bool] - input_ = vtype([True, True]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] is True) - self.assertTrue(value[1] is True) + result = MethodTest.TestObjectParamsArg(['one', 'two', 'three']) + assert len(result) == 3, result + assert result[0] == 'one' + assert result[1] == 'two' + assert result[2] == 'three' + + +def test_value_params_args(): + """Test use of value type params.""" + result = MethodTest.TestValueParamsArg(1, 2, 3) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + result = MethodTest.TestValueParamsArg([1, 2, 3]) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + +def test_non_params_array_in_last_place(): + """Test overload resolution with of non-"params" array as + last parameter.""" + result = MethodTest.TestNonParamsArrayInLastPlace(1, 2, 3) + assert result + + +def test_string_out_params(): + """Test use of string out-parameters.""" + result = MethodTest.TestStringOutParams("hi", "there") + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == "output string" + + result = MethodTest.TestStringOutParams("hi", None) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == "output string" + + +def test_string_ref_params(): + """Test use of string byref parameters.""" + result = MethodTest.TestStringRefParams("hi", "there") + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == "output string" + + result = MethodTest.TestStringRefParams("hi", None) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == "output string" + + +def test_value_out_params(): + """Test use of value type out-parameters.""" + result = MethodTest.TestValueOutParams("hi", 1) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == 42 + + # None cannot be converted to a value type like int, long, etc. + with pytest.raises(TypeError): + MethodTest.TestValueOutParams("hi", None) + + +def test_value_ref_params(): + """Test use of value type byref parameters.""" + result = MethodTest.TestValueRefParams("hi", 1) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == 42 + + # None cannot be converted to a value type like int, long, etc. + with pytest.raises(TypeError): + MethodTest.TestValueRefParams("hi", None) + + +def test_object_out_params(): + """Test use of object out-parameters.""" + result = MethodTest.TestObjectOutParams("hi", MethodTest()) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert isinstance(result[1], System.Exception) + + result = MethodTest.TestObjectOutParams("hi", None) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert isinstance(result[1], System.Exception) + + +def test_object_ref_params(): + """Test use of object byref parameters.""" + result = MethodTest.TestObjectRefParams("hi", MethodTest()) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert isinstance(result[1], System.Exception) + + result = MethodTest.TestObjectRefParams("hi", None) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert isinstance(result[1], System.Exception) + + +def test_struct_out_params(): + """Test use of struct out-parameters.""" + result = MethodTest.TestStructOutParams("hi", System.Guid.NewGuid()) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert isinstance(result[1], System.Guid) + + # None cannot be converted to a value type like a struct + with pytest.raises(TypeError): + MethodTest.TestValueRefParams("hi", None) + + +def test_struct_ref_params(): + """Test use of struct byref parameters.""" + result = MethodTest.TestStructRefParams("hi", System.Guid.NewGuid()) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert isinstance(result[1], System.Guid) + + # None cannot be converted to a value type like a struct + with pytest.raises(TypeError): + MethodTest.TestValueRefParams("hi", None) + + +def test_void_single_out_param(): + """Test void method with single out-parameter.""" + result = MethodTest.TestVoidSingleOutParam(9) + assert result == 42 + + # None cannot be converted to a value type + with pytest.raises(TypeError): + MethodTest.TestVoidSingleOutParam(None) - vtype = Array[System.Byte] - input_ = vtype([0, 255]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 255) - vtype = Array[System.SByte] - input_ = vtype([0, 127]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 127) +def test_void_single_ref_param(): + """Test void method with single ref-parameter.""" + result = MethodTest.TestVoidSingleRefParam(9) + assert result == 42 - vtype = Array[System.Char] - input_ = vtype([u'A', u'Z']) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == u'A') - self.assertTrue(value[1] == u'Z') + # None cannot be converted to a value type + with pytest.raises(TypeError): + MethodTest.TestVoidSingleRefParam(None) - vtype = Array[System.Char] - input_ = vtype([0, 65535]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == unichr(0)) - self.assertTrue(value[1] == unichr(65535)) - vtype = Array[System.Int16] - input_ = vtype([0, 32767]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 32767) +def test_single_default_param(): + """Test void method with single ref-parameter.""" + result = MethodTest.TestSingleDefaultParam() + assert result == 5 - vtype = Array[System.Int32] - input_ = vtype([0, 2147483647]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 2147483647) - vtype = Array[int] - input_ = vtype([0, 2147483647]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 2147483647) +def test_one_arg_and_two_default_param(): + """Test void method with single ref-parameter.""" + result = MethodTest.TestOneArgAndTwoDefaultParam(11) + assert result == 22 - vtype = Array[System.Int64] - input_ = vtype([0, long(9223372036854775807)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == long(9223372036854775807)) - - # Python 3 has no explicit long type, use System.Int64 instead - if PY2: - vtype = Array[long] - input_ = vtype([0, long(9223372036854775807)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == long(9223372036854775807)) - - vtype = Array[System.UInt16] - input_ = vtype([0, 65000]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == 65000) + result = MethodTest.TestOneArgAndTwoDefaultParam(15) + assert result == 26 - vtype = Array[System.UInt32] - input_ = vtype([0, long(4294967295)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == long(4294967295)) + result = MethodTest.TestOneArgAndTwoDefaultParam(20) + assert result == 31 - vtype = Array[System.UInt64] - input_ = vtype([0, long(18446744073709551615)]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0) - self.assertTrue(value[1] == long(18446744073709551615)) - vtype = Array[System.Single] - input_ = vtype([0.0, 3.402823e38]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0.0) - self.assertTrue(value[1] == 3.402823e38) +def test_two_default_param(): + """Test void method with single ref-parameter.""" + result = MethodTest.TestTwoDefaultParam() + assert result == 11 - vtype = Array[System.Double] - input_ = vtype([0.0, 1.7976931348623157e308]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0.0) - self.assertTrue(value[1] == 1.7976931348623157e308) - vtype = Array[float] - input_ = vtype([0.0, 1.7976931348623157e308]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == 0.0) - self.assertTrue(value[1] == 1.7976931348623157e308) +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") + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == "output string" - vtype = Array[System.Decimal] - input_ = vtype([System.Decimal.Zero, System.Decimal.One]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == System.Decimal.Zero) - self.assertTrue(value[1] == System.Decimal.One) + result = MethodTest.TestStringOutParams.__overloads__[str, refstr]( + "hi", None) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == "output string" - vtype = Array[System.String] - input_ = vtype(["one", "two"]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == "one") - self.assertTrue(value[1] == "two") - vtype = Array[str] - input_ = vtype(["one", "two"]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == "one") - self.assertTrue(value[1] == "two") +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") + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == "output string" - vtype = Array[ShortEnum] - input_ = vtype([ShortEnum.Zero, ShortEnum.One]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0] == ShortEnum.Zero) - self.assertTrue(value[1] == ShortEnum.One) + result = MethodTest.TestStringRefParams.__overloads__[str, refstr]( + "hi", None) + assert isinstance(result, tuple) + assert len(result) == 2 + assert result[0] is True + assert result[1] == "output string" - vtype = Array[System.Object] - input_ = vtype([inst, inst]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].__class__ == inst.__class__) - self.assertTrue(value[1].__class__ == inst.__class__) - vtype = Array[InterfaceTest] - input_ = vtype([inst, inst]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].__class__ == inst.__class__) - self.assertTrue(value[1].__class__ == inst.__class__) +def test_explicit_overload_selection(): + """Check explicit overload selection using [] syntax.""" + from Python.Test import ISayHello1, InterfaceTest, ShortEnum + from System import Array - vtype = Array[ISayHello1] - input_ = vtype([inst, inst]) - value = MethodTest.Overloaded.__overloads__[vtype](input_) - self.assertTrue(value[0].__class__ == inst.__class__) - self.assertTrue(value[1].__class__ == inst.__class__) + inst = InterfaceTest() + + value = MethodTest.Overloaded.__overloads__[System.Boolean](True) + assert value is True - def test_explicit_overload_selection_failure(self): - """Check that overload selection fails correctly.""" + value = MethodTest.Overloaded.__overloads__[bool](True) + assert value is True - with self.assertRaises(TypeError): - _ = MethodTest.Overloaded.__overloads__[System.Type](True) + value = MethodTest.Overloaded.__overloads__[System.Byte](255) + assert value == 255 - with self.assertRaises(TypeError): - _ = MethodTest.Overloaded.__overloads__[int, int](1, 1) + value = MethodTest.Overloaded.__overloads__[System.SByte](127) + assert value == 127 - with self.assertRaises(TypeError): - _ = MethodTest.Overloaded.__overloads__[str, int, int]("", 1, 1) + value = MethodTest.Overloaded.__overloads__[System.Char](u'A') + assert value == u'A' - with self.assertRaises(TypeError): - _ = MethodTest.Overloaded.__overloads__[int, long](1) + value = MethodTest.Overloaded.__overloads__[System.Char](65535) + assert value == unichr(65535) - def test_we_can_bind_to_encoding_get_string(self): - """Check that we can bind to the Encoding.GetString method - with variables.""" - from System.Text import Encoding - from System.IO import MemoryStream + value = MethodTest.Overloaded.__overloads__[System.Int16](32767) + assert value == 32767 - my_bytes = Encoding.UTF8.GetBytes('Some testing string') - stream = MemoryStream() - stream.Write(my_bytes, 0, my_bytes.Length) - stream.Position = 0 + value = MethodTest.Overloaded.__overloads__[System.Int32](2147483647) + assert value == 2147483647 - buff = System.Array.CreateInstance(System.Byte, 3) - buff.Initialize() - data = [] - read = 1 + value = MethodTest.Overloaded.__overloads__[int](2147483647) + assert value == 2147483647 - while read > 0: - read, _ = stream.Read(buff, 0, buff.Length) - temp = Encoding.UTF8.GetString(buff, 0, read) - data.append(temp) + value = MethodTest.Overloaded.__overloads__[System.Int64]( + long(9223372036854775807)) + assert value == long(9223372036854775807) - data = ''.join(data) - self.assertEqual(data, 'Some testing string') + # Python 3 has no explicit long type, use System.Int64 instead + if PY2: + value = MethodTest.Overloaded.__overloads__[long]( + long(9223372036854775807)) + assert value == long(9223372036854775807) + + value = MethodTest.Overloaded.__overloads__[System.UInt16](65000) + assert value == 65000 + + value = MethodTest.Overloaded.__overloads__[System.UInt32]( + long(4294967295)) + assert value == long(4294967295) + value = MethodTest.Overloaded.__overloads__[System.UInt64]( + long(18446744073709551615)) + assert value == long(18446744073709551615) -def test_suite(): - return unittest.makeSuite(MethodTests) + value = MethodTest.Overloaded.__overloads__[System.Single](3.402823e38) + assert value == 3.402823e38 + + value = MethodTest.Overloaded.__overloads__[System.Double]( + 1.7976931348623157e308) + assert value == 1.7976931348623157e308 + + value = MethodTest.Overloaded.__overloads__[float]( + 1.7976931348623157e308) + assert value == 1.7976931348623157e308 + + value = MethodTest.Overloaded.__overloads__[System.Decimal]( + System.Decimal.One) + assert value == System.Decimal.One + + value = MethodTest.Overloaded.__overloads__[System.String]("spam") + assert value == "spam" + + value = MethodTest.Overloaded.__overloads__[str]("spam") + assert value == "spam" + + value = MethodTest.Overloaded.__overloads__[ShortEnum](ShortEnum.Zero) + assert value == ShortEnum.Zero + + value = MethodTest.Overloaded.__overloads__[System.Object](inst) + assert value.__class__ == inst.__class__ + + value = MethodTest.Overloaded.__overloads__[InterfaceTest](inst) + assert value.__class__ == inst.__class__ + + value = MethodTest.Overloaded.__overloads__[ISayHello1](inst) + assert value.__class__ == inst.__class__ + + atype = Array[System.Object] + value = MethodTest.Overloaded.__overloads__[str, int, atype]( + "one", 1, atype([1, 2, 3])) + assert value == 3 + + value = MethodTest.Overloaded.__overloads__[str, int]("one", 1) + assert value == 1 + + value = MethodTest.Overloaded.__overloads__[int, str](1, "one") + assert value == 1 + + +def test_overload_selection_with_array_types(): + """Check overload selection using array types.""" + from Python.Test import ISayHello1, InterfaceTest, ShortEnum + from System import Array + + inst = InterfaceTest() + + vtype = Array[System.Boolean] + input_ = vtype([True, True]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] is True + assert value[1] is True + + vtype = Array[bool] + input_ = vtype([True, True]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] is True + assert value[1] is True + + vtype = Array[System.Byte] + input_ = vtype([0, 255]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == 255 + + vtype = Array[System.SByte] + input_ = vtype([0, 127]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == 127 + + vtype = Array[System.Char] + input_ = vtype([u'A', u'Z']) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == u'A' + assert value[1] == u'Z' + + vtype = Array[System.Char] + input_ = vtype([0, 65535]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == unichr(0) + assert value[1] == unichr(65535) + + vtype = Array[System.Int16] + input_ = vtype([0, 32767]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == 32767 + + vtype = Array[System.Int32] + input_ = vtype([0, 2147483647]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == 2147483647 + + vtype = Array[int] + input_ = vtype([0, 2147483647]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == 2147483647 + + vtype = Array[System.Int64] + input_ = vtype([0, long(9223372036854775807)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == long(9223372036854775807) + + # Python 3 has no explicit long type, use System.Int64 instead + if PY2: + vtype = Array[long] + input_ = vtype([0, long(9223372036854775807)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == long(9223372036854775807) + + vtype = Array[System.UInt16] + input_ = vtype([0, 65000]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == 65000 + + vtype = Array[System.UInt32] + input_ = vtype([0, long(4294967295)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == long(4294967295) + + vtype = Array[System.UInt64] + input_ = vtype([0, long(18446744073709551615)]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0 + assert value[1] == long(18446744073709551615) + + vtype = Array[System.Single] + input_ = vtype([0.0, 3.402823e38]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0.0 + assert value[1] == 3.402823e38 + + vtype = Array[System.Double] + input_ = vtype([0.0, 1.7976931348623157e308]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0.0 + assert value[1] == 1.7976931348623157e308 + + vtype = Array[float] + input_ = vtype([0.0, 1.7976931348623157e308]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == 0.0 + assert value[1] == 1.7976931348623157e308 + + vtype = Array[System.Decimal] + input_ = vtype([System.Decimal.Zero, System.Decimal.One]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == System.Decimal.Zero + assert value[1] == System.Decimal.One + + vtype = Array[System.String] + input_ = vtype(["one", "two"]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == "one" + assert value[1] == "two" + + vtype = Array[str] + input_ = vtype(["one", "two"]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == "one" + assert value[1] == "two" + + vtype = Array[ShortEnum] + input_ = vtype([ShortEnum.Zero, ShortEnum.One]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0] == ShortEnum.Zero + assert value[1] == ShortEnum.One + + vtype = Array[System.Object] + input_ = vtype([inst, inst]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].__class__ == inst.__class__ + assert value[1].__class__ == inst.__class__ + + vtype = Array[InterfaceTest] + input_ = vtype([inst, inst]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].__class__ == inst.__class__ + assert value[1].__class__ == inst.__class__ + + vtype = Array[ISayHello1] + input_ = vtype([inst, inst]) + value = MethodTest.Overloaded.__overloads__[vtype](input_) + assert value[0].__class__ == inst.__class__ + assert value[1].__class__ == inst.__class__ + + +def test_explicit_overload_selection_failure(): + """Check that overload selection fails correctly.""" + + with pytest.raises(TypeError): + _ = MethodTest.Overloaded.__overloads__[System.Type](True) + + with pytest.raises(TypeError): + _ = MethodTest.Overloaded.__overloads__[int, int](1, 1) + + with pytest.raises(TypeError): + _ = MethodTest.Overloaded.__overloads__[str, int, int]("", 1, 1) + + with pytest.raises(TypeError): + _ = MethodTest.Overloaded.__overloads__[int, long](1) + + +def test_we_can_bind_to_encoding_get_string(): + """Check that we can bind to the Encoding.GetString method + with variables.""" + from System.Text import Encoding + from System.IO import MemoryStream + + my_bytes = Encoding.UTF8.GetBytes('Some testing string') + stream = MemoryStream() + stream.Write(my_bytes, 0, my_bytes.Length) + stream.Position = 0 + + buff = System.Array.CreateInstance(System.Byte, 3) + buff.Initialize() + data = [] + read = 1 + + while read > 0: + read, _ = stream.Read(buff, 0, buff.Length) + temp = Encoding.UTF8.GetString(buff, 0, read) + data.append(temp) + + data = ''.join(data) + assert data == 'Some testing string' diff --git a/src/tests/test_module.py b/src/tests/test_module.py index 5ee8e6fc2..2255ea411 100644 --- a/src/tests/test_module.py +++ b/src/tests/test_module.py @@ -1,348 +1,369 @@ # -*- coding: utf-8 -*- +"""Test CLR modules and the CLR import hook.""" + import clr import time import types -import unittest import warnings from fnmatch import fnmatch -from _compat import ClassType, PY2, PY3, range -from utils import is_clr_class, is_clr_module, is_clr_root_module +import pytest + +from ._compat import ClassType, PY2, PY3, range +from .utils import is_clr_class, is_clr_module, is_clr_root_module # testImplicitAssemblyLoad() passes on deprecation warning; perfect! # # clr.AddReference('System.Windows.Forms') -class ModuleTests(unittest.TestCase): - """Test CLR modules and the CLR import hook.""" +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 - def test_import_hook_works(self): - """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 - def test_import_clr(self): - import clr - self.assertTrue(is_clr_root_module(clr)) +def test_import_clr(): + import clr + assert is_clr_root_module(clr) - def test_version_clr(self): - import clr - self.assertTrue(clr.__version__ >= "2.2.0") - def test_preload_var(self): - import clr - self.assertTrue(clr.getPreload() is False, clr.getPreload()) +def test_version_clr(): + import clr + assert clr.__version__ >= "2.2.0" + + +def test_preload_var(): + import clr + assert clr.getPreload() is False, clr.getPreload() + clr.setPreload(False) + assert clr.getPreload() is False, clr.getPreload() + try: + clr.setPreload(True) + assert clr.getPreload() is True, clr.getPreload() + clr.setPreload(0) + assert clr.getPreload() is False, clr.getPreload() + clr.setPreload(1) + assert clr.getPreload() is True, clr.getPreload() + + import System.Configuration + content = dir(System.Configuration) + assert len(content) > 10, content + finally: clr.setPreload(False) - self.assertTrue(clr.getPreload() is False, clr.getPreload()) - try: - clr.setPreload(True) - self.assertTrue(clr.getPreload() is True, clr.getPreload()) - clr.setPreload(0) - self.assertTrue(clr.getPreload() is False, clr.getPreload()) - clr.setPreload(1) - self.assertTrue(clr.getPreload() is True, clr.getPreload()) - - import System.Configuration - content = dir(System.Configuration) - self.assertTrue(len(content) > 10, content) - finally: - clr.setPreload(False) - - def test_module_interface(self): - """Test the interface exposed by CLR module objects.""" - import System - self.assertEquals(type(System.__dict__), type({})) - self.assertEquals(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__ - self.assertTrue(fnmatch(system_file, "*System*.dll") or fnmatch(system_file, "*mscorlib.dll"), - "unexpected System.__file__: " + system_file) - self.assertTrue(System.__doc__.startswith("Namespace containing types from the following assemblies:")) - self.assertTrue(is_clr_class(System.String)) - self.assertTrue(is_clr_class(System.Int32)) - - def test_simple_import(self): - """Test simple import.""" - import System - self.assertTrue(is_clr_module(System)) - self.assertTrue(System.__name__ == 'System') - - import sys - self.assertTrue(isinstance(sys, types.ModuleType)) - self.assertTrue(sys.__name__ == 'sys') - - if PY3: - import http.client as httplib - self.assertTrue(isinstance(httplib, types.ModuleType)) - self.assertTrue(httplib.__name__ == 'http.client') - elif PY2: - import httplib - self.assertTrue(isinstance(httplib, types.ModuleType)) - self.assertTrue(httplib.__name__ == 'httplib') - - def test_simple_import_with_alias(self): - """Test simple import with aliasing.""" - import System as mySystem - self.assertTrue(is_clr_module(mySystem)) - self.assertTrue(mySystem.__name__ == 'System') - - import sys as mySys - self.assertTrue(isinstance(mySys, types.ModuleType)) - self.assertTrue(mySys.__name__ == 'sys') - - if PY3: - import http.client as myHttplib - self.assertTrue(isinstance(myHttplib, types.ModuleType)) - self.assertTrue(myHttplib.__name__ == 'http.client') - elif PY2: - import httplib as myHttplib - self.assertTrue(isinstance(myHttplib, types.ModuleType)) - self.assertTrue(myHttplib.__name__ == 'httplib') - - def test_dotted_name_import(self): - """Test dotted-name import.""" - import System.Reflection - self.assertTrue(is_clr_module(System.Reflection)) - self.assertTrue(System.Reflection.__name__ == 'System.Reflection') - - import xml.dom - self.assertTrue(isinstance(xml.dom, types.ModuleType)) - self.assertTrue(xml.dom.__name__ == 'xml.dom') - - def test_multiple_dotted_name_import(self): - """Test an import bug with multiple dotted imports.""" - import System.Data - self.assertTrue(is_clr_module(System.Data)) - self.assertTrue(System.Data.__name__ == 'System.Data') - import System.Data - self.assertTrue(is_clr_module(System.Data)) - self.assertTrue(System.Data.__name__ == 'System.Data') - - def test_dotted_name_import_with_alias(self): - """Test dotted-name import with aliasing.""" - import System.Reflection as SysRef - self.assertTrue(is_clr_module(SysRef)) - self.assertTrue(SysRef.__name__ == 'System.Reflection') - - import xml.dom as myDom - self.assertTrue(isinstance(myDom, types.ModuleType)) - self.assertTrue(myDom.__name__ == 'xml.dom') - - def test_simple_import_from(self): - """Test simple 'import from'.""" - from System import Reflection - self.assertTrue(is_clr_module(Reflection)) - self.assertTrue(Reflection.__name__ == 'System.Reflection') - - from xml import dom - self.assertTrue(isinstance(dom, types.ModuleType)) - self.assertTrue(dom.__name__ == 'xml.dom') - - def test_simple_import_from_with_alias(self): - """Test simple 'import from' with aliasing.""" - from System import Collections as Coll - self.assertTrue(is_clr_module(Coll)) - self.assertTrue(Coll.__name__ == 'System.Collections') - - from xml import dom as myDom - self.assertTrue(isinstance(myDom, types.ModuleType)) - self.assertTrue(myDom.__name__ == 'xml.dom') - - def test_dotted_name_import_from(self): - """Test dotted-name 'import from'.""" - from System.Collections import Specialized - self.assertTrue(is_clr_module(Specialized)) - self.assertTrue( - Specialized.__name__ == 'System.Collections.Specialized') - - from System.Collections.Specialized import StringCollection - self.assertTrue(is_clr_class(StringCollection)) - self.assertTrue(StringCollection.__name__ == 'StringCollection') - - from xml.dom import pulldom - self.assertTrue(isinstance(pulldom, types.ModuleType)) - self.assertTrue(pulldom.__name__ == 'xml.dom.pulldom') - - from xml.dom.pulldom import PullDOM - self.assertTrue(isinstance(PullDOM, ClassType)) - self.assertTrue(PullDOM.__name__ == 'PullDOM') - - def test_dotted_name_import_from_with_alias(self): - """Test dotted-name 'import from' with aliasing.""" - from System.Collections import Specialized as Spec - self.assertTrue(is_clr_module(Spec)) - self.assertTrue(Spec.__name__ == 'System.Collections.Specialized') - - from System.Collections.Specialized import StringCollection as SC - self.assertTrue(is_clr_class(SC)) - self.assertTrue(SC.__name__ == 'StringCollection') - - from xml.dom import pulldom as myPulldom - self.assertTrue(isinstance(myPulldom, types.ModuleType)) - self.assertTrue(myPulldom.__name__ == 'xml.dom.pulldom') - - from xml.dom.pulldom import PullDOM as myPullDOM - self.assertTrue(isinstance(myPullDOM, ClassType)) - self.assertTrue(myPullDOM.__name__ == 'PullDOM') - - def test_from_module_import_star(self): - """Test from module import * behavior.""" - count = len(locals().keys()) - m = __import__('System.Xml', globals(), locals(), ['*']) - self.assertTrue(m.__name__ == 'System.Xml') - self.assertTrue(is_clr_module(m)) - self.assertTrue(len(locals().keys()) > count + 1) - - def test_implicit_assembly_load(self): - """Test implicit assembly loading via import.""" - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always") - - # should trigger a DeprecationWarning as Microsoft.Build hasn't - # been added as a reference yet (and should exist for mono) - import Microsoft.Build - - self.assertEqual(len(w), 1) - self.assertTrue(isinstance(w[0].message, DeprecationWarning)) - - with warnings.catch_warnings(record=True) as w: - clr.AddReference("System.Windows.Forms") - import System.Windows.Forms as Forms - self.assertTrue(is_clr_module(Forms)) - self.assertTrue(Forms.__name__ == 'System.Windows.Forms') - from System.Windows.Forms import Form - self.assertTrue(is_clr_class(Form)) - self.assertTrue(Form.__name__ == 'Form') - self.assertEqual(len(w), 0) - - def test_explicit_assembly_load(self): - """Test explicit assembly loading using standard CLR tools.""" - from System.Reflection import Assembly - import System, sys - - assembly = Assembly.LoadWithPartialName('System.Data') - self.assertTrue(assembly is not None) - - import System.Data - self.assertTrue('System.Data' in sys.modules) - - assembly = Assembly.LoadWithPartialName('SpamSpamSpamSpamEggsAndSpam') - self.assertTrue(assembly is None) - - def test_implicit_load_already_valid_namespace(self): - """Test implicit assembly load over an already valid namespace.""" - # In this case, the mscorlib assembly (loaded by default) defines - # a number of types in the System namespace. There is also a System - # assembly, which is _not_ loaded by default, which also contains - # types in the System namespace. The desired behavior is for the - # Python runtime to "do the right thing", allowing types from both - # assemblies to be found in the System module implicitly. - import System - self.assertTrue(is_clr_class(System.UriBuilder)) - def test_import_non_existant_module(self): - """Test import failure for a non-existent module.""" - with self.assertRaises(ImportError): - import System.SpamSpamSpam - def test_lookup_no_namespace_type(self): - """Test lookup of types without a qualified namespace.""" - import Python.Test - import clr - self.assertTrue(is_clr_class(clr.NoNamespaceType)) +def test_module_interface(): + """Test the interface exposed by CLR module objects.""" + import System + assert type(System.__dict__) == type({}) + 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 is_clr_class(System.String) + assert is_clr_class(System.Int32) + + +def test_simple_import(): + """Test simple import.""" + import System + assert is_clr_module(System) + assert System.__name__ == 'System' + + import sys + assert isinstance(sys, types.ModuleType) + assert sys.__name__ == 'sys' + + if PY3: + import http.client as httplib + assert isinstance(httplib, types.ModuleType) + assert httplib.__name__ == 'http.client' + elif PY2: + import httplib + assert isinstance(httplib, types.ModuleType) + assert httplib.__name__ == 'httplib' + + +def test_simple_import_with_alias(): + """Test simple import with aliasing.""" + import System as mySystem + assert is_clr_module(mySystem) + assert mySystem.__name__ == 'System' + + import sys as mySys + assert isinstance(mySys, types.ModuleType) + assert mySys.__name__ == 'sys' + + if PY3: + import http.client as myHttplib + assert isinstance(myHttplib, types.ModuleType) + assert myHttplib.__name__ == 'http.client' + elif PY2: + import httplib as myHttplib + assert isinstance(myHttplib, types.ModuleType) + assert myHttplib.__name__ == 'httplib' + + +def test_dotted_name_import(): + """Test dotted-name import.""" + import System.Reflection + assert is_clr_module(System.Reflection) + assert System.Reflection.__name__ == 'System.Reflection' + + import xml.dom + assert isinstance(xml.dom, types.ModuleType) + assert xml.dom.__name__ == 'xml.dom' + + +def test_multiple_dotted_name_import(): + """Test an import bug with multiple dotted imports.""" + import System.Data + assert is_clr_module(System.Data) + assert System.Data.__name__ == 'System.Data' + import System.Data + assert is_clr_module(System.Data) + assert System.Data.__name__ == 'System.Data' + + +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' + + import xml.dom as myDom + assert isinstance(myDom, types.ModuleType) + 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' + + from xml import dom + assert isinstance(dom, types.ModuleType) + 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' + + from xml import dom as myDom + assert isinstance(myDom, types.ModuleType) + 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' + + from System.Collections.Specialized import StringCollection + assert is_clr_class(StringCollection) + assert StringCollection.__name__ == 'StringCollection' + + from xml.dom import pulldom + assert isinstance(pulldom, types.ModuleType) + assert pulldom.__name__ == 'xml.dom.pulldom' + + from xml.dom.pulldom import PullDOM + assert isinstance(PullDOM, ClassType) + 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' + + from System.Collections.Specialized import StringCollection as SC + assert is_clr_class(SC) + assert SC.__name__ == 'StringCollection' + + from xml.dom import pulldom as myPulldom + assert isinstance(myPulldom, types.ModuleType) + assert myPulldom.__name__ == 'xml.dom.pulldom' + + from xml.dom.pulldom import PullDOM as myPullDOM + assert isinstance(myPullDOM, ClassType) + assert myPullDOM.__name__ == 'PullDOM' + + +def test_from_module_import_star(): + """Test from module import * behavior.""" + count = len(locals().keys()) + m = __import__('System.Xml', globals(), locals(), ['*']) + assert m.__name__ == 'System.Xml' + assert is_clr_module(m) + assert len(locals().keys()) > count + 1 + + +def test_implicit_assembly_load(): + """Test implicit assembly loading via import.""" + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + # should trigger a DeprecationWarning as Microsoft.Build hasn't + # been added as a reference yet (and should exist for mono) + import Microsoft.Build + + assert len(w) == 1 + assert isinstance(w[0].message, DeprecationWarning) + + with warnings.catch_warnings(record=True) as w: + clr.AddReference("System.Windows.Forms") + import System.Windows.Forms as Forms + assert is_clr_module(Forms) + assert Forms.__name__ == 'System.Windows.Forms' + from System.Windows.Forms import Form + assert is_clr_class(Form) + assert Form.__name__ == 'Form' + assert len(w) == 0 - def test_module_lookup_recursion(self): - """Test for recursive lookup handling.""" - with self.assertRaises(ImportError): - from System import System +def test_explicit_assembly_load(): + """Test explicit assembly loading using standard CLR tools.""" + from System.Reflection import Assembly + import System, sys - with self.assertRaises(AttributeError): - import System - _ = System.System + assembly = Assembly.LoadWithPartialName('System.Data') + assert assembly is not None - def test_module_get_attr(self): - """Test module getattr behavior.""" + import System.Data + assert 'System.Data' in sys.modules + + assembly = Assembly.LoadWithPartialName('SpamSpamSpamSpamEggsAndSpam') + assert assembly is None + + +def test_implicit_load_already_valid_namespace(): + """Test implicit assembly load over an already valid namespace.""" + # In this case, the mscorlib assembly (loaded by default) defines + # a number of types in the System namespace. There is also a System + # assembly, which is _not_ loaded by default, which also contains + # types in the System namespace. The desired behavior is for the + # 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 + + +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) + + +def test_module_lookup_recursion(): + """Test for recursive lookup handling.""" + + with pytest.raises(ImportError): + from System import System + + with pytest.raises(AttributeError): import System + _ = System.System + - int_type = System.Int32 - self.assertTrue(is_clr_class(int_type)) +def test_module_get_attr(): + """Test module getattr behavior.""" + import System - module = System.Xml - self.assertTrue(is_clr_module(module)) + int_type = System.Int32 + assert is_clr_class(int_type) - with self.assertRaises(AttributeError): - _ = System.Spam + module = System.Xml + assert is_clr_module(module) - with self.assertRaises(TypeError): - _ = getattr(System, 1) + with pytest.raises(AttributeError): + _ = System.Spam - def test_module_attr_abuse(self): - """Test handling of attempts to set module attributes.""" + with pytest.raises(TypeError): + _ = getattr(System, 1) - # It would be safer to use a dict-proxy as the __dict__ for CLR - # modules, but as of Python 2.3 some parts of the CPython runtime - # like dir() will fail if a module dict is not a real dictionary. - def test(): - import System - System.__dict__['foo'] = 0 - return 1 +def test_module_attr_abuse(): + """Test handling of attempts to set module attributes.""" - self.assertTrue(test()) + # It would be safer to use a dict-proxy as the __dict__ for CLR + # modules, but as of Python 2.3 some parts of the CPython runtime + # like dir() will fail if a module dict is not a real dictionary. - def test_module_type_abuse(self): - """Test handling of attempts to break the module type.""" + def test(): import System - mtype = type(System) - - with self.assertRaises(TypeError): - mtype.__getattribute__(0, 'spam') - - with self.assertRaises(TypeError): - mtype.__setattr__(0, 'spam', 1) - - with self.assertRaises(TypeError): - mtype.__repr__(0) - - def test_clr_list_assemblies(self): - from clr import ListAssemblies - verbose = list(ListAssemblies(True)) - short = list(ListAssemblies(False)) - self.assertTrue(u'mscorlib' in short) - self.assertTrue(u'System' in short) - self.assertTrue(u'Culture=' in verbose[0]) - self.assertTrue(u'Version=' in verbose[0]) - - def test_clr_add_reference(self): - from clr import AddReference - from System.IO import FileNotFoundException - for name in ("System", "Python.Runtime"): - assy = AddReference(name) - assy_name = assy.GetName().Name - self.assertEqual(assy_name, name) - - with self.assertRaises(FileNotFoundException): - AddReference("somethingtotallysilly") - - def test_assembly_load_thread_safety(self): - 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() - - -def test_suite(): - return unittest.makeSuite(ModuleTests) + System.__dict__['foo'] = 0 + return 1 + + assert 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') + + with pytest.raises(TypeError): + mtype.__setattr__(0, 'spam', 1) + + with pytest.raises(TypeError): + mtype.__repr__(0) + + +def test_clr_list_assemblies(): + from clr import ListAssemblies + verbose = list(ListAssemblies(True)) + short = list(ListAssemblies(False)) + assert u'mscorlib' in short + assert u'System' in short + assert u'Culture=' in verbose[0] + assert u'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 + assert assy_name == name + + with pytest.raises(FileNotFoundException): + AddReference("somethingtotallysilly") + + +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() diff --git a/src/tests/test_property.py b/src/tests/test_property.py index 8fb37768a..4dc8ea111 100644 --- a/src/tests/test_property.py +++ b/src/tests/test_property.py @@ -1,145 +1,148 @@ # -*- coding: utf-8 -*- -import unittest +"""Test CLR property support.""" +import pytest from Python.Test import PropertyTest -class PropertyTests(unittest.TestCase): - """Test CLR property support.""" +def test_public_instance_property(): + """Test public instance properties.""" + ob = PropertyTest() - def test_public_instance_property(self): - """Test public instance properties.""" - ob = PropertyTest() + assert ob.PublicProperty == 0 + ob.PublicProperty = 1 + assert ob.PublicProperty == 1 - self.assertTrue(ob.PublicProperty == 0) - ob.PublicProperty = 1 - self.assertTrue(ob.PublicProperty == 1) + with pytest.raises(TypeError): + del PropertyTest().PublicProperty - with self.assertRaises(TypeError): - del PropertyTest().PublicProperty - def test_public_static_property(self): - """Test public static properties.""" - ob = PropertyTest() +def test_public_static_property(): + """Test public static properties.""" + ob = PropertyTest() - self.assertTrue(PropertyTest.PublicStaticProperty == 0) - PropertyTest.PublicStaticProperty = 1 - self.assertTrue(PropertyTest.PublicStaticProperty == 1) + assert PropertyTest.PublicStaticProperty == 0 + PropertyTest.PublicStaticProperty = 1 + assert PropertyTest.PublicStaticProperty == 1 - self.assertTrue(ob.PublicStaticProperty == 1) - ob.PublicStaticProperty = 0 - self.assertTrue(ob.PublicStaticProperty == 0) + assert ob.PublicStaticProperty == 1 + ob.PublicStaticProperty = 0 + assert ob.PublicStaticProperty == 0 - with self.assertRaises(TypeError): - del PropertyTest.PublicStaticProperty + with pytest.raises(TypeError): + del PropertyTest.PublicStaticProperty - with self.assertRaises(TypeError): - del PropertyTest().PublicStaticProperty + with pytest.raises(TypeError): + del PropertyTest().PublicStaticProperty - def test_protected_instance_property(self): - """Test protected instance properties.""" - ob = PropertyTest() - self.assertTrue(ob.ProtectedProperty == 0) - ob.ProtectedProperty = 1 - self.assertTrue(ob.ProtectedProperty == 1) +def test_protected_instance_property(): + """Test protected instance properties.""" + ob = PropertyTest() - with self.assertRaises(TypeError): - del PropertyTest().ProtectedProperty + assert ob.ProtectedProperty == 0 + ob.ProtectedProperty = 1 + assert ob.ProtectedProperty == 1 - def test_protected_static_property(self): - """Test protected static properties.""" - ob = PropertyTest() + with pytest.raises(TypeError): + del PropertyTest().ProtectedProperty - self.assertTrue(PropertyTest.ProtectedStaticProperty == 0) - PropertyTest.ProtectedStaticProperty = 1 - self.assertTrue(PropertyTest.ProtectedStaticProperty == 1) - self.assertTrue(ob.ProtectedStaticProperty == 1) - ob.ProtectedStaticProperty = 0 - self.assertTrue(ob.ProtectedStaticProperty == 0) +def test_protected_static_property(): + """Test protected static properties.""" + ob = PropertyTest() - with self.assertRaises(TypeError): - del PropertyTest.ProtectedStaticProperty + assert PropertyTest.ProtectedStaticProperty == 0 + PropertyTest.ProtectedStaticProperty = 1 + assert PropertyTest.ProtectedStaticProperty == 1 - with self.assertRaises(TypeError): - del PropertyTest().ProtectedStaticProperty + assert ob.ProtectedStaticProperty == 1 + ob.ProtectedStaticProperty = 0 + assert ob.ProtectedStaticProperty == 0 - def test_internal_property(self): - """Test internal properties.""" + with pytest.raises(TypeError): + del PropertyTest.ProtectedStaticProperty - with self.assertRaises(AttributeError): - _ = PropertyTest().InternalProperty + with pytest.raises(TypeError): + del PropertyTest().ProtectedStaticProperty - with self.assertRaises(AttributeError): - _ = PropertyTest().InternalStaticProperty - with self.assertRaises(AttributeError): - _ = PropertyTest.InternalStaticProperty +def test_internal_property(): + """Test internal properties.""" - def test_private_property(self): - """Test private properties.""" + with pytest.raises(AttributeError): + _ = PropertyTest().InternalProperty - with self.assertRaises(AttributeError): - _ = PropertyTest().PrivateProperty + with pytest.raises(AttributeError): + _ = PropertyTest().InternalStaticProperty - with self.assertRaises(AttributeError): - _ = PropertyTest().PrivateStaticProperty + with pytest.raises(AttributeError): + _ = PropertyTest.InternalStaticProperty - with self.assertRaises(AttributeError): - _ = PropertyTest.PrivateStaticProperty - def test_property_descriptor_get_set(self): - """Test property descriptor get / set.""" +def test_private_property(): + """Test private properties.""" - # This test ensures that setting an attribute implemented with - # a descriptor actually goes through the descriptor (rather than - # silently replacing the descriptor in the instance or type dict. + with pytest.raises(AttributeError): + _ = PropertyTest().PrivateProperty - ob = PropertyTest() + with pytest.raises(AttributeError): + _ = PropertyTest().PrivateStaticProperty + + with pytest.raises(AttributeError): + _ = PropertyTest.PrivateStaticProperty - self.assertTrue(PropertyTest.PublicStaticProperty == 0) - self.assertTrue(ob.PublicStaticProperty == 0) - descriptor = PropertyTest.__dict__['PublicStaticProperty'] - self.assertTrue(type(descriptor) != int) +def test_property_descriptor_get_set(): + """Test property descriptor get / set.""" - ob.PublicStaticProperty = 0 - descriptor = PropertyTest.__dict__['PublicStaticProperty'] - self.assertTrue(type(descriptor) != int) + # This test ensures that setting an attribute implemented with + # a descriptor actually goes through the descriptor (rather than + # silently replacing the descriptor in the instance or type dict. - PropertyTest.PublicStaticProperty = 0 - descriptor = PropertyTest.__dict__['PublicStaticProperty'] - self.assertTrue(type(descriptor) != int) + ob = PropertyTest() - def test_property_descriptor_wrong_type(self): - """Test setting a property using a value of the wrong type.""" + assert PropertyTest.PublicStaticProperty == 0 + assert ob.PublicStaticProperty == 0 - with self.assertRaises(TypeError): - ob = PropertyTest() - ob.PublicProperty = "spam" + descriptor = PropertyTest.__dict__['PublicStaticProperty'] + assert type(descriptor) != int + + ob.PublicStaticProperty = 0 + descriptor = PropertyTest.__dict__['PublicStaticProperty'] + assert type(descriptor) != int + + PropertyTest.PublicStaticProperty = 0 + descriptor = PropertyTest.__dict__['PublicStaticProperty'] + assert type(descriptor) != int + + +def test_property_descriptor_wrong_type(): + """Test setting a property using a value of the wrong type.""" + + with pytest.raises(TypeError): + ob = PropertyTest() + ob.PublicProperty = "spam" - def test_property_descriptor_abuse(self): - """Test property descriptor abuse.""" - desc = PropertyTest.__dict__['PublicProperty'] - with self.assertRaises(TypeError): - desc.__get__(0, 0) +def test_property_descriptor_abuse(): + """Test property descriptor abuse.""" + desc = PropertyTest.__dict__['PublicProperty'] - with self.assertRaises(TypeError): - desc.__set__(0, 0) + with pytest.raises(TypeError): + desc.__get__(0, 0) - def test_interface_property(self): - """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.""" - from System.Collections import Hashtable, ICollection + with pytest.raises(TypeError): + desc.__set__(0, 0) - mapping = Hashtable() - coll = ICollection(mapping) - self.assertTrue(coll.Count == 0) +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.""" + from System.Collections import Hashtable, ICollection -def test_suite(): - return unittest.makeSuite(PropertyTests) + mapping = Hashtable() + coll = ICollection(mapping) + assert coll.Count == 0 diff --git a/src/tests/test_recursive_types.py b/src/tests/test_recursive_types.py new file mode 100644 index 000000000..ca4b871cf --- /dev/null +++ b/src/tests/test_recursive_types.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- + +"""Test if interop with recursive type inheritance works.""" + + +def test_recursive_type_creation(): + """Test that a recursive types don't crash with a + StackOverflowException""" + from Python.Test import RecursiveInheritance + + test_instance = RecursiveInheritance.SubClass() + test_instance.SomeMethod() diff --git a/src/tests/test_subclass.py b/src/tests/test_subclass.py index 34ec86d9a..8e862a56d 100644 --- a/src/tests/test_subclass.py +++ b/src/tests/test_subclass.py @@ -4,14 +4,15 @@ # both Linux and Windows # TODO: Remove delay of class creations. Adding SetUp/TearDown may help -import unittest +"""Test sub-classing managed types""" import System +import pytest from Python.Test import (IInterfaceTest, SubClassTest, EventArgsTest, FunctionsTest) from System.Collections.Generic import List -from _compat import range +from ._compat import range def interface_test_class_fixture(): @@ -84,113 +85,111 @@ def OnTestEvent(self, value): return DerivedEventTest -class SubClassTests(unittest.TestCase): - """Test sub-classing managed types""" - - @unittest.skip(reason="FIXME: test randomly pass/fails") - def test_base_class(self): - """Test base class managed type""" - ob = SubClassTest() - self.assertEqual(ob.foo(), "foo") - self.assertEqual(FunctionsTest.test_foo(ob), "foo") - self.assertEqual(ob.bar("bar", 2), "bar") - self.assertEqual(FunctionsTest.test_bar(ob, "bar", 2), "bar") - self.assertEqual(ob.not_overriden(), "not_overriden") - self.assertEqual(list(ob.return_list()), ["a", "b", "c"]) - self.assertEqual(list(SubClassTest.test_list(ob)), ["a", "b", "c"]) - - @unittest.skip(reason="FIXME: test randomly pass/fails") - def test_interface(self): - """Test python classes can derive from C# interfaces""" - InterfaceTestClass = interface_test_class_fixture() - ob = InterfaceTestClass() - self.assertEqual(ob.foo(), "InterfaceTestClass") - self.assertEqual(FunctionsTest.test_foo(ob), "InterfaceTestClass") - self.assertEqual(ob.bar("bar", 2), "bar/bar") - self.assertEqual(FunctionsTest.test_bar(ob, "bar", 2), "bar/bar") - - x = FunctionsTest.pass_through(ob) - self.assertEqual(id(x), id(ob)) - - @unittest.skip(reason="FIXME: test randomly pass/fails") - def test_derived_class(self): - """Test python class derived from managed type""" - DerivedClass = derived_class_fixture() - ob = DerivedClass() - self.assertEqual(ob.foo(), "DerivedClass") - self.assertEqual(ob.base_foo(), "foo") - self.assertEqual(ob.super_foo(), "foo") - self.assertEqual(FunctionsTest.test_foo(ob), "DerivedClass") - self.assertEqual(ob.bar("bar", 2), "bar_bar") - self.assertEqual(FunctionsTest.test_bar(ob, "bar", 2), "bar_bar") - self.assertEqual(ob.not_overriden(), "not_overriden") - self.assertEqual(list(ob.return_list()), ["A", "B", "C"]) - self.assertEqual(list(SubClassTest.test_list(ob)), ["A", "B", "C"]) - - x = FunctionsTest.pass_through(ob) - self.assertEqual(id(x), id(ob)) - - @unittest.skip(reason="FIXME: test randomly pass/fails") - def test_create_instance(self): - """Test derived instances can be created from managed code""" - DerivedClass = derived_class_fixture() - ob = FunctionsTest.create_instance(DerivedClass) - self.assertEqual(ob.foo(), "DerivedClass") - self.assertEqual(FunctionsTest.test_foo(ob), "DerivedClass") - self.assertEqual(ob.bar("bar", 2), "bar_bar") - self.assertEqual(FunctionsTest.test_bar(ob, "bar", 2), "bar_bar") - self.assertEqual(ob.not_overriden(), "not_overriden") - - x = FunctionsTest.pass_through(ob) - self.assertEqual(id(x), id(ob)) - - InterfaceTestClass = interface_test_class_fixture() - ob2 = FunctionsTest.create_instance(InterfaceTestClass) - self.assertEqual(ob2.foo(), "InterfaceTestClass") - self.assertEqual(FunctionsTest.test_foo(ob2), "InterfaceTestClass") - self.assertEqual(ob2.bar("bar", 2), "bar/bar") - self.assertEqual(FunctionsTest.test_bar(ob2, "bar", 2), "bar/bar") - - y = FunctionsTest.pass_through(ob2) - self.assertEqual(id(y), id(ob2)) - - @unittest.skip(reason="FIXME: test randomly pass/fails") - def test_events(self): - class EventHandler(object): - def handler(self, x, args): - self.value = args.value - - event_handler = EventHandler() - - x = SubClassTest() - x.TestEvent += event_handler.handler - self.assertEqual(FunctionsTest.test_event(x, 1), 1) - self.assertEqual(event_handler.value, 1) - - InterfaceTestClass = interface_test_class_fixture() - i = InterfaceTestClass() - with self.assertRaises(System.NotImplementedException): - FunctionsTest.test_event(i, 2) - - DerivedEventTest = derived_event_test_class_fixture() - d = DerivedEventTest() - d.add_TestEvent(event_handler.handler) - self.assertEqual(FunctionsTest.test_event(d, 3), 3) - self.assertEqual(event_handler.value, 3) - self.assertEqual(len(d.event_handlers), 1) - - def test_isinstance(self): - a = [str(x) for x in range(0, 1000)] - b = [System.String(x) for x in a] - - for x in a: - self.assertFalse(isinstance(x, System.Object)) - self.assertFalse(isinstance(x, System.String)) - - for x in b: - self.assertTrue(isinstance(x, System.Object)) - self.assertTrue(isinstance(x, System.String)) - - -def test_suite(): - return unittest.makeSuite(SubClassTests) +@pytest.mark.skip(reason="FIXME: test randomly pass/fails") +def test_base_class(): + """Test base class managed type""" + ob = SubClassTest() + assert ob.foo() == "foo" + assert FunctionsTest.test_foo(ob) == "foo" + assert ob.bar("bar", 2) == "bar" + assert FunctionsTest.test_bar(ob, "bar", 2) == "bar" + assert ob.not_overriden() == "not_overriden" + assert list(ob.return_list()) == ["a", "b", "c"] + assert list(SubClassTest.test_list(ob)) == ["a", "b", "c"] + + +@pytest.mark.skip(reason="FIXME: test randomly pass/fails") +def test_interface(): + """Test python classes can derive from C# interfaces""" + InterfaceTestClass = interface_test_class_fixture() + ob = InterfaceTestClass() + assert ob.foo() == "InterfaceTestClass" + assert FunctionsTest.test_foo(ob) == "InterfaceTestClass" + assert ob.bar("bar", 2) == "bar/bar" + assert FunctionsTest.test_bar(ob, "bar", 2) == "bar/bar" + + x = FunctionsTest.pass_through(ob) + assert id(x) == id(ob) + + +@pytest.mark.skip(reason="FIXME: test randomly pass/fails") +def test_derived_class(): + """Test python class derived from managed type""" + DerivedClass = derived_class_fixture() + ob = DerivedClass() + assert ob.foo() == "DerivedClass" + assert ob.base_foo() == "foo" + assert ob.super_foo() == "foo" + assert FunctionsTest.test_foo(ob) == "DerivedClass" + assert ob.bar("bar", 2) == "bar_bar" + assert FunctionsTest.test_bar(ob, "bar", 2) == "bar_bar" + assert ob.not_overriden() == "not_overriden" + assert list(ob.return_list()) == ["A", "B", "C"] + assert list(SubClassTest.test_list(ob)) == ["A", "B", "C"] + + x = FunctionsTest.pass_through(ob) + assert id(x) == id(ob) + + +@pytest.mark.skip(reason="FIXME: test randomly pass/fails") +def test_create_instance(): + """Test derived instances can be created from managed code""" + DerivedClass = derived_class_fixture() + ob = FunctionsTest.create_instance(DerivedClass) + assert ob.foo() == "DerivedClass" + assert FunctionsTest.test_foo(ob) == "DerivedClass" + assert ob.bar("bar", 2) == "bar_bar" + assert FunctionsTest.test_bar(ob, "bar", 2) == "bar_bar" + assert ob.not_overriden() == "not_overriden" + + x = FunctionsTest.pass_through(ob) + assert id(x) == id(ob) + + InterfaceTestClass = interface_test_class_fixture() + ob2 = FunctionsTest.create_instance(InterfaceTestClass) + assert ob2.foo() == "InterfaceTestClass" + assert FunctionsTest.test_foo(ob2) == "InterfaceTestClass" + assert ob2.bar("bar", 2) == "bar/bar" + assert FunctionsTest.test_bar(ob2, "bar", 2) == "bar/bar" + + y = FunctionsTest.pass_through(ob2) + assert id(y) == id(ob2) + + +@pytest.mark.skip(reason="FIXME: test randomly pass/fails") +def test_events(): + class EventHandler(object): + def handler(self, x, args): + self.value = args.value + + event_handler = EventHandler() + + x = SubClassTest() + x.TestEvent += event_handler.handler + assert FunctionsTest.test_event(x, 1) == 1 + assert event_handler.value == 1 + + InterfaceTestClass = interface_test_class_fixture() + i = InterfaceTestClass() + with pytest.raises(System.NotImplementedException): + FunctionsTest.test_event(i, 2) + + DerivedEventTest = derived_event_test_class_fixture() + d = DerivedEventTest() + d.add_TestEvent(event_handler.handler) + assert FunctionsTest.test_event(d, 3) == 3 + assert event_handler.value == 3 + assert len(d.event_handlers) == 1 + + +def test_isinstance_check(): + a = [str(x) for x in range(0, 1000)] + b = [System.String(x) for x in a] + + for x in a: + assert not isinstance(x, System.Object) + assert not isinstance(x, System.String) + + for x in b: + assert isinstance(x, System.Object) + assert isinstance(x, System.String) diff --git a/src/tests/test_suite/__init__.py b/src/tests/test_suite/__init__.py deleted file mode 100644 index ecc1c858f..000000000 --- a/src/tests/test_suite/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- - -import unittest - -from .test_callback import test_suite as callback_tests -from .test_import import test_suite as import_tests -from .test_recursive_types import test_suite as recursive_types_tests - - -def test_suite(): - suite = unittest.TestSuite() - suite.addTests((import_tests(),)) - suite.addTests((callback_tests(),)) - suite.addTests((recursive_types_tests(),)) - return suite diff --git a/src/tests/test_suite/test_callback.py b/src/tests/test_suite/test_callback.py deleted file mode 100644 index 2cb234442..000000000 --- a/src/tests/test_suite/test_callback.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- - -import unittest - - -def simpleDefaultArg(arg='test'): - return arg - - -class CallbackTests(unittest.TestCase): - """Test that callbacks from C# into python work.""" - - def test_default_for_null(self): - """Test that C# can use null for an optional python argument""" - from Python.Test import CallbackTest - - test_instance = CallbackTest() - ret_val = test_instance.Call_simpleDefaultArg_WithNull(__name__) - python_ret_val = simpleDefaultArg(None) - self.assertEquals(ret_val, python_ret_val) - - def test_default_for_none(self): - """Test that C# can use no argument for an optional python argument""" - from Python.Test import CallbackTest - - test_instance = CallbackTest() - ret_val = test_instance.Call_simpleDefaultArg_WithEmptyArgs(__name__) - python_ret_val = simpleDefaultArg() - self.assertEquals(ret_val, python_ret_val) - - -def test_suite(): - return unittest.makeSuite(CallbackTests) diff --git a/src/tests/test_suite/test_import.py b/src/tests/test_suite/test_import.py deleted file mode 100644 index 9bae9ca5f..000000000 --- a/src/tests/test_suite/test_import.py +++ /dev/null @@ -1,18 +0,0 @@ -# -*- coding: utf-8 -*- - -import unittest - - -class ImportTests(unittest.TestCase): - """Test the import statement.""" - - def test_relative_missing_import(self): - """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 self.assertRaises(ImportError): - from . import _missing_import - - -def test_suite(): - return unittest.makeSuite(ImportTests) diff --git a/src/tests/test_suite/test_recursive_types.py b/src/tests/test_suite/test_recursive_types.py deleted file mode 100644 index a213937a5..000000000 --- a/src/tests/test_suite/test_recursive_types.py +++ /dev/null @@ -1,19 +0,0 @@ -# -*- coding: utf-8 -*- - -import unittest - - -class RecursiveTypesTests(unittest.TestCase): - """Test if interop with recursive type inheritance works.""" - - def test_recursive_type_creation(self): - """Test that a recursive types don't crash with a - StackOverflowException""" - from Python.Test import RecursiveInheritance - - test_instance = RecursiveInheritance.SubClass() - test_instance.SomeMethod() - - -def test_suite(): - return unittest.makeSuite(RecursiveTypesTests) diff --git a/src/tests/test_sysargv.py b/src/tests/test_sysargv.py index eefb4d341..2649bf885 100644 --- a/src/tests/test_sysargv.py +++ b/src/tests/test_sysargv.py @@ -1,17 +1,12 @@ # -*- coding: utf-8 -*- -import unittest -import sys - -class SysArgvTests(unittest.TestCase): - """Test sys.argv state.""" +"""Test sys.argv state.""" - def test_sys_argv_state(self): - """Test sys.argv state doesn't change after clr import.""" - argv = sys.argv - import clr - self.assertTrue(argv == sys.argv) +import sys -def test_suite(): - return unittest.makeSuite(SysArgvTests) +def test_sys_argv_state(): + """Test sys.argv state doesn't change after clr import.""" + argv = sys.argv + import clr + assert argv == sys.argv diff --git a/src/tests/test_thread.py b/src/tests/test_thread.py index 623be60a0..c62c15939 100644 --- a/src/tests/test_thread.py +++ b/src/tests/test_thread.py @@ -1,62 +1,58 @@ # -*- coding: utf-8 -*- +"""Test CLR bridge threading and GIL handling.""" + import threading import time -import unittest - -from _compat import range, thread -from utils import dprint - -class ThreadTests(unittest.TestCase): - """Test CLR bridge threading and GIL handling.""" +from ._compat import range, thread +from .utils import dprint - def test_simple_callback_to_python(self): - """Test a call to managed code that then calls back into Python.""" - from Python.Test import ThreadTest - dprint("thread %s SimpleCallBack" % thread.get_ident()) - result = ThreadTest.CallEchoString("spam") - self.assertTrue(result == "spam") - dprint("thread %s SimpleCallBack ret" % thread.get_ident()) +def test_simple_callback_to_python(): + """Test a call to managed code that then calls back into Python.""" + from Python.Test import ThreadTest - def test_double_callback_to_python(self): - """Test a call to managed code that then calls back into Python - that then calls managed code that then calls Python again.""" - from Python.Test import ThreadTest + dprint("thread %s SimpleCallBack" % thread.get_ident()) + result = ThreadTest.CallEchoString("spam") + assert result == "spam" + dprint("thread %s SimpleCallBack ret" % thread.get_ident()) - dprint("thread %s DoubleCallBack" % thread.get_ident()) - result = ThreadTest.CallEchoString2("spam") - self.assertTrue(result == "spam") - dprint("thread %s DoubleCallBack ret" % thread.get_ident()) - def test_python_thread_calls_to_clr(self): - """Test calls by Python-spawned threads into managed code.""" - # This test is very likely to hang if something is wrong ;) - import System +def test_double_callback_to_python(): + """Test a call to managed code that then calls back into Python + that then calls managed code that then calls Python again.""" + from Python.Test import ThreadTest - done = [] + dprint("thread %s DoubleCallBack" % thread.get_ident()) + result = ThreadTest.CallEchoString2("spam") + assert result == "spam" + dprint("thread %s DoubleCallBack ret" % thread.get_ident()) - def run_thread(): - for i in range(10): - time.sleep(0.1) - dprint("thread %s %d" % (thread.get_ident(), i)) - mstr = System.String("thread %s %d" % (thread.get_ident(), i)) - dprint(mstr.ToString()) - done.append(None) - dprint("thread %s %d done" % (thread.get_ident(), i)) - def start_threads(count): - for _ in range(count): - thread_ = threading.Thread(target=run_thread) - thread_.start() +def test_python_thread_calls_to_clr(): + """Test calls by Python-spawned threads into managed code.""" + # This test is very likely to hang if something is wrong ;) + import System - start_threads(5) + done = [] - while len(done) < 50: - dprint(len(done)) + def run_thread(): + for i in range(10): time.sleep(0.1) - - -def test_suite(): - return unittest.makeSuite(ThreadTests) + dprint("thread %s %d" % (thread.get_ident(), i)) + mstr = System.String("thread %s %d" % (thread.get_ident(), i)) + dprint(mstr.ToString()) + done.append(None) + dprint("thread %s %d done" % (thread.get_ident(), i)) + + def start_threads(count): + for _ in range(count): + thread_ = threading.Thread(target=run_thread) + thread_.start() + + start_threads(5) + + while len(done) < 50: + dprint(len(done)) + time.sleep(0.1) diff --git a/src/tests/utils.py b/src/tests/utils.py index 6729d7b30..cacb015ec 100644 --- a/src/tests/utils.py +++ b/src/tests/utils.py @@ -7,7 +7,7 @@ from __future__ import print_function -from _compat import PY2, PY3 +from ._compat import PY2, PY3 def dprint(msg): From 104ef716fc6eea46a5830e1e1317ad5c8a336273 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 23 Jan 2017 05:42:26 -0700 Subject: [PATCH 118/245] Add setup.cfg Control settings for some add-ons like pytest --- setup.cfg | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 setup.cfg diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 000000000..4930652bb --- /dev/null +++ b/setup.cfg @@ -0,0 +1,7 @@ +[tool:pytest] +xfail_strict = True + +[check-manifest] +ignore = + .github + .github/* From 76aa7311c442adeac1f84300b6d3e41fc59c4bf6 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 28 Jan 2017 22:23:46 -0700 Subject: [PATCH 119/245] Simpler tox --- tox.ini | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/tox.ini b/tox.ini index 1cc666ae3..ef15d5099 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,4 @@ [tox] -skipsdist=True skip_missing_interpreters=True envlist = py27 @@ -7,32 +6,19 @@ envlist = py34 py35 py36 + py37 check [testenv] -recreate=True -basepython = - py27: {env:TOXPYTHON:python2.7} - py33: {env:TOXPYTHON:python3.3} - py34: {env:TOXPYTHON:python3.4} - py35: {env:TOXPYTHON:python3.5} - py36: {env:TOXPYTHON:python3.6} - check: python3.5 -setenv = - PYTHONUNBUFFERED=True - DISTUTILS_DEBUG= -passenv = - * +deps = + pytest commands = - python --version - python -c "import struct; print('ARCH: %d' % (struct.calcsize('P') * 8))" - python -c "import ctypes; print('UCS%d' % ctypes.sizeof(ctypes.c_wchar))" - python setup.py bdist_wheel - pip install --no-index --find-links=dist/ pythonnet - {posargs:python src\tests\runtests.py} + {posargs:py.test} [testenv:check] ignore_errors=True +skip_install=True +basepython=python3.5 deps = check-manifest flake8 From adc927f8bee500c43e961f4e071d4cf76542bead Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 8 Feb 2017 14:37:45 -0700 Subject: [PATCH 120/245] Upgrade NUnit to 3.6 --- .travis.yml | 2 +- appveyor.yml | 4 ++-- src/embed_tests/Python.EmbeddingTest.csproj | 4 ++-- src/embed_tests/packages.config | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.travis.yml b/.travis.yml index 7043d4893..1bd377871 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,7 +37,7 @@ install: script: - export PYTHONPATH=`pwd`:$PYTHONPATH - python -m pytest - # - mono ./packages/NUnit.*/tools/nunit-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll + # - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll after_success: # Uncomment if need to geninterop, ie. py37 final diff --git a/appveyor.yml b/appveyor.yml index 6876bb442..c80fdd541 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -10,7 +10,7 @@ environment: PYTHONUNBUFFERED: True PYTHONWARNINGS: 'ignore:::wheel.pep425tags:' PYTHONPATH: C:\testdir - NUNIT: nunit-console + NUNIT: nunit3-console CONDA_BLD: C:\conda CONDA_BLD_VERSION: 3.5 @@ -35,7 +35,7 @@ init: - set CONDA_BLD_ARCH=%PLATFORM:x=% - set PYTHON=C:\PYTHON%PYTHON_VERSION:.=% - if %PLATFORM%==x86 (set CONDA_BLD_ARCH=32) - - if %PLATFORM%==x86 (set NUNIT=%NUNIT%-x86) + # - if %PLATFORM%==x86 (set NUNIT=%NUNIT%-x86) - if %PLATFORM%==x64 (set PYTHON=%PYTHON%-x64) # Prepend newly installed Python to the PATH of this build diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 9cca794b4..a2e92ed19 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -65,8 +65,8 @@ pdbonly - - ..\..\packages\NUnit.2.6.4\lib\nunit.framework.dll + + ..\..\packages\NUnit.3.6.0\lib\net40\nunit.framework.dll diff --git a/src/embed_tests/packages.config b/src/embed_tests/packages.config index 33152fe85..4cb01d3be 100644 --- a/src/embed_tests/packages.config +++ b/src/embed_tests/packages.config @@ -1,5 +1,5 @@ - - + + From 5f86154b1acc2c4e051310284f6ffbce428d4122 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 13 Feb 2017 11:14:38 -0700 Subject: [PATCH 121/245] Fix coverage w NUnit3; add OpenCover filter NUnit3/OpenCover behavior changed. Filter removes coverage from Embedded test files by focusing only on types of Python.Runtime.* --- ci/appveyor_run_tests.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 index 974114cdb..fbfc773a5 100644 --- a/ci/appveyor_run_tests.ps1 +++ b/ci/appveyor_run_tests.ps1 @@ -28,6 +28,7 @@ if ($PYTHON_STATUS -ne 0) { Write-Host ("Starting embedded tests") -ForegroundColor "Green" .$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:cs.coverage ` -target:"$NUNIT" -targetargs:"$CS_TESTS" ` + -filter:"+[*]Python.Runtime*" ` -returntargetcode $NUNIT_STATUS = $LastExitCode if ($NUNIT_STATUS -ne 0) { From a343b34dd3d8e5622b15523e54e0c8d01a59215e Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 14 Feb 2017 04:54:32 -0700 Subject: [PATCH 122/245] Remove check-manifest --- setup.cfg | 5 ----- tox.ini | 1 - 2 files changed, 6 deletions(-) diff --git a/setup.cfg b/setup.cfg index 4930652bb..5ee7224f7 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,7 +1,2 @@ [tool:pytest] xfail_strict = True - -[check-manifest] -ignore = - .github - .github/* diff --git a/tox.ini b/tox.ini index ef15d5099..3c9be5c63 100644 --- a/tox.ini +++ b/tox.ini @@ -23,6 +23,5 @@ deps = check-manifest flake8 commands = - check-manifest {toxinidir} flake8 src setup.py python setup.py check --strict --metadata From ce40fb1a72e1e10ec8428bdd55bab7c08e2866ca Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 14 Feb 2017 04:55:41 -0700 Subject: [PATCH 123/245] Add overload tests from #131 --- src/tests/test_method.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/tests/test_method.py b/src/tests/test_method.py index f8b2acf09..e29986969 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -743,3 +743,29 @@ def test_we_can_bind_to_encoding_get_string(): data = ''.join(data) assert data == 'Some testing string' + + +def test_wrong_overload(): + """Test regression in which implicit conversion caused the wrong types + to be used. See #131 for issue. Fixed by #137, #151""" + + # Used to return `50L` + res = System.Math.Abs(50.5) + assert res == 50.5 + assert type(res) == float + + res = System.Math.Abs(-50.5) + assert res == 50.5 + assert type(res) == float + + res = System.Math.Max(50.5, 50.1) + assert res == 50.5 + assert type(res) == float + + 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? + + res = System.Math.Max(System.Double(50.5), 50.1) + assert res == 50.5 + assert type(res) == float From 8add8d1e29b84339a8fb72cf60a29ffdc8ea5cee Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 14 Feb 2017 07:57:57 -0700 Subject: [PATCH 124/245] Refactor converter.cs & methodbind*.cs (#375) --- src/runtime/converter.cs | 85 ++++++++++++++----------------- src/runtime/methodbinder.cs | 99 ++++++++++++++++-------------------- src/runtime/methodbinding.cs | 30 +++++------ 3 files changed, 97 insertions(+), 117 deletions(-) diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 3a3fa309d..aeaf2d871 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -52,62 +52,53 @@ static Converter() /// internal static Type GetTypeByAlias(IntPtr op) { - if (op == Runtime.PyStringType || - op == Runtime.PyUnicodeType) - { + if (op == Runtime.PyStringType) return stringType; - } - else if (op == Runtime.PyIntType) - { + + if (op == Runtime.PyUnicodeType) + return stringType; + + if (op == Runtime.PyIntType) return int32Type; - } - else if (op == Runtime.PyLongType) - { + + if (op == Runtime.PyLongType) return int64Type; - } - else if (op == Runtime.PyFloatType) - { + + if (op == Runtime.PyFloatType) return doubleType; - } - else if (op == Runtime.PyBoolType) - { + + if (op == Runtime.PyBoolType) return boolType; - } + return null; } internal static IntPtr GetPythonTypeByAlias(Type op) { if (op == stringType) - { return Runtime.PyUnicodeType; - } - else if (Runtime.IsPython3 && (op == int16Type || - op == int32Type || - op == int64Type)) - { + if (op == int16Type) return Runtime.PyIntType; - } - else if (op == int16Type || - op == int32Type) - { + if (op == int32Type) return Runtime.PyIntType; - } - else if (op == int64Type) - { + + if (op == int64Type && Runtime.IsPython2) return Runtime.PyLongType; - } - else if (op == doubleType || - op == singleType) - { + + if (op == int64Type) + return Runtime.PyIntType; + + if (op == doubleType) return Runtime.PyFloatType; - } - else if (op == boolType) - { + + if (op == singleType) + return Runtime.PyFloatType; + + if (op == boolType) return Runtime.PyBoolType; - } + return IntPtr.Zero; } @@ -329,27 +320,27 @@ internal static bool ToManagedValue(IntPtr value, Type obType, return ToPrimitive(value, stringType, out result, setError); } - else if (Runtime.PyBool_Check(value)) + if (Runtime.PyBool_Check(value)) { return ToPrimitive(value, boolType, out result, setError); } - else if (Runtime.PyInt_Check(value)) + if (Runtime.PyInt_Check(value)) { return ToPrimitive(value, int32Type, out result, setError); } - else if (Runtime.PyLong_Check(value)) + if (Runtime.PyLong_Check(value)) { return ToPrimitive(value, int64Type, out result, setError); } - else if (Runtime.PyFloat_Check(value)) + if (Runtime.PyFloat_Check(value)) { return ToPrimitive(value, doubleType, out result, setError); } - else if (Runtime.PySequence_Check(value)) + if (Runtime.PySequence_Check(value)) { return ToArray(value, typeof(object[]), out result, setError); } @@ -371,31 +362,31 @@ internal static bool ToManagedValue(IntPtr value, Type obType, return true; } - else if (value == Runtime.PyBoolType) + if (value == Runtime.PyBoolType) { result = boolType; return true; } - else if (value == Runtime.PyIntType) + if (value == Runtime.PyIntType) { result = int32Type; return true; } - else if (value == Runtime.PyLongType) + if (value == Runtime.PyLongType) { result = int64Type; return true; } - else if (value == Runtime.PyFloatType) + if (value == Runtime.PyFloatType) { result = doubleType; return true; } - else if (value == Runtime.PyListType || value == Runtime.PyTupleType) + if (value == Runtime.PyListType || value == Runtime.PyTupleType) { result = typeof(object[]); return true; diff --git a/src/runtime/methodbinder.cs b/src/runtime/methodbinder.cs index 86a76dd82..1417c21c5 100644 --- a/src/runtime/methodbinder.cs +++ b/src/runtime/methodbinder.cs @@ -170,6 +170,9 @@ internal MethodBase[] GetMethods() /// Precedence algorithm largely lifted from jython - the concerns are /// generally the same so we'll start w/this and tweak as necessary. /// + /// + /// TODO: Add link to specific Jython Section/Code/File + /// internal static int GetPrecedence(MethodBase mi) { ParameterInfo[] pi = mi.GetParameters(); @@ -198,61 +201,49 @@ internal static int ArgPrecedence(Type t) TypeCode tc = Type.GetTypeCode(t); // TODO: Clean up - if (tc == TypeCode.Object) + switch (tc) { - return 1; - } - if (tc == TypeCode.UInt64) - { - return 10; - } - if (tc == TypeCode.UInt32) - { - return 11; - } - if (tc == TypeCode.UInt16) - { - return 12; - } - if (tc == TypeCode.Int64) - { - return 13; - } - if (tc == TypeCode.Int32) - { - return 14; - } - if (tc == TypeCode.Int16) - { - return 15; - } - if (tc == TypeCode.Char) - { - return 16; - } - if (tc == TypeCode.SByte) - { - return 17; - } - if (tc == TypeCode.Byte) - { - return 18; - } - if (tc == TypeCode.Single) - { - return 20; - } - if (tc == TypeCode.Double) - { - return 21; - } - if (tc == TypeCode.String) - { - return 30; - } - if (tc == TypeCode.Boolean) - { - return 40; + case TypeCode.Object: + return 1; + + case TypeCode.UInt64: + return 10; + + case TypeCode.UInt32: + return 11; + + case TypeCode.UInt16: + return 12; + + case TypeCode.Int64: + return 13; + + case TypeCode.Int32: + return 14; + + case TypeCode.Int16: + return 15; + + case TypeCode.Char: + return 16; + + case TypeCode.SByte: + return 17; + + case TypeCode.Byte: + return 18; + + case TypeCode.Single: + return 20; + + case TypeCode.Double: + return 21; + + case TypeCode.String: + return 30; + + case TypeCode.Boolean: + return 40; } if (t.IsArray) diff --git a/src/runtime/methodbinding.cs b/src/runtime/methodbinding.cs index df6632068..07090a92c 100644 --- a/src/runtime/methodbinding.cs +++ b/src/runtime/methodbinding.cs @@ -55,8 +55,7 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) return Exceptions.RaiseTypeError("No match found for given type params"); } - var mb = new MethodBinding(self.m, self.target); - mb.info = mi; + var mb = new MethodBinding(self.m, self.target) { info = mi }; Runtime.XIncref(mb.pyHandle); return mb.pyHandle; } @@ -76,22 +75,21 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key) } string name = Runtime.GetManagedString(key); - if (name == "__doc__") + switch (name) { - IntPtr doc = self.m.GetDocString(); - Runtime.XIncref(doc); - return doc; + case "__doc__": + IntPtr doc = self.m.GetDocString(); + Runtime.XIncref(doc); + return doc; + // FIXME: deprecate __overloads__ soon... + case "__overloads__": + case "Overloads": + var om = new OverloadMapper(self.m, self.target); + Runtime.XIncref(om.pyHandle); + return om.pyHandle; + default: + return Runtime.PyObject_GenericGetAttr(ob, key); } - - // FIXME: deprecate __overloads__ soon... - if (name == "__overloads__" || name == "Overloads") - { - var om = new OverloadMapper(self.m, self.target); - Runtime.XIncref(om.pyHandle); - return om.pyHandle; - } - - return Runtime.PyObject_GenericGetAttr(ob, key); } From a019017bd2dec6871fe78c69b12ebf10c75a79f4 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 13 Feb 2017 22:14:35 -0700 Subject: [PATCH 125/245] Cleanup/Comment Python.Runtime.dll.config & travis We don't need the `*.dll` variant since we don't call for those in `runtime.cs` Enable embedded tests on travis --- .travis.yml | 5 ++++- Python.Runtime.dll.config | 9 ++------- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1bd377871..cf236ccfe 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,9 +35,12 @@ install: - coverage run setup.py build_ext --inplace script: + # Set-up and run python tests - export PYTHONPATH=`pwd`:$PYTHONPATH - python -m pytest - # - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll + + # Run embedded tests + - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll after_success: # Uncomment if need to geninterop, ie. py37 final diff --git a/Python.Runtime.dll.config b/Python.Runtime.dll.config index 8591f58fe..b820676cf 100644 --- a/Python.Runtime.dll.config +++ b/Python.Runtime.dll.config @@ -4,17 +4,12 @@ Keep this file next to Python.Runtime.dll For more information read: http://www.mono-project.com/Config - http://www.mono-project.com/Config_DllMap --> + http://www.mono-project.com/docs/advanced/pinvoke/dllmap --> + - - - - - - From 5ad3408c77acf851f72bd73931c3f420a17cdc24 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 14 Feb 2017 03:35:23 -0700 Subject: [PATCH 126/245] Add LD_LIBRARY_PATH to travis env Find dlls for embedded tests on PY3 --- .travis.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.travis.yml b/.travis.yml index cf236ccfe..3f32f1e7e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -39,6 +39,14 @@ script: - export PYTHONPATH=`pwd`:$PYTHONPATH - python -m pytest + # Set-up dll path for embedded tests + - export LD_LIBRARY_PATH=/opt/python/2.7.9/lib:$LD_LIBRARY_PATH + - export LD_LIBRARY_PATH=/opt/python/3.3.5/lib:$LD_LIBRARY_PATH + - export LD_LIBRARY_PATH=/opt/python/3.4.2/lib:$LD_LIBRARY_PATH + - export LD_LIBRARY_PATH=/opt/python/3.5.2/lib:$LD_LIBRARY_PATH + - export LD_LIBRARY_PATH=/opt/python/3.6.0/lib:$LD_LIBRARY_PATH + - export LD_LIBRARY_PATH=/opt/python/3.7.0/lib:$LD_LIBRARY_PATH + - echo $LD_LIBRARY_PATH # Run embedded tests - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll From 31f0b30147060a6f5ed7964bf2c6aa9b1a2c9277 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 14 Feb 2017 03:50:48 -0700 Subject: [PATCH 127/245] Find dll for PY2 travis embedded tests Copy Python.Runtime.dll.config to embedded tests bin output --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 3f32f1e7e..21b766eb3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -47,6 +47,7 @@ script: - export LD_LIBRARY_PATH=/opt/python/3.6.0/lib:$LD_LIBRARY_PATH - export LD_LIBRARY_PATH=/opt/python/3.7.0/lib:$LD_LIBRARY_PATH - echo $LD_LIBRARY_PATH + - cp Python.Runtime.dll.config src/embed_tests/bin/Python.Runtime.dll.config # Run embedded tests - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll From fcd1cd2ffeed3e658c6444f04d223b18f71d62d8 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 14 Feb 2017 12:23:51 -0700 Subject: [PATCH 128/245] Generalize LD_LIBRARY_PATH Avoid having to manually update python/travis versions --- .travis.yml | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 21b766eb3..f9c99b5f7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -40,12 +40,9 @@ script: - python -m pytest # Set-up dll path for embedded tests - - export LD_LIBRARY_PATH=/opt/python/2.7.9/lib:$LD_LIBRARY_PATH - - export LD_LIBRARY_PATH=/opt/python/3.3.5/lib:$LD_LIBRARY_PATH - - export LD_LIBRARY_PATH=/opt/python/3.4.2/lib:$LD_LIBRARY_PATH - - export LD_LIBRARY_PATH=/opt/python/3.5.2/lib:$LD_LIBRARY_PATH - - export LD_LIBRARY_PATH=/opt/python/3.6.0/lib:$LD_LIBRARY_PATH - - export LD_LIBRARY_PATH=/opt/python/3.7.0/lib:$LD_LIBRARY_PATH + - OUTPUT=$(python --version 2>&1) + - PY_VER=${OUTPUT:7:9} + - export LD_LIBRARY_PATH=/opt/python/$PY_VER/lib:$LD_LIBRARY_PATH - echo $LD_LIBRARY_PATH - cp Python.Runtime.dll.config src/embed_tests/bin/Python.Runtime.dll.config # Run embedded tests From 6afc9e684856fca988c6d5260ee2d6de3735b7cf Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 14 Feb 2017 16:33:16 -0700 Subject: [PATCH 129/245] Add GetPrecedence reference --- src/runtime/methodbinder.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/runtime/methodbinder.cs b/src/runtime/methodbinder.cs index 1417c21c5..b3df8448f 100644 --- a/src/runtime/methodbinder.cs +++ b/src/runtime/methodbinder.cs @@ -167,11 +167,12 @@ internal MethodBase[] GetMethods() } /// - /// Precedence algorithm largely lifted from jython - the concerns are - /// generally the same so we'll start w/this and tweak as necessary. + /// Precedence algorithm largely lifted from Jython - the concerns are + /// generally the same so we'll start with this and tweak as necessary. /// /// - /// TODO: Add link to specific Jython Section/Code/File + /// Based from Jython `org.python.core.ReflectedArgs.precedence` + /// See: https://github.com/jythontools/jython/blob/master/src/org/python/core/ReflectedArgs.java#L192 /// internal static int GetPrecedence(MethodBase mi) { @@ -328,7 +329,7 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth else if (pynargs > clrnargs && clrnargs > 0 && Attribute.IsDefined(pi[clrnargs - 1], typeof(ParamArrayAttribute))) { - // This is a spam(params object[] egg) style method + // This is a `foo(params object[] bar)` style method match = true; arrayStart = clrnargs - 1; } From 8f30a39a2b53f664e814a470972724c7ccb75567 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 14 Feb 2017 21:21:32 -0700 Subject: [PATCH 130/245] Use builtin miniconda --- appveyor.yml | 9 +--- ci/appveyor_build_recipe.ps1 | 21 ++++++-- ci/install_miniconda.ps1 | 95 ------------------------------------ ci/run_with_env.cmd | 85 -------------------------------- 4 files changed, 20 insertions(+), 190 deletions(-) delete mode 100644 ci/install_miniconda.ps1 delete mode 100644 ci/run_with_env.cmd diff --git a/appveyor.yml b/appveyor.yml index c80fdd541..080aa3807 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -11,13 +11,7 @@ environment: PYTHONWARNINGS: 'ignore:::wheel.pep425tags:' PYTHONPATH: C:\testdir NUNIT: nunit3-console - CONDA_BLD: C:\conda - CONDA_BLD_VERSION: 3.5 - - # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the - # /E:ON and /V:ON options are not enabled in the batch script interpreter - # See: http://stackoverflow.com/a/13751649/163740 - CMD_IN_ENV: 'cmd /E:ON /V:ON /C .\ci\run_with_env.cmd' + CONDA_BLD: C:\miniconda35 matrix: - PYTHON_VERSION: 2.7 @@ -37,6 +31,7 @@ init: - if %PLATFORM%==x86 (set CONDA_BLD_ARCH=32) # - if %PLATFORM%==x86 (set NUNIT=%NUNIT%-x86) - if %PLATFORM%==x64 (set PYTHON=%PYTHON%-x64) + - if %PLATFORM%==x64 (set CONDA_BLD=%CONDA_BLD%-x64) # Prepend newly installed Python to the PATH of this build - set PATH=%PYTHON%;%PYTHON%\Scripts;%PATH% diff --git a/ci/appveyor_build_recipe.ps1 b/ci/appveyor_build_recipe.ps1 index 0c885d88d..cd11f57b9 100644 --- a/ci/appveyor_build_recipe.ps1 +++ b/ci/appveyor_build_recipe.ps1 @@ -1,6 +1,21 @@ if ($env:APPVEYOR_PULL_REQUEST_NUMBER) { - Invoke-Expression .\ci\install_miniconda.ps1 - &"$env:CONDA_BLD\Scripts\conda" build conda.recipe --dirty -q - $CONDA_PKG=(&"$env:CONDA_BLD\Scripts\conda" build conda.recipe --output -q) + # Update PATH, and keep a copy to restore at end of this PowerShell script + $old_path = $env:path + $env:path = "$env:CONDA_BLD;$env:CONDA_BLD\Scripts;" + $env:path + + Write-Host "Starting Conda Update/Install" -ForegroundColor "Green" + conda update conda -q -y + conda install conda-build jinja2 anaconda-client -q -y + + Write-Host "Starting Conda Recipe build" -ForegroundColor "Green" + conda build conda.recipe -q --dirty + + $CONDA_PKG=(conda build conda.recipe -q --output) Copy-Item $CONDA_PKG "$env:APPVEYOR_BUILD_FOLDER\dist\" + Write-Host "Completed Conda Recipe build" -ForegroundColor "Green" + + # Restore PATH back to original + $env:path = $old_path +} else { + Write-Host "Skipping Conda Recipe build" -ForegroundColor "Green" } diff --git a/ci/install_miniconda.ps1 b/ci/install_miniconda.ps1 deleted file mode 100644 index 5c87ca894..000000000 --- a/ci/install_miniconda.ps1 +++ /dev/null @@ -1,95 +0,0 @@ -# Sample script to install Miniconda under Windows -# Authors: Olivier Grisel, Jonathan Helmus and Kyle Kastner, Robert McGibbon -# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/ - -$MINICONDA_URL = "http://repo.continuum.io/miniconda/" - - -function DownloadMiniconda($python_version, $platform_suffix) { - $webclient = New-Object System.Net.WebClient - $filename = "Miniconda3-latest-Windows-" + $platform_suffix + ".exe" - $url = $MINICONDA_URL + $filename - - $basedir = $pwd.Path + "\" - $filepath = $basedir + $filename - if (Test-Path $filename) { - Write-Host "Reusing" $filepath - return $filepath - } - - # Download and retry up to 3 times in case of network transient errors. - Write-Host "Downloading" $filename "from" $url - $retry_attempts = 2 - for ($i=0; $i -lt $retry_attempts; $i++) { - try { - $webclient.DownloadFile($url, $filepath) - break - } - catch [Exception] { - Start-Sleep 1 - } - } - - if (Test-Path $filepath) { - Write-Host "File saved at" $filepath - } else { - # Retry once to get the error message if any at the last try - $webclient.DownloadFile($url, $filepath) - } - return $filepath -} - - -function InstallMiniconda($python_version, $architecture, $python_home) { - Write-Host "Installing Python $python_version $architecture bit to $python_home" - if (Test-Path $python_home) { - Write-Host "$python_home already exists, skipping." - } - if ($architecture -match "32") { - $platform_suffix = "x86" - } else { - $platform_suffix = "x86_64" - } - - $filepath = DownloadMiniconda $python_version $platform_suffix - Write-Host "Installing $filepath to $python_home" - $install_log = $python_home + ".log" - $args = "/S /D=$python_home" - Write-Host $filepath $args - Start-Process -FilePath $filepath -ArgumentList $args -Wait -Passthru - if (Test-Path $python_home) { - Write-Host "Python $python_version $architecture bit installation complete" - } else { - Write-Host "Failed to install Python in $python_home" - Get-Content -Path $install_log - Exit 1 - } -} - - -function InstallCondaPackages($python_home, $spec) { - $conda_path = $python_home + "\Scripts\conda.exe" - $args = "install --yes " + $spec - Write-Host ("conda " + $args) -ForegroundColor "Green" - Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru -} - - -function UpdateConda($python_home) { - $conda_path = $python_home + "\Scripts\conda.exe" - Write-Host "Updating conda..." -ForegroundColor "Green" - $args = "update --yes conda" - Write-Host $conda_path $args - Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru -} - - -function main() { - Write-Host "Starting install_miniconda.ps1" -ForegroundColor "Green" - InstallMiniconda $env:CONDA_BLD_VERSION $env:CONDA_BLD_ARCH $env:CONDA_BLD - UpdateConda $env:CONDA_BLD - InstallCondaPackages $env:CONDA_BLD "conda-build jinja2 anaconda-client" - Write-Host "Completed install_miniconda.ps1" -ForegroundColor "Green" -} - -main diff --git a/ci/run_with_env.cmd b/ci/run_with_env.cmd deleted file mode 100644 index c88489f2c..000000000 --- a/ci/run_with_env.cmd +++ /dev/null @@ -1,85 +0,0 @@ -:: EXPECTED ENV VARS: PYTHON_ARCH (either x86 or x64) -:: CONDA_PY (either 27, 33, 35 etc. - only major version is extracted) -:: -:: -:: To build extensions for 64 bit Python 3, we need to configure environment -:: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of: -:: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1) -:: -:: To build extensions for 64 bit Python 2, we need to configure environment -:: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of: -:: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0) -:: -:: 32 bit builds, and 64-bit builds for 3.5 and beyond, do not require specific -:: environment configurations. -:: -:: Note: this script needs to be run with the /E:ON and /V:ON flags for the -:: cmd interpreter, at least for (SDK v7.0) -:: -:: More details at: -:: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows -:: http://stackoverflow.com/a/13751649/163740 -:: -:: Author: Phil Elson -:: Original Author: Olivier Grisel (https://github.com/ogrisel/python-appveyor-demo) -:: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/ -:: -:: Notes about batch files for Python people: -:: -:: Quotes in values are literally part of the values: -:: SET FOO="bar" -:: FOO is now five characters long: " b a r " -:: If you don't want quotes, don't include them on the right-hand side. -:: -:: The CALL lines at the end of this file look redundant, but if you move them -:: outside of the IF clauses, they do not run properly in the SET_SDK_64==Y -:: case, I don't know why. -:: originally from https://github.com/pelson/Obvious-CI/blob/master/scripts/obvci_appveyor_python_build_env.cmd -:: https://github.com/alimanfoo/zarr/blob/master/build.cmd -:: https://github.com/cython/cython/blob/master/appveyor/run_with_env.cmd -:: https://github.com/cjrh/easycython/blob/master/appveyor/setup_build_env.cmd -@ECHO OFF - -SET COMMAND_TO_RUN=%* -SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows - -:: CONDA_PY style, such as 27, 34 etc. -SET MAJOR_PYTHON_VERSION=%CONDA_PY:~0,1% -SET MINOR_PYTHON_VERSION=%CONDA_PY:~1,1% - -:: Based on the Python version, determine what SDK version to use, and whether -:: to set the SDK for 64-bit. -IF %MAJOR_PYTHON_VERSION% == 2 ( - SET WINDOWS_SDK_VERSION="v7.0" - SET SET_SDK_64=Y -) ELSE IF %MAJOR_PYTHON_VERSION% == 3 ( - SET WINDOWS_SDK_VERSION="v7.1" - IF %MINOR_PYTHON_VERSION% LEQ 4 ( - SET SET_SDK_64=Y - ) ELSE ( - SET SET_SDK_64=N - ) -) ELSE ( - ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%" - EXIT /B 1 -) - -IF "%PYTHON_ARCH%"=="64" ( - IF %SET_SDK_64% == Y ( - ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture - SET DISTUTILS_USE_SDK=1 - SET MSSdk=1 - "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION% - "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release - ECHO Executing: %COMMAND_TO_RUN% - call %COMMAND_TO_RUN% || EXIT /B 1 - ) ELSE ( - ECHO Using default MSVC build environment for 64 bit architecture - ECHO Executing: %COMMAND_TO_RUN% - call %COMMAND_TO_RUN% || EXIT /B 1 - ) -) ELSE ( - ECHO Using default MSVC build environment for 32 bit architecture - ECHO Executing: %COMMAND_TO_RUN% - call %COMMAND_TO_RUN% || EXIT /B 1 -) From 1bd8636089e762d30446beb0ecde8cdabedc564f Mon Sep 17 00:00:00 2001 From: denfromufa Date: Wed, 15 Feb 2017 13:29:11 -0600 Subject: [PATCH 131/245] Update version (#379) * Update setup.py * Update clr.py --- setup.py | 2 +- src/runtime/resources/clr.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index f2790ddd3..37a936584 100644 --- a/setup.py +++ b/setup.py @@ -368,7 +368,7 @@ def run(self): setup( name="pythonnet", - version="2.2.2", + version="2.3.0.dev1", description=".Net and Mono integration for Python", url='https://pythonnet.github.io/', license='MIT', diff --git a/src/runtime/resources/clr.py b/src/runtime/resources/clr.py index c329b1f6d..ccd17889f 100644 --- a/src/runtime/resources/clr.py +++ b/src/runtime/resources/clr.py @@ -2,7 +2,7 @@ Code in this module gets loaded into the main clr module. """ -__version__ = "2.2.2" +__version__ = "2.3.0.dev1" class clrproperty(object): From 08c2d646d588539c27b6c9e4af3cddfbc3f97ce9 Mon Sep 17 00:00:00 2001 From: denfromufa Date: Thu, 16 Feb 2017 03:15:26 -0600 Subject: [PATCH 132/245] StackOverflow/Slack shields (#384) Add StackExchange and Slack shields Shields got too long for a single line, had to break them up into two lines. One for build/quality status, the other for social/info. Add regression number to disabled code. --- README.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 86825386c..c66e8eef8 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,12 @@ [![appveyor shield][]](https://ci.appveyor.com/project/pythonnet/pythonnet/branch/master) [![travis shield][]](https://travis-ci.org/pythonnet/pythonnet) [![codecov shield][]](https://codecov.io/github/pythonnet/pythonnet) + [![license shield][]](./LICENSE) [![pypi package version][]](https://pypi.python.org/pypi/pythonnet) [![python supported shield][]](https://pypi.python.org/pypi/pythonnet) +[![stackexchange shield][]](http://stackoverflow.com/questions/tagged/python.net) +[![slack][]](https://pythonnet.slack.com) Python for .NET is a package that gives Python programmers nearly seamless integration with the .NET Common Language Runtime (CLR) and @@ -35,14 +38,14 @@ from System.Windows.Forms import Form ## Embedding Python in .NET - All calls to python should be inside - a `using (Py.GIL()) {/_ Your code here _/}` block. + a `using (Py.GIL()) {/* Your code here */}` block. - Import python modules using `dynamic mod = Py.Import("mod")`, then you can call functions as normal, eg `mod.func(args)`. - Use `mod.func(args, Py.kw("keywordargname", keywordargvalue))` to apply keyword arguments. - All python objects should be declared as `dynamic` type. - Mathematical operations involving python and literal/managed types must - have the python object first, eg `np.pi_2` works, `2_np.pi` doesn't. + have the python object first, eg. `np.pi_2` works, `2_np.pi` doesn't. ### Example @@ -57,7 +60,7 @@ static void Main(string[] args) Console.WriteLine(sin(5)); double c = np.cos(5) + sin(5); Console.WriteLine(c); - /* this block is temporarily disabled due to regression + /* this block is temporarily disabled due to regression #249 dynamic a = np.array(new List { 1, 2, 3 }); dynamic b = np.array(new List { 6, 5, 4 }, Py.kw("dtype", np.int32)); Console.WriteLine(a.dtype); @@ -81,7 +84,7 @@ int32 [appveyor shield]: https://img.shields.io/appveyor/ci/pythonnet/pythonnet/master.svg?label=AppVeyor -[codecov shield]: https://img.shields.io/codecov/c/github/pythonnet/pythonnet/master.svg?label=codecov +[codecov shield]: https://img.shields.io/codecov/c/github/pythonnet/pythonnet/master.svg?label=Codecov [license shield]: https://img.shields.io/badge/license-MIT-blue.svg?maxAge=3600 @@ -89,4 +92,8 @@ int32 [python supported shield]: https://img.shields.io/pypi/pyversions/pythonnet.svg +[slack]: https://img.shields.io/badge/chat-slack-color.svg?style=social + +[stackexchange shield]: https://img.shields.io/badge/StackOverflow-python.net-blue.svg + [travis shield]: https://img.shields.io/travis/pythonnet/pythonnet/master.svg?label=Travis From 0f00e3a995d1d00d863ce9c170f8809722bcf1c9 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Thu, 16 Feb 2017 14:02:45 +0100 Subject: [PATCH 133/245] Slack integration for Travis and Appveyor (#386) * Add Slack integration for Travis * Use encrypted string for Travis. * Add hook for Appveyor. --- .travis.yml | 2 ++ appveyor.yml | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/.travis.yml b/.travis.yml index 5b56cf4a6..1cb2d3fb4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,3 +57,5 @@ after_success: notifications: email: false + slack: + secure: "UiQdSK1/uNnHl8/gQgfLj/F5JGxtJuaT3QYtKNcw3Ddpr3FX8tfXJ/RjsCsSlRQzDm7AdBAeMzcBQmvH4iRIV2y7qVywLyru5MPiwY4ZjMN6fJK/zaaxetOct9fasIBYzHguNPDAtiBGFh2iK1H1MXTY8rkmU3WZvl18b8EsrP0=" diff --git a/appveyor.yml b/appveyor.yml index 080aa3807..35fb2c5cc 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -68,3 +68,8 @@ on_finish: artifacts: - path: dist\* + +notifications: + - provider: Slack + incoming_webhook: + secure: 2S/t6rGHdbwoxehnvn5KgfsHrBFEtwnPD7M5olGErmz70oWFVpqoWd/EvDwh7rKZGdOTjDmpwcukc2xi5VRaGHbBAqFYS3tAdgAMrcaTNWs= From 4ecde5b0f5e5482559c1cde663b68f4e67ee54f7 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 02:54:28 -0700 Subject: [PATCH 134/245] Simplify LD_LIBRARY_PATH on Travis Based from: http://stackoverflow.com/a/24115039/5208670 Moved to own section to separate as a prep-enviroment step --- .travis.yml | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1cb2d3fb4..dabc5c338 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,5 @@ sudo: false -# language: csharp installs mono/dotnet but has limited python. language: python python: - 2.7 @@ -29,6 +28,11 @@ addons: - mono-devel - ca-certificates-mono +before_install: + # Set-up dll path for embedded tests + - PY_LIBDIR=$(python -c 'import sysconfig; print(sysconfig.get_config_var("LIBDIR"))') + - export LD_LIBRARY_PATH=$PY_LIBDIR:$LD_LIBRARY_PATH + install: - pip install --upgrade pycparser coverage codecov pytest # setup.py install works too, but need to deal w Python.test then @@ -39,11 +43,6 @@ script: - export PYTHONPATH=`pwd`:$PYTHONPATH - python -m pytest - # Set-up dll path for embedded tests - - OUTPUT=$(python --version 2>&1) - - PY_VER=${OUTPUT:7:9} - - export LD_LIBRARY_PATH=/opt/python/$PY_VER/lib:$LD_LIBRARY_PATH - - echo $LD_LIBRARY_PATH - cp Python.Runtime.dll.config src/embed_tests/bin/Python.Runtime.dll.config # Run embedded tests # - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll From c64e34e3a1b47e8ec36afbc1fa5f6ab2f2ecadb9 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 03:01:00 -0700 Subject: [PATCH 135/245] Rename NUnit vars to generic names Makes it easier to switch test-runners in the future. Note the if section is being skipped for NUnit3, but leaving it in case needed to rollback to NUnit2, or upgrade to XUnit --- appveyor.yml | 2 -- ci/appveyor_run_tests.ps1 | 20 ++++++++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 35fb2c5cc..facdacff1 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -10,7 +10,6 @@ environment: PYTHONUNBUFFERED: True PYTHONWARNINGS: 'ignore:::wheel.pep425tags:' PYTHONPATH: C:\testdir - NUNIT: nunit3-console CONDA_BLD: C:\miniconda35 matrix: @@ -29,7 +28,6 @@ init: - set CONDA_BLD_ARCH=%PLATFORM:x=% - set PYTHON=C:\PYTHON%PYTHON_VERSION:.=% - if %PLATFORM%==x86 (set CONDA_BLD_ARCH=32) - # - if %PLATFORM%==x86 (set NUNIT=%NUNIT%-x86) - if %PLATFORM%==x64 (set PYTHON=%PYTHON%-x64) - if %PLATFORM%==x64 (set CONDA_BLD=%CONDA_BLD%-x64) diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 index fbfc773a5..194056c75 100644 --- a/ci/appveyor_run_tests.ps1 +++ b/ci/appveyor_run_tests.ps1 @@ -1,9 +1,17 @@ -# Script to simplify appveyor configuration and resolve path to tools +# Script to simplify AppVeyor configuration and resolve path to tools + +# Test Runner framework being used for embedded tests +$CS_RUNNER = "nunit3-console" + +# Needed for ARCH specific runners(NUnit2/XUnit3). Skip for NUnit3 +if ($FALSE -and $env:PLATFORM -eq "x86"){ + $CS_RUNNER = $CS_RUNNER + "-x86" +} # Executable paths for OpenCover # Note if OpenCover fails, it won't affect the exit codes. $OPENCOVER = Resolve-Path .\packages\OpenCover.*\tools\OpenCover.Console.exe -$NUNIT = Resolve-Path .\packages\NUnit.*\tools\"$env:NUNIT".exe +$CS_RUNNER = Resolve-Path .\packages\NUnit.*\tools\"$CS_RUNNER".exe $PY = Get-Command python # Can't use ".\build\*\Python.EmbeddingTest.dll". Missing framework files. @@ -27,16 +35,16 @@ if ($PYTHON_STATUS -ne 0) { # Powershell options splatting: http://stackoverflow.com/a/24313253/5208670 Write-Host ("Starting embedded tests") -ForegroundColor "Green" .$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:cs.coverage ` - -target:"$NUNIT" -targetargs:"$CS_TESTS" ` + -target:"$CS_RUNNER" -targetargs:"$CS_TESTS" ` -filter:"+[*]Python.Runtime*" ` -returntargetcode -$NUNIT_STATUS = $LastExitCode -if ($NUNIT_STATUS -ne 0) { +$CS_STATUS = $LastExitCode +if ($CS_STATUS -ne 0) { Write-Host "Embedded tests failed" -ForegroundColor "Red" } # Set exit code to fail if either Python or Embedded tests failed -if ($PYTHON_STATUS -ne 0 -or $NUNIT_STATUS -ne 0) { +if ($PYTHON_STATUS -ne 0 -or $CS_STATUS -ne 0) { Write-Host "Tests failed" -ForegroundColor "Red" $host.SetShouldExit(1) } From 1d7e784b0b7b493dfd05d055479f4dd8fc870c06 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 03:04:51 -0700 Subject: [PATCH 136/245] Remove python test STDERR redirect Pytest doesn't need stderr redirect. It behaves --- ci/appveyor_run_tests.ps1 | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/ci/appveyor_run_tests.ps1 b/ci/appveyor_run_tests.ps1 index 194056c75..4245d1577 100644 --- a/ci/appveyor_run_tests.ps1 +++ b/ci/appveyor_run_tests.ps1 @@ -19,20 +19,16 @@ $CS_TESTS = ".\src\embed_tests\bin\Python.EmbeddingTest.dll" $RUNTIME_DIR = ".\src\runtime\bin\" # Run python tests with C# coverage -# why `2>&1 | %{ "$_" }`? see: http://stackoverflow.com/a/20950421/5208670 Write-Host ("Starting Python tests") -ForegroundColor "Green" .$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:py.coverage ` -target:"$PY" -targetargs:"-m pytest" ` - -returntargetcode ` - 2>&1 | %{ "$_" } + -returntargetcode $PYTHON_STATUS = $LastExitCode if ($PYTHON_STATUS -ne 0) { Write-Host "Python tests failed, continuing to embedded tests" -ForegroundColor "Red" } # Run Embedded tests with C# coverage -# Powershell continuation: http://stackoverflow.com/a/2608186/5208670 -# Powershell options splatting: http://stackoverflow.com/a/24313253/5208670 Write-Host ("Starting embedded tests") -ForegroundColor "Green" .$OPENCOVER -register:user -searchdirs:"$RUNTIME_DIR" -output:cs.coverage ` -target:"$CS_RUNNER" -targetargs:"$CS_TESTS" ` From 433dc33edc2872daefb2fda0e3d4fe1b55d5858c Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 03:10:16 -0700 Subject: [PATCH 137/245] Clean-up AppVeyor build recipe Conda automatically updates when doing install. To disable its autoupdate add conda config --set auto_update_conda False --- ci/appveyor_build_recipe.ps1 | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/ci/appveyor_build_recipe.ps1 b/ci/appveyor_build_recipe.ps1 index cd11f57b9..f36702f40 100644 --- a/ci/appveyor_build_recipe.ps1 +++ b/ci/appveyor_build_recipe.ps1 @@ -1,21 +1,24 @@ +# Build `conda.recipe` only if this is a Pull_Request. Saves time for CI. + if ($env:APPVEYOR_PULL_REQUEST_NUMBER) { # Update PATH, and keep a copy to restore at end of this PowerShell script $old_path = $env:path $env:path = "$env:CONDA_BLD;$env:CONDA_BLD\Scripts;" + $env:path - Write-Host "Starting Conda Update/Install" -ForegroundColor "Green" - conda update conda -q -y - conda install conda-build jinja2 anaconda-client -q -y + Write-Host "Starting conda install" -ForegroundColor "Green" + conda config --set always_yes True + conda config --set changeps1 False + conda install conda-build jinja2 anaconda-client --quiet - Write-Host "Starting Conda Recipe build" -ForegroundColor "Green" - conda build conda.recipe -q --dirty + Write-Host "Starting conda build recipe" -ForegroundColor "Green" + conda build conda.recipe --dirty --quiet - $CONDA_PKG=(conda build conda.recipe -q --output) - Copy-Item $CONDA_PKG "$env:APPVEYOR_BUILD_FOLDER\dist\" - Write-Host "Completed Conda Recipe build" -ForegroundColor "Green" + $CONDA_PKG=(conda build conda.recipe --output) + Copy-Item $CONDA_PKG .\dist\ + Write-Host "Completed conda build recipe" -ForegroundColor "Green" # Restore PATH back to original $env:path = $old_path } else { - Write-Host "Skipping Conda Recipe build" -ForegroundColor "Green" + Write-Host "Skipping conda build recipe" -ForegroundColor "Green" } From d319f4ebaedc163ec21a39ca124c51ccbf453afb Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 03:12:02 -0700 Subject: [PATCH 138/245] Add requirements.txt and pytest options Pytest options provide summary for skipped/xfailed tests and adds color on appveyor --- .travis.yml | 4 ++-- appveyor.yml | 5 ++--- requirements.txt | 11 +++++++++++ setup.cfg | 4 ++++ 4 files changed, 19 insertions(+), 5 deletions(-) create mode 100644 requirements.txt diff --git a/.travis.yml b/.travis.yml index dabc5c338..cedd01bf1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,8 +34,8 @@ before_install: - export LD_LIBRARY_PATH=$PY_LIBDIR:$LD_LIBRARY_PATH install: - - pip install --upgrade pycparser coverage codecov pytest - # setup.py install works too, but need to deal w Python.test then + - pip install --upgrade -r requirements.txt + # `setup.py install` works too, but need to deal with `Python.Test` PATH - coverage run setup.py build_ext --inplace script: diff --git a/appveyor.yml b/appveyor.yml index facdacff1..490c4b280 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -40,10 +40,9 @@ init: - python -c "import ctypes; print(ctypes.sizeof(ctypes.c_wchar))" install: - # install for wheels & coverage - - pip install --upgrade pip wheel coverage codecov pytest + - pip install --upgrade -r requirements.txt - # Install OpenCover. Can't put on packages.config; not Linux/Mono compatible + # Install OpenCover. Can't put on `packages.config`, not Mono compatible - .\tools\nuget\nuget.exe install OpenCover -OutputDirectory packages build_script: diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 000000000..19c3693a1 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +# Requirements for both Travis and AppVeyor +pytest +coverage + +# Platform specific requirements +pip; sys_platform == 'win32' +wheel; sys_platform == 'win32' +pycparser; sys_platform != 'win32' + +# Coverage upload +codecov diff --git a/setup.cfg b/setup.cfg index 5ee7224f7..f05de8217 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,2 +1,6 @@ +# Don't combine `.bumpversion.cfg` with `setup.cfg`. Messes up formatting. + [tool:pytest] xfail_strict = True +# -r fsxX: show extra summary info for: (f)ailed, (s)kip, (x)failed, (X)passed +addopts = -r fsxX --color=yes From 5ead8ef214083ad2b958b66271939261f80ea275 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 03:15:18 -0700 Subject: [PATCH 139/245] Quiet sdist output & update comments on AppVeyor --- appveyor.yml | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 490c4b280..83a2b0da6 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -20,7 +20,7 @@ environment: - PYTHON_VERSION: 3.6 init: - # Prepare environment + # Prepare Environment - mkdir C:\testdir # Set environment variables depending based on build cfg @@ -46,17 +46,16 @@ install: - .\tools\nuget\nuget.exe install OpenCover -OutputDirectory packages build_script: - # build clean sdist & wheel with coverage of setup.py, install local wheel - - coverage run setup.py sdist bdist_wheel + # Create clean `sdist`. Only used for releases + - python setup.py --quiet sdist + # Build `wheel` with coverage of `setup.py` + - coverage run setup.py bdist_wheel test_script: - pip install --no-index --find-links=.\dist\ pythonnet - ps: Copy-Item (Resolve-Path .\build\*\Python.Test.dll) C:\testdir - # Test runner - ps: .\ci\appveyor_run_tests.ps1 - - # Build conda-recipe on Pull Requests - ps: .\ci\appveyor_build_recipe.ps1 on_finish: From da940f53920e3606302e92ad7dc57c06668dfbe2 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 03:32:25 -0700 Subject: [PATCH 140/245] Add pytest header info & remove unused fixtures Fixtures came from a different project and I forgot to delete them. Add custom header to gather environment info with test results. Remove testdir from pythonpath. pytest handles this on conftest.py --- appveyor.yml | 6 ----- src/tests/conftest.py | 58 ++++++++++++------------------------------- 2 files changed, 16 insertions(+), 48 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 83a2b0da6..df1fe52c4 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,7 +9,6 @@ environment: global: PYTHONUNBUFFERED: True PYTHONWARNINGS: 'ignore:::wheel.pep425tags:' - PYTHONPATH: C:\testdir CONDA_BLD: C:\miniconda35 matrix: @@ -34,11 +33,6 @@ init: # Prepend newly installed Python to the PATH of this build - set PATH=%PYTHON%;%PYTHON%\Scripts;%PATH% - # Check that we have the expected version, architecture for Python - - python --version - - python -c "import struct; print(struct.calcsize('P') * 8)" - - python -c "import ctypes; print(ctypes.sizeof(ctypes.c_wchar))" - install: - pip install --upgrade -r requirements.txt diff --git a/src/tests/conftest.py b/src/tests/conftest.py index 85fff291f..7e86f87ae 100644 --- a/src/tests/conftest.py +++ b/src/tests/conftest.py @@ -1,57 +1,31 @@ # -*- coding: utf-8 -*- -# TODO: move tests one out of src. Pythonnet doesn't run... +# TODO: move tests one out of src to project root. +# TODO: travis has numpy on their workers. Maybe add tests? """Helpers for testing.""" -import io -import os +import ctypes import sys +import sysconfig -import pytest import clr +# Add path for Python.Test & Add References sys.path.append('C:/testdir/') clr.AddReference("Python.Test") clr.AddReference("System.Collections") clr.AddReference("System.Data") -DIR_PATH = os.path.dirname(__file__) -FILES_DIR = os.path.join(DIR_PATH, 'files') +def pytest_report_header(config): + """Generate extra report headers""" + # FIXME: https://github.com/pytest-dev/pytest/issues/2257 + is_64bits = sys.maxsize > 2**32 + arch = "x64" if is_64bits else "x86" + ucs = ctypes.sizeof(ctypes.c_wchar) + libdir = sysconfig.get_config_var("LIBDIR") + shared = bool(sysconfig.get_config_var("Py_ENABLE_SHARED")) -@pytest.fixture() -def filepath(): - """Returns full file path for test files.""" - - def make_filepath(filename): - # http://stackoverflow.com/questions/18011902/parameter-to-a-fixture - # Alternate solution is to use paramtrization `inderect=True` - # http://stackoverflow.com/a/33879151 - # Syntax is noisy and requires specific variable names - return os.path.join(FILES_DIR, filename) - - return make_filepath - - -@pytest.fixture() -def load_file(filepath): - """Opens filename with encoding and return its contents.""" - - def make_load_file(filename, encoding='utf-8'): - # http://stackoverflow.com/questions/18011902/parameter-to-a-fixture - # Alternate solution is to use paramtrization `inderect=True` - # http://stackoverflow.com/a/33879151 - # Syntax is noisy and requires specific variable names - # And seems to be limited to only 1 argument. - with io.open(filepath(filename), encoding=encoding) as f: - return f.read().strip() - - return make_load_file - - -@pytest.fixture() -def get_stream(filepath): - def make_stream(filename, encoding='utf-8'): - return io.open(filepath(filename), encoding=encoding) - - return make_stream + header = ("Arch: {arch}, UCS: {ucs}, LIBDIR: {libdir}, " + "Py_ENABLE_SHARED: {shared}".format(**locals())) + return header From 99e04c525f9eb26e478036c0f426f654d468cc36 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 04:44:48 -0700 Subject: [PATCH 141/245] Move Conda env to PowerShell recipe script PY_VER removes the `.` it is used on appveyor_build_recipe.ps1 --- appveyor.yml | 12 ++++-------- ci/appveyor_build_recipe.ps1 | 11 +++++++++++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index df1fe52c4..1b15f0925 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,7 +9,6 @@ environment: global: PYTHONUNBUFFERED: True PYTHONWARNINGS: 'ignore:::wheel.pep425tags:' - CONDA_BLD: C:\miniconda35 matrix: - PYTHON_VERSION: 2.7 @@ -22,15 +21,12 @@ init: # Prepare Environment - mkdir C:\testdir - # Set environment variables depending based on build cfg - - set CONDA_PY=%PYTHON_VERSION:.=% - - set CONDA_BLD_ARCH=%PLATFORM:x=% - - set PYTHON=C:\PYTHON%PYTHON_VERSION:.=% - - if %PLATFORM%==x86 (set CONDA_BLD_ARCH=32) + # Update Environment Variables based on matrix/platform + - set PY_VER=%PYTHON_VERSION:.=% + - set PYTHON=C:\PYTHON%PY_VER% - if %PLATFORM%==x64 (set PYTHON=%PYTHON%-x64) - - if %PLATFORM%==x64 (set CONDA_BLD=%CONDA_BLD%-x64) - # Prepend newly installed Python to the PATH of this build + # Put desired Python version first in PATH - set PATH=%PYTHON%;%PYTHON%\Scripts;%PATH% install: diff --git a/ci/appveyor_build_recipe.ps1 b/ci/appveyor_build_recipe.ps1 index f36702f40..00d28ce88 100644 --- a/ci/appveyor_build_recipe.ps1 +++ b/ci/appveyor_build_recipe.ps1 @@ -1,5 +1,16 @@ # Build `conda.recipe` only if this is a Pull_Request. Saves time for CI. +$env:CONDA_PY = "$env:PY_VER" +# Use pre-installed miniconda. Note that location differs if 64bit +$env:CONDA_BLD = "C:\miniconda35" + +if ($env:PLATFORM -eq "x86"){ + $env:CONDA_BLD_ARCH=32 +} else { + $env:CONDA_BLD_ARCH=64 + $env:CONDA_BLD = "$env:CONDA_BLD" + "-x64" +} + if ($env:APPVEYOR_PULL_REQUEST_NUMBER) { # Update PATH, and keep a copy to restore at end of this PowerShell script $old_path = $env:path From d77f933489c295407b32de332d70fbde1ccfe2a8 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 06:19:47 -0700 Subject: [PATCH 142/245] Use Codecov report flags Upgrade to Codecov v2.0.6, didn't get released to PyPi. --- .travis.yml | 6 ++++-- appveyor.yml | 7 +++++-- requirements.txt | 3 ++- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index cedd01bf1..375920fb6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,6 +18,7 @@ env: - LD_PRELOAD=/lib/x86_64-linux-gnu/libSegFault.so - SEGFAULT_SIGNALS=all - PYTHONUNBUFFERED=True + - CODECOV_ENV=TRAVIS_PYTHON_VERSION addons: apt: @@ -51,8 +52,9 @@ after_success: # Uncomment if need to geninterop, ie. py37 final # - python tools/geninterop/geninterop.py - # Waiting on mono-cov support or SharpCover - - codecov + # Waiting on mono-coverage, SharpCover or xr.Baboon + - coverage xml -i + - codecov --file coverage.xml --flags Setup_Linux notifications: email: false diff --git a/appveyor.yml b/appveyor.yml index 1b15f0925..6c26b646f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,6 +9,7 @@ environment: global: PYTHONUNBUFFERED: True PYTHONWARNINGS: 'ignore:::wheel.pep425tags:' + CODECOV_ENV: PYTHON_VERSION, PLATFORM matrix: - PYTHON_VERSION: 2.7 @@ -49,8 +50,10 @@ test_script: - ps: .\ci\appveyor_build_recipe.ps1 on_finish: - # Upload coverage - - codecov + - coverage xml -i + - codecov --file coverage.xml --flags Setup_Windows + - codecov --file py.coverage --flags Python_Tests + - codecov --file cs.coverage --flags Embedded_Tests artifacts: - path: dist\* diff --git a/requirements.txt b/requirements.txt index 19c3693a1..bcceedf25 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,4 +8,5 @@ wheel; sys_platform == 'win32' pycparser; sys_platform != 'win32' # Coverage upload -codecov +# codecov v2.0.6 isn't on PyPi +https://github.com/codecov/codecov-python/tarball/v2.0.6 From df59d0f9200a4adf6840a6e2faac528ac480f039 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 19:36:10 -0700 Subject: [PATCH 143/245] Clean-up CI configs --- .travis.yml | 10 +++++----- appveyor.yml | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 375920fb6..13eea9516 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,6 +30,9 @@ addons: - ca-certificates-mono before_install: + # Set-up location where `Python.Test.dll` will be output + - export PYTHONPATH=`pwd`:$PYTHONPATH + # Set-up dll path for embedded tests - PY_LIBDIR=$(python -c 'import sysconfig; print(sysconfig.get_config_var("LIBDIR"))') - export LD_LIBRARY_PATH=$PY_LIBDIR:$LD_LIBRARY_PATH @@ -40,15 +43,12 @@ install: - coverage run setup.py build_ext --inplace script: - # Set-up and run python tests - - export PYTHONPATH=`pwd`:$PYTHONPATH - python -m pytest - - cp Python.Runtime.dll.config src/embed_tests/bin/Python.Runtime.dll.config - # Run embedded tests + - cp Python.Runtime.dll.config src/embed_tests/bin/ # - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll -after_success: +after_script: # Uncomment if need to geninterop, ie. py37 final # - python tools/geninterop/geninterop.py diff --git a/appveyor.yml b/appveyor.yml index 6c26b646f..a839e2eea 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -44,7 +44,7 @@ build_script: test_script: - pip install --no-index --find-links=.\dist\ pythonnet - - ps: Copy-Item (Resolve-Path .\build\*\Python.Test.dll) C:\testdir + - ps: Copy-Item .\src\testing\bin\Python.Test.dll C:\testdir\ - ps: .\ci\appveyor_run_tests.ps1 - ps: .\ci\appveyor_build_recipe.ps1 From 94c266ee60d7d91db3f274342b92104e6888515f Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 16 Feb 2017 20:08:00 -0700 Subject: [PATCH 144/245] Update CHANGELOG --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dcf33d7e..9161b3977 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Added XML Documentation (#349) - Added Embedded tests on Appveyor (#353) - Added PY3 settings to configuration-manager (#346) +- Added `Slack` chat (#384)(#383)(#386) ### Changed @@ -22,11 +23,14 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Completed refactor of Build Directives on `Runtime.cs` (#339) - Refactor python unittests (#329) - Unfroze Mono version on Travis (#345) +- Changed `unittests` to `pytest` (#368) +- Upgraded NUnit framework from 2.6.4 to 3.6.0 (#371) ### Fixed - Fixed crash during Initialization (#343) - Fixed crash during Shutdown (#365) +- Fixed multiple build warnings ### Removed From 1d583c7e18ab7496314b59148ab79a5a5dd22fa5 Mon Sep 17 00:00:00 2001 From: yagweb Date: Fri, 17 Feb 2017 14:07:28 +0800 Subject: [PATCH 145/245] Pass arbitrary .NET object as value of an attr of PyObject by dyn type(#373) --- AUTHORS.md | 1 + CHANGELOG.md | 2 + src/embed_tests/Python.EmbeddingTest.csproj | 2 + src/embed_tests/dynamic.cs | 122 ++++++++++++++++++++ src/runtime/pyobject.cs | 32 ++--- 5 files changed, 144 insertions(+), 15 deletions(-) create mode 100644 src/embed_tests/dynamic.cs diff --git a/AUTHORS.md b/AUTHORS.md index 2a2110f26..64511275b 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -29,6 +29,7 @@ - Sean Freitag ([@cowboygneox](https://github.com/cowboygneox)) - Serge Weinstock ([@sweinst](https://github.com/sweinst)) - Virgil Dupras ([@hsoft](https://github.com/hsoft)) +- Wenguang Yang ([@yagweb](https://github.com/yagweb)) - Xavier Dupré ([@sdpython](https://github.com/sdpython)) - Zane Purvis ([@zanedp](https://github.com/zanedp)) - ([@ArvidJB](https://github.com/ArvidJB)) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9161b3977..e55ed6245 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Added Embedded tests on Appveyor (#353) - Added PY3 settings to configuration-manager (#346) - Added `Slack` chat (#384)(#383)(#386) +- Added function of passing an arbitrary .NET object as the value + of an attribute of PyObject (#370)(#373) ### Changed diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index a2e92ed19..ef011d044 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -65,6 +65,7 @@ pdbonly + ..\..\packages\NUnit.3.6.0\lib\net40\nunit.framework.dll @@ -76,6 +77,7 @@ + diff --git a/src/embed_tests/dynamic.cs b/src/embed_tests/dynamic.cs new file mode 100644 index 000000000..c70fe203c --- /dev/null +++ b/src/embed_tests/dynamic.cs @@ -0,0 +1,122 @@ +using System; +using System.Text; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + [TestFixture] + public class dynamicTest + { + private Py.GILState gil; + + [SetUp] + public void SetUp() + { + gil = Py.GIL(); + } + + [TearDown] + public void TearDown() + { + gil.Dispose(); + } + + /// + /// Set the attribute of a pyobject with a .NET object. + /// + [Test] + public void AssignObject() + { + StringBuilder stream = new StringBuilder(); + dynamic sys = Py.Import("sys"); + sys.testattr = stream; + // Check whether there are the same object. + var _stream = sys.testattr.AsManagedObject(typeof(StringBuilder)); + Assert.AreEqual(_stream, stream); + + PythonEngine.RunSimpleString( + "import sys\n" + + "sys.testattr.Append('Hello!')\n"); + Assert.AreEqual(stream.ToString(), "Hello!"); + } + + /// + /// Set the attribute of a pyobject to null. + /// + [Test] + public void AssignNone() + { + dynamic sys = Py.Import("sys"); + sys.testattr = new StringBuilder(); + Assert.IsNotNull(sys.testattr); + + sys.testattr = null; + Assert.IsNull(sys.testattr); + } + + /// + /// Check whether we can get the attr of a python object when the + /// value of attr is a PyObject. + /// + [Test] + public void AssignPyObject() + { + dynamic sys = Py.Import("sys"); + dynamic io = Py.Import("io"); + sys.testattr = io.StringIO(); + dynamic bb = sys.testattr; //Get the PyObject + bb.write("Hello!"); + Assert.AreEqual(bb.getvalue().ToString(), "Hello!"); + } + + /// + /// Pass the .NET object in Python side. + /// + [Test] + public void PassObjectInPython() + { + StringBuilder stream = new StringBuilder(); + dynamic sys = Py.Import("sys"); + sys.testattr1 = stream; + + //Pass the .NET object in Python side + PythonEngine.RunSimpleString( + "import sys\n" + + "sys.testattr2 = sys.testattr1\n" + ); + + //Compare in Python + PythonEngine.RunSimpleString( + "import sys\n" + + "sys.testattr3 = sys.testattr1 is sys.testattr2\n" + ); + Assert.AreEqual(sys.testattr3.ToString(), "True"); + + //Compare in .NET + Assert.AreEqual(sys.testattr1, sys.testattr2); + } + + /// + /// Pass the PyObject in .NET side + /// + [Test] + public void PassPyObjectInNet() + { + StringBuilder stream = new StringBuilder(); + dynamic sys = Py.Import("sys"); + sys.testattr1 = stream; + sys.testattr2 = sys.testattr1; + + //Compare in Python + PyObject res = PythonEngine.RunString( + "import sys\n" + + "sys.testattr3 = sys.testattr1 is sys.testattr2\n" + ); + Assert.AreEqual(sys.testattr3.ToString(), "True"); + + //Compare in .NET + Assert.AreEqual(sys.testattr1, sys.testattr2); + } + } +} diff --git a/src/runtime/pyobject.cs b/src/runtime/pyobject.cs index 3296d81f8..47f413409 100644 --- a/src/runtime/pyobject.cs +++ b/src/runtime/pyobject.cs @@ -887,30 +887,32 @@ public override int GetHashCode() return Runtime.PyObject_Hash(obj).ToInt32(); } - public override bool TryGetMember(GetMemberBinder binder, out object result) + + public long Refcount { - if (this.HasAttr(binder.Name)) - { - result = CheckNone(this.GetAttr(binder.Name)); - return true; - } - else + get { - return base.TryGetMember(binder, out result); + return Runtime.Refcount(obj); } } + + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + result = CheckNone(this.GetAttr(binder.Name)); + return true; + } + public override bool TrySetMember(SetMemberBinder binder, object value) { - if (this.HasAttr(binder.Name)) - { - this.SetAttr(binder.Name, (PyObject)value); - return true; - } - else + IntPtr ptr = Converter.ToPython(value, value?.GetType()); + int r = Runtime.PyObject_SetAttrString(obj, binder.Name, ptr); + if (r < 0) { - return base.TrySetMember(binder, value); + throw new PythonException(); } + Runtime.XDecref(ptr); + return true; } private void GetArgs(object[] inargs, out PyTuple args, out PyDict kwargs) From 2cb6742f48aa66ece98b0d9b10df0b7f057ebf19 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 17 Feb 2017 09:01:52 -0700 Subject: [PATCH 146/245] Add Coverity badge --- .gitignore | 3 +++ CHANGELOG.md | 1 + README.md | 3 +++ 3 files changed, 7 insertions(+) diff --git a/.gitignore b/.gitignore index 968a5c66a..6f813dcb0 100644 --- a/.gitignore +++ b/.gitignore @@ -54,3 +54,6 @@ _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm + +# Coverity +cov-int/ diff --git a/CHANGELOG.md b/CHANGELOG.md index e55ed6245..183692345 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Added `Slack` chat (#384)(#383)(#386) - Added function of passing an arbitrary .NET object as the value of an attribute of PyObject (#370)(#373) +- Added Coverity (#390) ### Changed diff --git a/README.md b/README.md index c66e8eef8..6a721e70f 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ [![appveyor shield][]](https://ci.appveyor.com/project/pythonnet/pythonnet/branch/master) [![travis shield][]](https://travis-ci.org/pythonnet/pythonnet) [![codecov shield][]](https://codecov.io/github/pythonnet/pythonnet) +[![coverity shield][]](https://scan.coverity.com/projects/pythonnet) [![license shield][]](./LICENSE) [![pypi package version][]](https://pypi.python.org/pypi/pythonnet) @@ -86,6 +87,8 @@ int32 [codecov shield]: https://img.shields.io/codecov/c/github/pythonnet/pythonnet/master.svg?label=Codecov +[coverity shield]: https://img.shields.io/coverity/scan/7830.svg + [license shield]: https://img.shields.io/badge/license-MIT-blue.svg?maxAge=3600 [pypi package version]: https://img.shields.io/pypi/v/pythonnet.svg From 3212cfe5cfcb806203d034936026924e88cd0a3c Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 20 Feb 2017 15:44:26 -0700 Subject: [PATCH 147/245] Clean-up CHANGELOG --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 183692345..546caf842 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Added `Slack` chat (#384)(#383)(#386) - Added function of passing an arbitrary .NET object as the value of an attribute of PyObject (#370)(#373) -- Added Coverity (#390) +- Added `Coverity scan` (#390) ### Changed @@ -48,7 +48,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. ## [2.2.1][] - 2017-01-26 -`v2.2.0` had a release issue on pypi. Bumped to `v2.2.1` +- `v2.2.0` had a release issue on pypi. Bumped to `v2.2.1` ### Added @@ -114,7 +114,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. ## [2.0.0][] - 2015-06-26 - Release +- Release ## 2.0.0-alpha.2 From f6d176ce43e1d3d15e55f35911da91b656293f1e Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 20 Feb 2017 19:11:47 -0700 Subject: [PATCH 148/245] Standardize Python.Test fixture location Ensures that Python.Test is output to same location on both Linux and Windows as part of build. .gitkeep to be ensure folder is part of version control. Can be removed if any file is added to it. --- .travis.yml | 6 +----- appveyor.yml | 5 ----- src/testing/Python.Test.csproj | 2 +- src/tests/conftest.py | 9 +++++++-- src/tests/fixtures/.gitkeep | 0 5 files changed, 9 insertions(+), 13 deletions(-) create mode 100644 src/tests/fixtures/.gitkeep diff --git a/.travis.yml b/.travis.yml index 13eea9516..bd3b9fdf7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,17 +30,13 @@ addons: - ca-certificates-mono before_install: - # Set-up location where `Python.Test.dll` will be output - - export PYTHONPATH=`pwd`:$PYTHONPATH - # Set-up dll path for embedded tests - PY_LIBDIR=$(python -c 'import sysconfig; print(sysconfig.get_config_var("LIBDIR"))') - export LD_LIBRARY_PATH=$PY_LIBDIR:$LD_LIBRARY_PATH install: - pip install --upgrade -r requirements.txt - # `setup.py install` works too, but need to deal with `Python.Test` PATH - - coverage run setup.py build_ext --inplace + - coverage run setup.py install script: - python -m pytest diff --git a/appveyor.yml b/appveyor.yml index a839e2eea..9fb2bb15f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -19,9 +19,6 @@ environment: - PYTHON_VERSION: 3.6 init: - # Prepare Environment - - mkdir C:\testdir - # Update Environment Variables based on matrix/platform - set PY_VER=%PYTHON_VERSION:.=% - set PYTHON=C:\PYTHON%PY_VER% @@ -44,8 +41,6 @@ build_script: test_script: - pip install --no-index --find-links=.\dist\ pythonnet - - ps: Copy-Item .\src\testing\bin\Python.Test.dll C:\testdir\ - - ps: .\ci\appveyor_run_tests.ps1 - ps: .\ci\appveyor_build_recipe.ps1 diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index 4ed9db680..f135ff9c5 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -103,7 +103,7 @@ $(TargetDir)$(TargetName).pdb - + diff --git a/src/tests/conftest.py b/src/tests/conftest.py index 7e86f87ae..534334491 100644 --- a/src/tests/conftest.py +++ b/src/tests/conftest.py @@ -5,13 +5,18 @@ """Helpers for testing.""" import ctypes +import os import sys import sysconfig import clr -# Add path for Python.Test & Add References -sys.path.append('C:/testdir/') +# Add path for `Python.Test` +cwd = os.path.dirname(__file__) +fixtures = os.path.join(cwd, 'fixtures') +sys.path.append(fixtures) + +# Add References for tests clr.AddReference("Python.Test") clr.AddReference("System.Collections") clr.AddReference("System.Data") diff --git a/src/tests/fixtures/.gitkeep b/src/tests/fixtures/.gitkeep new file mode 100644 index 000000000..e69de29bb From c0fb3f274328b35da8af4cd231986cbfe623f7b0 Mon Sep 17 00:00:00 2001 From: yagweb Date: Tue, 21 Feb 2017 20:44:28 +0800 Subject: [PATCH 149/245] Add unittest for Overflow/across AppDomains Exceptions reproduction (#393) First exception shows issue from #376 --- src/embed_tests/pyinitialize.cs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/embed_tests/pyinitialize.cs b/src/embed_tests/pyinitialize.cs index bfd95aaab..ba2578266 100644 --- a/src/embed_tests/pyinitialize.cs +++ b/src/embed_tests/pyinitialize.cs @@ -36,5 +36,33 @@ public static void StartAndStopTwice() PythonEngine.Initialize(); PythonEngine.Shutdown(); } + + [Test] + [Ignore("System.OverflowException : Arithmetic operation resulted in an overflow")] + //[Ignore("System.ArgumentException : Cannot pass a GCHandle across AppDomains")] + public void ReInitialize() + { + string code = "from System import Int32\n"; + PythonEngine.Initialize(); + using (Py.GIL()) + { + //import any class or struct from .NET + PythonEngine.RunSimpleString(code); + } + PythonEngine.Shutdown(); + + PythonEngine.Initialize(); + using (Py.GIL()) + { + //Import a class/struct from .NET + //This class/struct must be imported during the first initialization. + PythonEngine.RunSimpleString(code); + //Create an instance of the class/struct + //System.OverflowException Exception will be raised here. + //If replacing int with Int64, OverflowException will be replaced with AppDomain exception. + PythonEngine.RunSimpleString("Int32(1)"); + } + PythonEngine.Shutdown(); + } } } From 2871d1be4ebaa2a919073ca1191084c658da8d91 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 06:58:13 -0700 Subject: [PATCH 150/245] Re-order Initialize tests --- src/embed_tests/pyinitialize.cs | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/src/embed_tests/pyinitialize.cs b/src/embed_tests/pyinitialize.cs index ba2578266..6a766ce1d 100644 --- a/src/embed_tests/pyinitialize.cs +++ b/src/embed_tests/pyinitialize.cs @@ -5,16 +5,18 @@ namespace Python.EmbeddingTest { public class PyInitializeTest { + /// + /// Tests issue with multiple simple Initialize/Shutdowns. + /// Fixed by #343 + /// [Test] - public static void LoadSpecificArgs() + public static void StartAndStopTwice() { - var args = new[] { "test1", "test2" }; - using (new PythonEngine(args)) - using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) - { - Assert.AreEqual(args[0], argv[0].ToString()); - Assert.AreEqual(args[1], argv[1].ToString()); - } + PythonEngine.Initialize(); + PythonEngine.Shutdown(); + + PythonEngine.Initialize(); + PythonEngine.Shutdown(); } [Test] @@ -28,13 +30,15 @@ public static void LoadDefaultArgs() } [Test] - public static void StartAndStopTwice() + public static void LoadSpecificArgs() { - PythonEngine.Initialize(); - PythonEngine.Shutdown(); - - PythonEngine.Initialize(); - PythonEngine.Shutdown(); + var args = new[] { "test1", "test2" }; + using (new PythonEngine(args)) + using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) + { + Assert.AreEqual(args[0], argv[0].ToString()); + Assert.AreEqual(args[1], argv[1].ToString()); + } } [Test] From bd1a27eb98268af0a06bc51df3553df0191fc356 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 07:00:22 -0700 Subject: [PATCH 151/245] Add documentation and ref to ReInitialize test --- src/embed_tests/pyinitialize.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/embed_tests/pyinitialize.cs b/src/embed_tests/pyinitialize.cs index 6a766ce1d..8a172fe3e 100644 --- a/src/embed_tests/pyinitialize.cs +++ b/src/embed_tests/pyinitialize.cs @@ -41,8 +41,13 @@ public static void LoadSpecificArgs() } } + /// + /// Failing test demonstrating current issue with OverflowException (#376) + /// and ArgumentException issue after that one is fixed. + /// More complex version of StartAndStopTwice test + /// [Test] - [Ignore("System.OverflowException : Arithmetic operation resulted in an overflow")] + [Ignore("GH#376: System.OverflowException : Arithmetic operation resulted in an overflow")] //[Ignore("System.ArgumentException : Cannot pass a GCHandle across AppDomains")] public void ReInitialize() { From 38af8d15390f0fe2fbff6faceb806420d101c863 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 07:06:21 -0700 Subject: [PATCH 152/245] Split and re-order TestPyTupleIsTupleType test --- src/embed_tests/pytuple.cs | 39 ++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/pytuple.cs index 18a6ea344..e555d4dfa 100644 --- a/src/embed_tests/pytuple.cs +++ b/src/embed_tests/pytuple.cs @@ -5,6 +5,33 @@ namespace Python.EmbeddingTest { public class PyTupleTest { + /// + /// Test IsTupleType without having to Initialize a tuple. + /// PyTuple constructor use IsTupleType. This decouples the tests. + /// + [Test] + public void TestStringIsTupleType() + { + using (Py.GIL()) + { + var s = new PyString("foo"); + Assert.IsFalse(PyTuple.IsTupleType(s)); + } + } + + /// + /// Test IsTupleType with Tuple. + /// + [Test] + public void TestPyTupleIsTupleType() + { + using (Py.GIL()) + { + var t = new PyTuple(); + Assert.IsTrue(PyTuple.IsTupleType(t)); + } + } + [Test] public void TestPyTupleEmpty() { @@ -39,18 +66,6 @@ public void TestPyTupleValidAppend() } } - [Test] - public void TestPyTupleIsTupleType() - { - using (Py.GIL()) - { - var s = new PyString("foo"); - var t = new PyTuple(); - Assert.IsTrue(PyTuple.IsTupleType(t)); - Assert.IsFalse(PyTuple.IsTupleType(s)); - } - } - [Test] public void TestPyTupleStringConvert() { From e75d1c277f54cd272632b82d05d84a69f1bb05fd Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 07:17:30 -0700 Subject: [PATCH 153/245] Skip PyTuple test with AppDomain issue This skip removes the issue from all PY3 on Travis/AppVeyor. PY27 still has issue randomly on both Travis/AppVeyor x86, x64,. --- src/embed_tests/pytuple.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/pytuple.cs index e555d4dfa..ef8aaadca 100644 --- a/src/embed_tests/pytuple.cs +++ b/src/embed_tests/pytuple.cs @@ -42,7 +42,15 @@ public void TestPyTupleEmpty() } } + /// + /// FIXME: Unable to unload AppDomain, Unload thread timed out. + /// Seen on Travis/AppVeyor on both PY2 and PY3. Causes Embedded_Tests + /// to hang after they are finished for ~40 seconds until nunit3 forces + /// a timeout on unloading tests. Doesn't fail the tests though but + /// greatly slows down CI. nunit2 silently has this issue. + /// [Test] + [Ignore("GH#397: Travis/AppVeyor: Unable to unload AppDomain, Unload thread timed out")] public void TestPyTupleInvalidAppend() { using (Py.GIL()) @@ -93,6 +101,9 @@ public void TestPyTupleValidConvert() } } + /// + /// FIXME: Possible source of intermittent AppVeyor PY27: Unable to unload AppDomain. + /// [Test] public void TestNewPyTupleFromPyTuple() { From e7c94dfd774699a9cfe4a3360f1139051ac4097f Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 07:26:33 -0700 Subject: [PATCH 154/245] Clean-up embedded tests Clean-up embedded tests comments and variable types Remove TestFixture attribute. Optional since NUnit 2.5 https://nunit.org/index.php?p=testFixture&r=2.6.4 --- src/embed_tests/dynamic.cs | 23 +++++++++++------------ src/embed_tests/pyimport.cs | 1 - src/embed_tests/pyinitialize.cs | 15 ++++++++------- src/embed_tests/pyiter.cs | 1 + src/embed_tests/pylong.cs | 1 + src/embed_tests/pyobject.cs | 1 + src/embed_tests/pythonexception.cs | 1 - src/embed_tests/pytuple.cs | 1 + 8 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/embed_tests/dynamic.cs b/src/embed_tests/dynamic.cs index c70fe203c..25d70f2c5 100644 --- a/src/embed_tests/dynamic.cs +++ b/src/embed_tests/dynamic.cs @@ -5,7 +5,6 @@ namespace Python.EmbeddingTest { - [TestFixture] public class dynamicTest { private Py.GILState gil; @@ -23,16 +22,16 @@ public void TearDown() } /// - /// Set the attribute of a pyobject with a .NET object. + /// Set the attribute of a PyObject with a .NET object. /// [Test] public void AssignObject() { - StringBuilder stream = new StringBuilder(); + var stream = new StringBuilder(); dynamic sys = Py.Import("sys"); sys.testattr = stream; // Check whether there are the same object. - var _stream = sys.testattr.AsManagedObject(typeof(StringBuilder)); + dynamic _stream = sys.testattr.AsManagedObject(typeof(StringBuilder)); Assert.AreEqual(_stream, stream); PythonEngine.RunSimpleString( @@ -42,7 +41,7 @@ public void AssignObject() } /// - /// Set the attribute of a pyobject to null. + /// Set the attribute of a PyObject to null. /// [Test] public void AssignNone() @@ -76,24 +75,24 @@ public void AssignPyObject() [Test] public void PassObjectInPython() { - StringBuilder stream = new StringBuilder(); + var stream = new StringBuilder(); dynamic sys = Py.Import("sys"); sys.testattr1 = stream; - //Pass the .NET object in Python side + // Pass the .NET object in Python side PythonEngine.RunSimpleString( "import sys\n" + "sys.testattr2 = sys.testattr1\n" ); - //Compare in Python + // Compare in Python PythonEngine.RunSimpleString( "import sys\n" + "sys.testattr3 = sys.testattr1 is sys.testattr2\n" ); Assert.AreEqual(sys.testattr3.ToString(), "True"); - //Compare in .NET + // Compare in .NET Assert.AreEqual(sys.testattr1, sys.testattr2); } @@ -103,19 +102,19 @@ public void PassObjectInPython() [Test] public void PassPyObjectInNet() { - StringBuilder stream = new StringBuilder(); + var stream = new StringBuilder(); dynamic sys = Py.Import("sys"); sys.testattr1 = stream; sys.testattr2 = sys.testattr1; - //Compare in Python + // Compare in Python PyObject res = PythonEngine.RunString( "import sys\n" + "sys.testattr3 = sys.testattr1 is sys.testattr2\n" ); Assert.AreEqual(sys.testattr3.ToString(), "True"); - //Compare in .NET + // Compare in .NET Assert.AreEqual(sys.testattr1, sys.testattr2); } } diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index ebdc5b125..7751d37ce 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -17,7 +17,6 @@ namespace Python.EmbeddingTest /// | | - __init__.py /// | | - one.py /// - [TestFixture] public class PyImportTest { private IntPtr gs; diff --git a/src/embed_tests/pyinitialize.cs b/src/embed_tests/pyinitialize.cs index 8a172fe3e..2f9aae2c7 100644 --- a/src/embed_tests/pyinitialize.cs +++ b/src/embed_tests/pyinitialize.cs @@ -1,3 +1,4 @@ +using System; using NUnit.Framework; using Python.Runtime; @@ -51,11 +52,11 @@ public static void LoadSpecificArgs() //[Ignore("System.ArgumentException : Cannot pass a GCHandle across AppDomains")] public void ReInitialize() { - string code = "from System import Int32\n"; + var code = "from System import Int32\n"; PythonEngine.Initialize(); using (Py.GIL()) { - //import any class or struct from .NET + // Import any class or struct from .NET PythonEngine.RunSimpleString(code); } PythonEngine.Shutdown(); @@ -63,12 +64,12 @@ public void ReInitialize() PythonEngine.Initialize(); using (Py.GIL()) { - //Import a class/struct from .NET - //This class/struct must be imported during the first initialization. + // Import a class/struct from .NET + // This class/struct must be imported during the first initialization. PythonEngine.RunSimpleString(code); - //Create an instance of the class/struct - //System.OverflowException Exception will be raised here. - //If replacing int with Int64, OverflowException will be replaced with AppDomain exception. + // Create an instance of the class/struct + // System.OverflowException Exception will be raised here. + // If replacing int with Int64, OverflowException will be replaced with AppDomain exception. PythonEngine.RunSimpleString("Int32(1)"); } PythonEngine.Shutdown(); diff --git a/src/embed_tests/pyiter.cs b/src/embed_tests/pyiter.cs index b110903f6..b896ab4c9 100644 --- a/src/embed_tests/pyiter.cs +++ b/src/embed_tests/pyiter.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using NUnit.Framework; using Python.Runtime; diff --git a/src/embed_tests/pylong.cs b/src/embed_tests/pylong.cs index 37cf1042d..0c57a0a74 100644 --- a/src/embed_tests/pylong.cs +++ b/src/embed_tests/pylong.cs @@ -1,3 +1,4 @@ +using System; using NUnit.Framework; using Python.Runtime; diff --git a/src/embed_tests/pyobject.cs b/src/embed_tests/pyobject.cs index f114d3d9e..be35ed3ca 100644 --- a/src/embed_tests/pyobject.cs +++ b/src/embed_tests/pyobject.cs @@ -1,3 +1,4 @@ +using System; using NUnit.Framework; using Python.Runtime; diff --git a/src/embed_tests/pythonexception.cs b/src/embed_tests/pythonexception.cs index 7811bd37b..2a0021648 100644 --- a/src/embed_tests/pythonexception.cs +++ b/src/embed_tests/pythonexception.cs @@ -11,7 +11,6 @@ namespace Python.EmbeddingTest /// Keeping this in the old-style SetUp/TearDown /// to ensure that setup still works. /// - [TestFixture] public class PythonExceptionTest { private IntPtr gs; diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/pytuple.cs index ef8aaadca..ef72d2ea9 100644 --- a/src/embed_tests/pytuple.cs +++ b/src/embed_tests/pytuple.cs @@ -1,3 +1,4 @@ +using System; using NUnit.Framework; using Python.Runtime; From c99c5f21656c7c257c2e18395eaeddbc3b85d107 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 07:53:39 -0700 Subject: [PATCH 155/245] Fix conda build log stderr->stdout Recent conda-build update added a new log output to log:info. Powershell interprets this as an ERROR since its on STDERR. Prevent accidental auto-update & display INFO before building. Would have made debugging this psudo-error easier. --- ci/appveyor_build_recipe.ps1 | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ci/appveyor_build_recipe.ps1 b/ci/appveyor_build_recipe.ps1 index 00d28ce88..c767091f3 100644 --- a/ci/appveyor_build_recipe.ps1 +++ b/ci/appveyor_build_recipe.ps1 @@ -19,10 +19,14 @@ if ($env:APPVEYOR_PULL_REQUEST_NUMBER) { Write-Host "Starting conda install" -ForegroundColor "Green" conda config --set always_yes True conda config --set changeps1 False + conda config --set auto_update_conda False conda install conda-build jinja2 anaconda-client --quiet + conda info + # why `2>&1 | %{ "$_" }`? Redirect STDERR to STDOUT + # see: http://stackoverflow.com/a/20950421/5208670 Write-Host "Starting conda build recipe" -ForegroundColor "Green" - conda build conda.recipe --dirty --quiet + conda build conda.recipe --quiet 2>&1 | %{ "$_" } $CONDA_PKG=(conda build conda.recipe --output) Copy-Item $CONDA_PKG .\dist\ From 5e27c67f0119d769f4deb19d9da46bd627126d8e Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 09:45:41 -0700 Subject: [PATCH 156/245] Quiet AppVeyor pip/nuget installs Reduce verbosity to make relevant information easier to find. Errors and Warnings are still displayed. Travis doesn't need this since they have log folding. --- appveyor.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 9fb2bb15f..e973ac581 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -28,10 +28,10 @@ init: - set PATH=%PYTHON%;%PYTHON%\Scripts;%PATH% install: - - pip install --upgrade -r requirements.txt + - pip install --upgrade -r requirements.txt --quiet # Install OpenCover. Can't put on `packages.config`, not Mono compatible - - .\tools\nuget\nuget.exe install OpenCover -OutputDirectory packages + - .\tools\nuget\nuget.exe install OpenCover -OutputDirectory packages -Verbosity quiet build_script: # Create clean `sdist`. Only used for releases From cbafe1ed8b6438a41726740fa0174225c3c121ea Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 12:04:40 -0700 Subject: [PATCH 157/245] Allow private env:var to force conda build To trigger conda build, just add/update private env:vars FORCE_CONDA_BUILD on link below. Easier to debug and no need to edit appveyor yml/ps1 https://ci.appveyor.com/project/USER_NAME/pythonnet/settings/environment --- ci/appveyor_build_recipe.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/appveyor_build_recipe.ps1 b/ci/appveyor_build_recipe.ps1 index c767091f3..278e292b0 100644 --- a/ci/appveyor_build_recipe.ps1 +++ b/ci/appveyor_build_recipe.ps1 @@ -11,7 +11,7 @@ if ($env:PLATFORM -eq "x86"){ $env:CONDA_BLD = "$env:CONDA_BLD" + "-x64" } -if ($env:APPVEYOR_PULL_REQUEST_NUMBER) { +if ($env:APPVEYOR_PULL_REQUEST_NUMBER -or $env:FORCE_CONDA_BUILD -eq "True") { # Update PATH, and keep a copy to restore at end of this PowerShell script $old_path = $env:path $env:path = "$env:CONDA_BLD;$env:CONDA_BLD\Scripts;" + $env:path From e753b722577510d0de34b3c29d2adf37b6586d2b Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 12:22:37 -0700 Subject: [PATCH 158/245] Update AUTHORS Add names to a few more contributors --- AUTHORS.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/AUTHORS.md b/AUTHORS.md index 64511275b..09358586e 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -12,11 +12,14 @@ ## Contributors +- Arvid JB ([@ArvidJB](https://github.com/ArvidJB)) - Bradley Friedman ([@leith-bartrich](https://github.com/leith-bartrich)) - Christian Heimes ([@tiran](https://github.com/tiran)) - Christoph Gohlke ([@cgohlke](https://github.com/cgohlke)) +- Daniel Fernandez ([@fdanny](https://github.com/fdanny)) - Daniel Santana ([@dgsantana](https://github.com/dgsantana)) - David Lechner ([@dlech](https://github.com/dlech)) +- Dmitriy Se ([@dmitriyse](https://github.com/dmitriyse)) - He-chien Tsai ([@t3476](https://github.com/t3476)) - Jeff Reback ([@jreback](https://github.com/jreback)) - Joe Frayne ([@jfrayne](https://github.com/jfrayne)) @@ -32,10 +35,7 @@ - Wenguang Yang ([@yagweb](https://github.com/yagweb)) - Xavier Dupré ([@sdpython](https://github.com/sdpython)) - Zane Purvis ([@zanedp](https://github.com/zanedp)) -- ([@ArvidJB](https://github.com/ArvidJB)) - ([@bltribble](https://github.com/bltribble)) -- ([@dmitriyse](https://github.com/dmitriyse)) -- ([@fdanny](https://github.com/fdanny)) - ([@omnicognate](https://github.com/omnicognate)) - ([@rico-chet](https://github.com/rico-chet)) - ([@rmadsen-ks](https://github.com/rmadsen-ks)) From 3c693714541b5aee5209a0192fb24c29b0e740fb Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 13:39:22 -0700 Subject: [PATCH 159/245] Rename TearDown to Dispose Easier for future possible migration to other frameworks --- src/embed_tests/dynamic.cs | 2 +- src/embed_tests/pyimport.cs | 2 +- src/embed_tests/pythonexception.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/embed_tests/dynamic.cs b/src/embed_tests/dynamic.cs index 25d70f2c5..8338d68f6 100644 --- a/src/embed_tests/dynamic.cs +++ b/src/embed_tests/dynamic.cs @@ -16,7 +16,7 @@ public void SetUp() } [TearDown] - public void TearDown() + public void Dispose() { gil.Dispose(); } diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index 7751d37ce..43bea1427 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -39,7 +39,7 @@ public void SetUp() } [TearDown] - public void TearDown() + public void Dispose() { PythonEngine.ReleaseLock(gs); PythonEngine.Shutdown(); diff --git a/src/embed_tests/pythonexception.cs b/src/embed_tests/pythonexception.cs index 2a0021648..bdae9db9e 100644 --- a/src/embed_tests/pythonexception.cs +++ b/src/embed_tests/pythonexception.cs @@ -23,7 +23,7 @@ public void SetUp() } [TearDown] - public void TearDown() + public void Dispose() { PythonEngine.ReleaseLock(gs); PythonEngine.Shutdown(); From a9e2fe78f353211b3114377b7fbd3637b0fe59ca Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 13:45:49 -0700 Subject: [PATCH 160/245] Relocate Embedded tests fixtures Each test type should contain its own fixtures. Reduces weird dependency of each testing framework --- src/{tests => embed_tests/fixtures}/PyImportTest/__init__.py | 0 src/{tests => embed_tests/fixtures}/PyImportTest/sysargv.py | 0 .../fixtures}/PyImportTest/test/__init__.py | 0 src/{tests => embed_tests/fixtures}/PyImportTest/test/one.py | 0 src/embed_tests/pyimport.cs | 4 ++-- 5 files changed, 2 insertions(+), 2 deletions(-) rename src/{tests => embed_tests/fixtures}/PyImportTest/__init__.py (100%) rename src/{tests => embed_tests/fixtures}/PyImportTest/sysargv.py (100%) rename src/{tests => embed_tests/fixtures}/PyImportTest/test/__init__.py (100%) rename src/{tests => embed_tests/fixtures}/PyImportTest/test/one.py (100%) diff --git a/src/tests/PyImportTest/__init__.py b/src/embed_tests/fixtures/PyImportTest/__init__.py similarity index 100% rename from src/tests/PyImportTest/__init__.py rename to src/embed_tests/fixtures/PyImportTest/__init__.py diff --git a/src/tests/PyImportTest/sysargv.py b/src/embed_tests/fixtures/PyImportTest/sysargv.py similarity index 100% rename from src/tests/PyImportTest/sysargv.py rename to src/embed_tests/fixtures/PyImportTest/sysargv.py diff --git a/src/tests/PyImportTest/test/__init__.py b/src/embed_tests/fixtures/PyImportTest/test/__init__.py similarity index 100% rename from src/tests/PyImportTest/test/__init__.py rename to src/embed_tests/fixtures/PyImportTest/test/__init__.py diff --git a/src/tests/PyImportTest/test/one.py b/src/embed_tests/fixtures/PyImportTest/test/one.py similarity index 100% rename from src/tests/PyImportTest/test/one.py rename to src/embed_tests/fixtures/PyImportTest/test/one.py diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index 43bea1427..17547d69a 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -10,7 +10,7 @@ namespace Python.EmbeddingTest /// /// /// Keeping in old-style SetUp/TearDown due to required SetUp. - /// The required directory structure was added to .\pythonnet\src\tests\ directory: + /// The required directory structure was added to .\pythonnet\src\embed_tests\fixtures\ directory: /// + PyImportTest/ /// | - __init__.py /// | + test/ @@ -30,7 +30,7 @@ public void SetUp() /* Append the tests directory to sys.path * using reflection to circumvent the private * modifiers placed on most Runtime methods. */ - const string s = "../../tests"; + const string s = "../fixtures"; string testPath = Path.Combine(TestContext.CurrentContext.TestDirectory, s); IntPtr str = Runtime.Runtime.PyString_FromString(testPath); From 02a8a348e8249a74601d30fa26b46631279cc8fe Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 17:31:31 -0700 Subject: [PATCH 161/245] Update LICENSE year & include in recipe --- LICENSE | 2 +- conda.recipe/meta.yaml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 0535829ff..e344a0795 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2017 the contributors of the "Python for .NET" project +Copyright (c) 2006-2017 the contributors of the "Python for .NET" project Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), diff --git a/conda.recipe/meta.yaml b/conda.recipe/meta.yaml index da62edc90..32bc544f6 100644 --- a/conda.recipe/meta.yaml +++ b/conda.recipe/meta.yaml @@ -26,3 +26,4 @@ test: about: home: https://github.com/pythonnet/pythonnet license: MIT + license_file: LICENSE From 0e5e58edd0cf0d36660e909662dcca5486161851 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 15:36:54 -0700 Subject: [PATCH 162/245] Update conda-recipe version Get it from recipe file instead of git-tag. --- conda.recipe/meta.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conda.recipe/meta.yaml b/conda.recipe/meta.yaml index 32bc544f6..eaa8747b2 100644 --- a/conda.recipe/meta.yaml +++ b/conda.recipe/meta.yaml @@ -1,6 +1,6 @@ package: name: pythonnet - version: {{ environ.get('GIT_DESCRIBE_TAG', '').replace('-dev', '.dev') }} + version: "2.3.0.dev1" build: skip: True # [not win] From 928717d3a1fc3fdee49eee5a0cd07780a35bd647 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 17:10:32 -0700 Subject: [PATCH 163/245] Add SharedAssemblyInfo & Update Assembly version Reset version back down to v2.x from v4.0.0.2 See link below for Semanctic Versioning & .NET https://codingforsmarties.wordpress.com/2016/01/21/how-to-version-assemblies-destined-for-nuget/ --- src/SharedAssemblyInfo.cs | 28 +++++++++++++++++ src/clrmodule/AssemblyInfo.cs | 39 ------------------------ src/clrmodule/ClrModule.cs | 3 +- src/clrmodule/Properties/AssemblyInfo.cs | 11 +++++++ src/clrmodule/clrmodule.csproj | 6 +++- src/console/AssemblyInfo.cs | 16 ---------- src/console/Console.csproj | 6 +++- src/console/Properties/AssemblyInfo.cs | 8 +++++ src/runtime/AssemblyInfo.cs | 15 --------- src/runtime/Properties/AssemblyInfo.cs | 11 +++++++ src/runtime/Python.Runtime.csproj | 6 +++- 11 files changed, 75 insertions(+), 74 deletions(-) create mode 100644 src/SharedAssemblyInfo.cs delete mode 100644 src/clrmodule/AssemblyInfo.cs create mode 100644 src/clrmodule/Properties/AssemblyInfo.cs delete mode 100644 src/console/AssemblyInfo.cs create mode 100644 src/console/Properties/AssemblyInfo.cs delete mode 100644 src/runtime/AssemblyInfo.cs create mode 100644 src/runtime/Properties/AssemblyInfo.cs diff --git a/src/SharedAssemblyInfo.cs b/src/SharedAssemblyInfo.cs new file mode 100644 index 000000000..24ba26862 --- /dev/null +++ b/src/SharedAssemblyInfo.cs @@ -0,0 +1,28 @@ +using System; +using System.Reflection; +using System.Resources; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("pythonnet")] +[assembly: AssemblyProduct("Python for .NET")] +[assembly: AssemblyCopyright("Copyright (c) 2006-2017 the contributors of the 'Python for .NET' project")] +[assembly: AssemblyTrademark("")] + +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("")] + +[assembly: CLSCompliant(true)] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version Information. Keeping it simple. May need to revisit for Nuget +// See: https://codingforsmarties.wordpress.com/2016/01/21/how-to-version-assemblies-destined-for-nuget/ +// AssemblyVersion can only be numeric +[assembly: AssemblyVersion("2.3.0")] diff --git a/src/clrmodule/AssemblyInfo.cs b/src/clrmodule/AssemblyInfo.cs deleted file mode 100644 index 669183255..000000000 --- a/src/clrmodule/AssemblyInfo.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. - -[assembly: AssemblyTitle("clrmodule")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("clrmodule")] -[assembly: AssemblyCopyright("Copyright © 2013")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. - -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM - -[assembly: Guid("ae10d6a4-55c2-482f-9716-9988e6c169e3")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] - -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/clrmodule/ClrModule.cs b/src/clrmodule/ClrModule.cs index 413b952eb..d24376a1f 100644 --- a/src/clrmodule/ClrModule.cs +++ b/src/clrmodule/ClrModule.cs @@ -52,7 +52,8 @@ public static void initclr() var pythonRuntimeName = new AssemblyName("Python.Runtime") { #if USE_PYTHON_RUNTIME_VERSION - Version = new Version("4.0.0.1"), + // Has no effect until SNK works. Keep updated anyways. + Version = new Version("2.3.0"), #endif CultureInfo = CultureInfo.InvariantCulture }; diff --git a/src/clrmodule/Properties/AssemblyInfo.cs b/src/clrmodule/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..939f4171f --- /dev/null +++ b/src/clrmodule/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("clrmodule")] +[assembly: AssemblyDescription("")] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ae10d6a4-55c2-482f-9716-9988e6c169e3")] diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index 435630d0e..6f44789d7 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -14,6 +14,7 @@ 1591 ..\..\ $(SolutionDir) + Properties true prompt @@ -72,7 +73,10 @@ - + + + Properties\SharedAssemblyInfo.cs + diff --git a/src/console/AssemblyInfo.cs b/src/console/AssemblyInfo.cs deleted file mode 100644 index 17d792c7a..000000000 --- a/src/console/AssemblyInfo.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Reflection; -using System.Resources; -using System.Runtime.InteropServices; -using System.Security.Permissions; - -[assembly: AssemblyProduct("Python for .NET")] -[assembly: AssemblyVersion("2.4.2.7")] -[assembly: AssemblyTitle("Python Console")] -[assembly: AssemblyDefaultAlias("python.exe")] -[assembly: CLSCompliant(true)] -[assembly: ComVisible(false)] -[assembly: AssemblyDescription("")] -[assembly: AssemblyCopyright("MIT License")] -[assembly: AssemblyFileVersion("2.0.0.4")] -[assembly: NeutralResourcesLanguage("en")] diff --git a/src/console/Console.csproj b/src/console/Console.csproj index cdee6893b..9fe44830c 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -14,6 +14,7 @@ 1591 ..\..\ $(SolutionDir) + Properties python-clear.ico prompt @@ -71,7 +72,10 @@ - + + + Properties\SharedAssemblyInfo.cs + diff --git a/src/console/Properties/AssemblyInfo.cs b/src/console/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..081ae0c94 --- /dev/null +++ b/src/console/Properties/AssemblyInfo.cs @@ -0,0 +1,8 @@ +using System.Reflection; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Python Console")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyDefaultAlias("python.exe")] diff --git a/src/runtime/AssemblyInfo.cs b/src/runtime/AssemblyInfo.cs deleted file mode 100644 index a357b81d9..000000000 --- a/src/runtime/AssemblyInfo.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Reflection; -using System.Resources; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -[assembly: AssemblyProduct("Python for .NET")] -[assembly: AssemblyVersion("4.0.0.1")] -[assembly: AssemblyDefaultAlias("Python.Runtime.dll")] -[assembly: CLSCompliant(true)] -[assembly: ComVisible(false)] -[assembly: AssemblyCopyright("MIT License")] -[assembly: AssemblyFileVersion("2.0.0.2")] -[assembly: NeutralResourcesLanguage("en")] -[assembly: InternalsVisibleTo("Python.EmbeddingTest")] diff --git a/src/runtime/Properties/AssemblyInfo.cs b/src/runtime/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..a5d33c7ab --- /dev/null +++ b/src/runtime/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Python for .NET")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyDefaultAlias("Python.Runtime.dll")] + +[assembly: InternalsVisibleTo("Python.EmbeddingTest")] diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index f1616dcd6..fd2281d58 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -14,6 +14,7 @@ 1591 ..\..\ $(SolutionDir) + Properties true false @@ -73,7 +74,10 @@ - + + + Properties\SharedAssemblyInfo.cs + From 5a7d297837a100da4674fd6306cd708d215b2d8c Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 20:09:31 -0700 Subject: [PATCH 164/245] Add .bumpversion Configuration based from gh:bumpversion:issues:77#issuecomment-130696156 Usage: bumpversion major -> increases major and adds `dev` if not present bumpversion minor -> increases minor and adds `dev` if not present bumpversion release -> drop the `dev` portion --- .bumpversion.cfg | 29 +++++++++++++++++++++++++++++ .editorconfig | 5 +++++ setup.cfg | 4 ++++ 3 files changed, 38 insertions(+) create mode 100644 .bumpversion.cfg diff --git a/.bumpversion.cfg b/.bumpversion.cfg new file mode 100644 index 000000000..f79dfb480 --- /dev/null +++ b/.bumpversion.cfg @@ -0,0 +1,29 @@ +[bumpversion] +current_version = 2.3.0.dev1 +parse = (?P\d+)\.(?P\d+)\.(?P\d+)(\.(?P[a-z]+)(?P\d+))? +serialize = + {major}.{minor}.{patch}.{release}{dev} + {major}.{minor}.{patch} + +[bumpversion:part:release] +optional_value = dummy +values = + dev + dummy + +[bumpversion:part:dev] + +[bumpversion:file:setup.py] + +[bumpversion:file:conda.recipe/meta.yaml] + +[bumpversion:file:src/runtime/resources/clr.py] + +[bumpversion:file:src/SharedAssemblyInfo.cs] +serialize = + {major}.{minor}.{patch} + +[bumpversion:file:src/clrmodule/ClrModule.cs] +serialize = + {major}.{minor}.{patch} + diff --git a/.editorconfig b/.editorconfig index ff0b3c71d..25636a549 100644 --- a/.editorconfig +++ b/.editorconfig @@ -22,3 +22,8 @@ indent_size = 2 # Solution [*.sln] indent_style = tab + +# bumpversion reformats itself after every bump +[.bumpversion.cfg] +trim_trailing_whitespace = false +indent_style = tab diff --git a/setup.cfg b/setup.cfg index f05de8217..d1a72ff31 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,4 +1,8 @@ +# [bumpversion] comments. bumpversion deleted all comments on its file. # Don't combine `.bumpversion.cfg` with `setup.cfg`. Messes up formatting. +# Don't use `first_value = 1`. It will break `release` bump +# Keep `optional = dummy` needed to bump to release. +# See: https://github.com/peritus/bumpversion/issues/59 [tool:pytest] xfail_strict = True From b7a3c7ea18fa49d2977ed142e559e96f6ae6af55 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 18 Apr 2016 12:56:47 -0700 Subject: [PATCH 165/245] Add object overload test --- src/testing/methodtest.cs | 15 +++++++++++++++ src/tests/test_method.py | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/testing/methodtest.cs b/src/testing/methodtest.cs index 7634c4839..76546f0d3 100644 --- a/src/testing/methodtest.cs +++ b/src/testing/methodtest.cs @@ -116,6 +116,21 @@ public static int[] TestOverloadedParams(int v, int[] args) return args; } + public static string TestOverloadedNoObject(int i) + { + return "Got int"; + } + + public static string TestOverloadedObject(int i) + { + return "Got int"; + } + + public static string TestOverloadedObject(object o) + { + return "Got object"; + } + public static bool TestStringOutParams(string s, out string s1) { s1 = "output string"; diff --git a/src/tests/test_method.py b/src/tests/test_method.py index e29986969..41171df82 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -769,3 +769,25 @@ def test_wrong_overload(): res = System.Math.Max(System.Double(50.5), 50.1) assert res == 50.5 assert type(res) == float + + +def test_no_object_in_param(): + """Test that fix for #203 doesn't break behavior w/ no object overload""" + + res = MethodTest.TestOverloadedNoObject(5) + assert res == "Got int" + + with pytest.raises(TypeError): + MethodTest.TestOverloadedNoObject("test") + + +@pytest.mark.xfail(reason="Needs fixing. #203") +def test_object_in_param(): + """Test regression introduced by #151 in which Object method overloads + aren't being used. See #203 for issue.""" + + res = MethodTest.TestOverloadedObject(5) + assert res == "Got int" + + res = MethodTest.TestOverloadedObject("test") + assert res == "Got object" From 2cabc9f623dac83d83f0798102510670299fbbaf Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 22 May 2016 12:19:10 -0700 Subject: [PATCH 166/245] Add object type to methodbind --- src/runtime/methodbinder.cs | 2 +- src/tests/test_method.py | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/methodbinder.cs b/src/runtime/methodbinder.cs index b3df8448f..f0c58f34f 100644 --- a/src/runtime/methodbinder.cs +++ b/src/runtime/methodbinder.cs @@ -375,7 +375,7 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth if (clrtype != null) { var typematch = false; - if (pi[n].ParameterType != clrtype) + if ((pi[n].ParameterType != typeof(object)) && (pi[n].ParameterType != clrtype)) { IntPtr pytype = Converter.GetPythonTypeByAlias(pi[n].ParameterType); pyoptype = Runtime.PyObject_Type(op); diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 41171df82..2c59fedac 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -781,7 +781,6 @@ def test_no_object_in_param(): MethodTest.TestOverloadedNoObject("test") -@pytest.mark.xfail(reason="Needs fixing. #203") def test_object_in_param(): """Test regression introduced by #151 in which Object method overloads aren't being used. See #203 for issue.""" From 4071aa3c37ac45bb6fe40d23558f68922f9b7f3e Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 14 Feb 2017 23:26:49 -0700 Subject: [PATCH 167/245] Add more object overload method tests --- src/testing/methodtest.cs | 50 +++++++++++++++++++++++++++++++++++++++ src/tests/test_method.py | 29 +++++++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/src/testing/methodtest.cs b/src/testing/methodtest.cs index 76546f0d3..e76348ab4 100644 --- a/src/testing/methodtest.cs +++ b/src/testing/methodtest.cs @@ -131,6 +131,56 @@ public static string TestOverloadedObject(object o) return "Got object"; } + public static string TestOverloadedObjectTwo(int a, int b) + { + return "Got int-int"; + } + + public static string TestOverloadedObjectTwo(string a, string b) + { + return "Got string-string"; + } + + public static string TestOverloadedObjectTwo(string a, int b) + { + return "Got string-int"; + } + + public static string TestOverloadedObjectTwo(string a, object b) + { + return "Got string-object"; + } + + public static string TestOverloadedObjectTwo(int a, object b) + { + return "Got int-object"; + } + + public static string TestOverloadedObjectTwo(object a, int b) + { + return "Got object-int"; + } + + public static string TestOverloadedObjectTwo(object a, object b) + { + return "Got object-object"; + } + + public static string TestOverloadedObjectTwo(int a, string b) + { + return "Got int-string"; + } + + public static string TestOverloadedObjectThree(object a, int b) + { + return "Got object-int"; + } + + public static string TestOverloadedObjectThree(int a, object b) + { + return "Got int-object"; + } + public static bool TestStringOutParams(string s, out string s1) { s1 = "output string"; diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 2c59fedac..12c8cb13e 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -790,3 +790,32 @@ def test_object_in_param(): res = MethodTest.TestOverloadedObject("test") assert res == "Got object" + + +def test_object_in_multiparam(): + """Test method with object multiparams behaves""" + + res = MethodTest.TestOverloadedObjectTwo(5, 5) + assert res == "Got int-int" + + res = MethodTest.TestOverloadedObjectTwo(5, "foo") + assert res == "Got int-string" + + res = MethodTest.TestOverloadedObjectTwo("foo", 7.24) + assert res == "Got string-object" + + res = MethodTest.TestOverloadedObjectTwo("foo", "bar") + assert res == "Got string-string" + + res = MethodTest.TestOverloadedObjectTwo("foo", 5) + assert res == "Got string-int" + + res = MethodTest.TestOverloadedObjectTwo(7.24, 7.24) + assert res == "Got object-object" + + +def test_object_in_multiparam_exception(): + """Test method with object multiparams behaves""" + + with pytest.raises(TypeError): + MethodTest.TestOverloadedObjectThree("foo", "bar") From 9e3193b9726a8ba53fbfcb9cd228180dc8458ca9 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 22 Feb 2017 07:35:31 -0700 Subject: [PATCH 168/245] Update CHANGELOG --- CHANGELOG.md | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 546caf842..b68bc38a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,35 +9,45 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. ### Added -- Code Coverage (#345) -- Added `pysetargv` (#347) +- Added Code Coverage (#345) +- Added `PySys_SetArgvEx` (#347) - Added XML Documentation (#349) -- Added Embedded tests on Appveyor (#353) -- Added PY3 settings to configuration-manager (#346) -- Added `Slack` chat (#384)(#383)(#386) +- Added `Embedded_Tests` on AppVeyor (#353) +- Added PY3 settings to solution configuration-manager (#346) +- Added `Slack` (#384)(#383)(#386) - Added function of passing an arbitrary .NET object as the value - of an attribute of PyObject (#370)(#373) + of an attribute of `PyObject` (#370)(#373) - Added `Coverity scan` (#390) +- Added `bumpversion` for version control (#319)(#398) +- Added `tox` for local testing (#345) +- Added `requirements.txt` ### Changed -- Refactored `setup.py` (#337) -- Upgraded NUnit framework to 2.6.4 (#353) -- Completed refactor of Build Directives on `Runtime.cs` (#339) -- Refactor python unittests (#329) -- Unfroze Mono version on Travis (#345) +- Refactored python `unittests` (#329) +- Refactored python `setup.py` (#337) +- Refactored remaining of Build Directives on `runtime.cs` (#339) +- Refactored `Embedded_Tests` to make easier to write tests (#369) - Changed `unittests` to `pytest` (#368) -- Upgraded NUnit framework from 2.6.4 to 3.6.0 (#371) +- Upgraded NUnit framework from `2.6.3` to `3.5.0` (#341) +- Downgraded NUnit framework from `3.5.0` to `2.6.4` (#353) +- Upgraded NUnit framework from `2.6.4` to `3.6.0` (#371) +- Unfroze Mono version on Travis (#345) +- Changed `conda.recipe` build to only pull-requests (#345) ### Fixed -- Fixed crash during Initialization (#343) +- Fixed crash during Initialization (#262)(#343) - Fixed crash during Shutdown (#365) - Fixed multiple build warnings +- Fixed method signature match for Object Type (#203)(#377) +- Fixed outdated version number in AssemblyInfo (#398) +- Fixed wrong version number in `conda.recipe` (#398) +- Fixed fixture location for Python tests and `Embedded_Tests` ### Removed -- Removed `six` dependency for unittests (#329) +- Removed `six` dependency for `unittests` (#329) - Removed `Mono.Unix` dependency for `UCS4` (#360) ## [2.2.2][] - 2017-01-29 From b21fab95a6000b3848e4ca7556f62cc3b68753d0 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 21 Feb 2017 09:10:18 -0700 Subject: [PATCH 169/245] Enable embedded_tests to Travis w. conditional filters Add conditional class skip to pytuple for Travis/PY27 Add individual filters to other tests as needed https://www.amido.com/code/conditional-ignore-nunit-and-the-ability-to-conditionally-ignore-a-test/ http://stackoverflow.com/a/16075029/5208670 --- .travis.yml | 2 +- src/embed_tests/dynamic.cs | 17 ++++++++++++++++- src/embed_tests/pyinitialize.cs | 5 +++++ src/embed_tests/pytuple.cs | 28 ++++++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index bd3b9fdf7..95e13b574 100644 --- a/.travis.yml +++ b/.travis.yml @@ -42,7 +42,7 @@ script: - python -m pytest - cp Python.Runtime.dll.config src/embed_tests/bin/ - # - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll + - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll after_script: # Uncomment if need to geninterop, ie. py37 final diff --git a/src/embed_tests/dynamic.cs b/src/embed_tests/dynamic.cs index 8338d68f6..4130323fd 100644 --- a/src/embed_tests/dynamic.cs +++ b/src/embed_tests/dynamic.cs @@ -58,13 +58,25 @@ public void AssignNone() /// Check whether we can get the attr of a python object when the /// value of attr is a PyObject. /// + /// + /// FIXME: Issue on Travis PY27: Error : Python.EmbeddingTest.dynamicTest.AssignPyObject + /// Python.Runtime.PythonException : ImportError : /home/travis/virtualenv/python2.7.9/lib/python2.7/lib-dynload/_io.so: undefined symbol: _PyLong_AsInt + /// [Test] public void AssignPyObject() { + if (Environment.GetEnvironmentVariable("TRAVIS") == "true" && + Environment.GetEnvironmentVariable("TRAVIS_PYTHON_VERSION") == "2.7") + { + // Most recently threw `auto-releasing thread-state, but no thread-state for this thread` + // instead of the error below. Maybe had bad mapping to library? + Assert.Ignore("Fails on Travis/PY27: ImportError: ... undefined symbol: _PyLong_AsInt"); + } + dynamic sys = Py.Import("sys"); dynamic io = Py.Import("io"); sys.testattr = io.StringIO(); - dynamic bb = sys.testattr; //Get the PyObject + dynamic bb = sys.testattr; // Get the PyObject bb.write("Hello!"); Assert.AreEqual(bb.getvalue().ToString(), "Hello!"); } @@ -72,6 +84,9 @@ public void AssignPyObject() /// /// Pass the .NET object in Python side. /// + /// + /// FIXME: Possible source of intermittent Travis PY27: Unable to unload AppDomain. + /// [Test] public void PassObjectInPython() { diff --git a/src/embed_tests/pyinitialize.cs b/src/embed_tests/pyinitialize.cs index 2f9aae2c7..2bfbd1a41 100644 --- a/src/embed_tests/pyinitialize.cs +++ b/src/embed_tests/pyinitialize.cs @@ -33,6 +33,11 @@ public static void LoadDefaultArgs() [Test] public static void LoadSpecificArgs() { + if (Environment.GetEnvironmentVariable("TRAVIS") == "true" && + Environment.GetEnvironmentVariable("TRAVIS_PYTHON_VERSION") != "2.7") + { + Assert.Ignore("FIXME: Fails on Travis/PY3+: Fatal Python error: no mem for sys.argv"); + } var args = new[] { "test1", "test2" }; using (new PythonEngine(args)) using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/pytuple.cs index ef72d2ea9..88910147c 100644 --- a/src/embed_tests/pytuple.cs +++ b/src/embed_tests/pytuple.cs @@ -6,10 +6,37 @@ namespace Python.EmbeddingTest { public class PyTupleTest { + /// + /// Tests set-up. Being used to skip class on Travis/PY27 + /// + /// + /// FIXME: Fails on Travis/PY27: All tests below (unless otherwise stated) + /// Fatal Python error: auto-releasing thread-state, but no thread-state for this thread + /// Stacktrace: + /// at (wrapper managed-to-native) Python.Runtime.Runtime.PyGILState_Release (intptr) + /// at Python.Runtime.PythonEngine.ReleaseLock (intptr) + /// at Python.Runtime.PythonException.Dispose () + /// at Python.Runtime.PythonException.Finalize () + /// at (wrapper runtime-invoke) object.runtime_invoke_virtual_void__this__ (object,intptr,intptr,intptr) + /// + [SetUp] + public void SetUp() + { + if (Environment.GetEnvironmentVariable("TRAVIS") == "true" && + Environment.GetEnvironmentVariable("TRAVIS_PYTHON_VERSION") == "2.7") + { + Assert.Ignore("Fails on Travis/PY27: Fatal Python error: auto-releasing thread-state, but no thread-state for this thread"); + } + } + /// /// Test IsTupleType without having to Initialize a tuple. /// PyTuple constructor use IsTupleType. This decouples the tests. /// + /// + /// Travis PY27 intermittently fails this test. Indicates issue is + /// most likely with PyTuple.IsTupleType + /// [Test] public void TestStringIsTupleType() { @@ -104,6 +131,7 @@ public void TestPyTupleValidConvert() /// /// FIXME: Possible source of intermittent AppVeyor PY27: Unable to unload AppDomain. + /// FIXME: Intermittent Issue on Travis PY33: Fatal Python error: PyMUTEX_LOCK(gil_mutex) failed. Seen twice. /// [Test] public void TestNewPyTupleFromPyTuple() From 3cb531a5710764b3567d003a446eb62693dbd0a7 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 22 Feb 2017 10:02:13 -0700 Subject: [PATCH 170/245] Split blank DefineConstants on `*.csproj` Visual Studio by default wants to split these. Any time the csproj is update (new test for example) it splits them. Splitting them now to not worry about them when reviewing pull_requests. --- src/console/Console.csproj | 12 ++++++++---- src/embed_tests/Python.EmbeddingTest.csproj | 12 ++++++++---- src/runtime/runtime.cs | 1 - src/testing/Python.Test.csproj | 12 ++++++++---- 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/src/console/Console.csproj b/src/console/Console.csproj index 9fe44830c..138c129f8 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -31,7 +31,8 @@ full - + + true pdbonly @@ -41,7 +42,8 @@ full - + + true pdbonly @@ -51,7 +53,8 @@ full - + + true pdbonly @@ -61,7 +64,8 @@ full - + + true pdbonly diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index ef011d044..1b015136d 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -30,7 +30,8 @@ full - + + true pdbonly @@ -40,7 +41,8 @@ full - + + true pdbonly @@ -50,7 +52,8 @@ full - + + true pdbonly @@ -60,7 +63,8 @@ full - + + true pdbonly diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 22b590657..fff628e29 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -195,7 +195,6 @@ internal static void Initialize() { op = Runtime.PyImport_ImportModule("builtins"); dict = Runtime.PyObject_GetAttrString(op, "__dict__"); - } else // Python2 { diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index f135ff9c5..d433e089a 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -31,7 +31,8 @@ full - + + true pdbonly @@ -41,7 +42,8 @@ full - + + true pdbonly @@ -51,7 +53,8 @@ full - + + true pdbonly @@ -61,7 +64,8 @@ full - + + true pdbonly From d86880a81ee5e52eeb855cf93b452167c4aa5ddf Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 22 Feb 2017 10:02:53 -0700 Subject: [PATCH 171/245] Update CHANGELOG --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b68bc38a0..369b16005 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,8 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Added Code Coverage (#345) - Added `PySys_SetArgvEx` (#347) - Added XML Documentation (#349) -- Added `Embedded_Tests` on AppVeyor (#353) +- Added `Embedded_Tests` on AppVeyor (#224)(#353) +- Added `Embedded_Tests` on Travis (#224)(#391) - Added PY3 settings to solution configuration-manager (#346) - Added `Slack` (#384)(#383)(#386) - Added function of passing an arbitrary .NET object as the value From edc7621c496d00f863bd7583c1a41aba3b71338f Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 23 Feb 2017 07:55:15 -0700 Subject: [PATCH 172/245] Fix PythonException GC (#400) Since PythonException doesn't inherit from PyObject, need to reapply the same fix as from gh:365. Seen mostly on PY27/Travis on PyTuple tests. Enable PyTuple tests for PY27/Travis --- src/embed_tests/pytuple.cs | 23 ----------------------- src/runtime/pythonexception.cs | 2 +- 2 files changed, 1 insertion(+), 24 deletions(-) diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/pytuple.cs index 88910147c..03c450694 100644 --- a/src/embed_tests/pytuple.cs +++ b/src/embed_tests/pytuple.cs @@ -6,29 +6,6 @@ namespace Python.EmbeddingTest { public class PyTupleTest { - /// - /// Tests set-up. Being used to skip class on Travis/PY27 - /// - /// - /// FIXME: Fails on Travis/PY27: All tests below (unless otherwise stated) - /// Fatal Python error: auto-releasing thread-state, but no thread-state for this thread - /// Stacktrace: - /// at (wrapper managed-to-native) Python.Runtime.Runtime.PyGILState_Release (intptr) - /// at Python.Runtime.PythonEngine.ReleaseLock (intptr) - /// at Python.Runtime.PythonException.Dispose () - /// at Python.Runtime.PythonException.Finalize () - /// at (wrapper runtime-invoke) object.runtime_invoke_virtual_void__this__ (object,intptr,intptr,intptr) - /// - [SetUp] - public void SetUp() - { - if (Environment.GetEnvironmentVariable("TRAVIS") == "true" && - Environment.GetEnvironmentVariable("TRAVIS_PYTHON_VERSION") == "2.7") - { - Assert.Ignore("Fails on Travis/PY27: Fatal Python error: auto-releasing thread-state, but no thread-state for this thread"); - } - } - /// /// Test IsTupleType without having to Initialize a tuple. /// PyTuple constructor use IsTupleType. This decouples the tests. diff --git a/src/runtime/pythonexception.cs b/src/runtime/pythonexception.cs index 8e2f992f4..58b33f0f3 100644 --- a/src/runtime/pythonexception.cs +++ b/src/runtime/pythonexception.cs @@ -140,7 +140,7 @@ public void Dispose() { if (!disposed) { - if (Runtime.Py_IsInitialized() > 0) + if (Runtime.Py_IsInitialized() > 0 && !Runtime.IsFinalizing) { IntPtr gs = PythonEngine.AcquireLock(); Runtime.XDecref(_pyType); From ea44eef9b4fbc4d0ab9ba4f7f31af16c7e9b44e4 Mon Sep 17 00:00:00 2001 From: yag Date: Fri, 17 Feb 2017 15:47:55 +0800 Subject: [PATCH 173/245] Add Eval(...) and Exec(...) --- src/embed_tests/Python.EmbeddingTest.csproj | 1 + src/embed_tests/pyrunstring.cs | 61 ++++++++++++++++++++ src/runtime/pythonengine.cs | 64 +++++++++++++++------ 3 files changed, 107 insertions(+), 19 deletions(-) create mode 100644 src/embed_tests/pyrunstring.cs diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 1b015136d..f943ca787 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -86,6 +86,7 @@ + diff --git a/src/embed_tests/pyrunstring.cs b/src/embed_tests/pyrunstring.cs new file mode 100644 index 000000000..29fef522a --- /dev/null +++ b/src/embed_tests/pyrunstring.cs @@ -0,0 +1,61 @@ +using System; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + public class RunStringTest + { + private Py.GILState gil; + + [SetUp] + public void SetUp() + { + gil = Py.GIL(); + } + + [TearDown] + public void Dispose() + { + gil.Dispose(); + } + + [Test] + public void TestRunSimpleString() + { + int aa = PythonEngine.RunSimpleString("import sys"); + Assert.AreEqual(aa, 0); + + int bb = PythonEngine.RunSimpleString("import 1234"); + Assert.AreEqual(bb, -1); + } + + [Test] + public void TestEval() + { + dynamic sys = Py.Import("sys"); + sys.attr1 = 100; + var locals = new PyDict(); + locals.SetItem("sys", sys); + locals.SetItem("a", new PyInt(10)); + + object b = PythonEngine.Eval("sys.attr1 + a + 1", null, locals.Handle) + .AsManagedObject(typeof(Int32)); + Assert.AreEqual(b, 111); + } + + [Test] + public void TestExec() + { + dynamic sys = Py.Import("sys"); + sys.attr1 = 100; + var locals = new PyDict(); + locals.SetItem("sys", sys); + locals.SetItem("a", new PyInt(10)); + + PythonEngine.Exec("c = sys.attr1 + a + 1", null, locals.Handle); + object c = locals.GetItem("c").AsManagedObject(typeof(Int32)); + Assert.AreEqual(c, 111); + } + } +} diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index e9fa888a9..1728422af 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -156,11 +156,7 @@ public static void Initialize(IEnumerable args) string code = "import atexit, clr\n" + "atexit.register(clr._AtExit)\n"; - PyObject r = PythonEngine.RunString(code); - if (r != null) - { - r.Dispose(); - } + PythonEngine.Exec(code); // Load the clr.py resource into the clr module IntPtr clr = Python.Runtime.ImportHook.GetCLRModule(); @@ -180,12 +176,7 @@ public static void Initialize(IEnumerable args) { // add the contents of clr.py to the module string clr_py = reader.ReadToEnd(); - PyObject result = RunString(clr_py, module_globals, locals.Handle); - if (null == result) - { - throw new PythonException(); - } - result.Dispose(); + Exec(clr_py, module_globals, locals.Handle); } // add the imported module to the clr module, and copy the API functions @@ -253,11 +244,7 @@ public static void InitExt() " exec(line)\n" + " break\n"; - PyObject r = PythonEngine.RunString(code); - if (r != null) - { - r.Dispose(); - } + PythonEngine.Exec(code); } catch (PythonException e) { @@ -405,6 +392,38 @@ public static PyObject ModuleFromString(string name, string code) } + /// + /// Eval Method + /// + /// + /// Evaluate a Python expression and returns the result. + /// It's a subset of Python eval function. + /// + public static PyObject Eval(string code, IntPtr? globals = null, IntPtr? locals = null) + { + PyObject result = RunString(code, globals, locals, RunFlagType.Eval); + return result; + } + + + /// + /// Exec Method + /// + /// + /// Run a string containing Python code. + /// It's a subset of Python exec function. + /// + public static void Exec(string code, IntPtr? globals = null, IntPtr? locals = null) + { + PyObject result = RunString(code, globals, locals, RunFlagType.File); + if (result.obj != Runtime.PyNone) + { + throw new PythonException(); + } + result.Dispose(); + } + + /// /// RunString Method /// @@ -413,8 +432,8 @@ public static PyObject ModuleFromString(string name, string code) /// executing the code string as a PyObject instance, or null if /// an exception was raised. /// - public static PyObject RunString( - string code, IntPtr? globals = null, IntPtr? locals = null + internal static PyObject RunString( + string code, IntPtr? globals = null, IntPtr? locals = null, RunFlagType _flag = RunFlagType.File ) { var borrowedGlobals = true; @@ -439,7 +458,7 @@ public static PyObject RunString( borrowedLocals = false; } - var flag = (IntPtr)257; /* Py_file_input */ + var flag = (IntPtr)_flag; try { @@ -465,6 +484,13 @@ public static PyObject RunString( } } + public enum RunFlagType + { + Single = 256, + File = 257, /* Py_file_input */ + Eval = 258 + } + public static class Py { public static GILState GIL() From 2dfff9f21601afe742477fda4c3df1040925c91a Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 23 Feb 2017 14:25:56 -0700 Subject: [PATCH 174/245] Keep RunString Public. Fix Assert.AreEqual order - Deprecation/Removal should be a separate issue/pr - In NUnit/XUnit, expected is the first argument, actual is second. Opposite to how Python does it --- src/embed_tests/pyrunstring.cs | 12 ++++++------ src/runtime/pythonengine.cs | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/embed_tests/pyrunstring.cs b/src/embed_tests/pyrunstring.cs index 29fef522a..b17bb87f8 100644 --- a/src/embed_tests/pyrunstring.cs +++ b/src/embed_tests/pyrunstring.cs @@ -24,10 +24,10 @@ public void Dispose() public void TestRunSimpleString() { int aa = PythonEngine.RunSimpleString("import sys"); - Assert.AreEqual(aa, 0); + Assert.AreEqual(0, aa); int bb = PythonEngine.RunSimpleString("import 1234"); - Assert.AreEqual(bb, -1); + Assert.AreEqual(-1, bb); } [Test] @@ -40,8 +40,8 @@ public void TestEval() locals.SetItem("a", new PyInt(10)); object b = PythonEngine.Eval("sys.attr1 + a + 1", null, locals.Handle) - .AsManagedObject(typeof(Int32)); - Assert.AreEqual(b, 111); + .AsManagedObject(typeof(int)); + Assert.AreEqual(111, b); } [Test] @@ -54,8 +54,8 @@ public void TestExec() locals.SetItem("a", new PyInt(10)); PythonEngine.Exec("c = sys.attr1 + a + 1", null, locals.Handle); - object c = locals.GetItem("c").AsManagedObject(typeof(Int32)); - Assert.AreEqual(c, 111); + object c = locals.GetItem("c").AsManagedObject(typeof(int)); + Assert.AreEqual(111, c); } } } diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 1728422af..accd349c5 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -432,7 +432,7 @@ public static void Exec(string code, IntPtr? globals = null, IntPtr? locals = nu /// executing the code string as a PyObject instance, or null if /// an exception was raised. /// - internal static PyObject RunString( + public static PyObject RunString( string code, IntPtr? globals = null, IntPtr? locals = null, RunFlagType _flag = RunFlagType.File ) { From e8c22947dd61cb409ee87770ffcd9c09228324e4 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 23 Feb 2017 17:08:13 -0700 Subject: [PATCH 175/245] Update CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 369b16005..5d2d05bc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Added `bumpversion` for version control (#319)(#398) - Added `tox` for local testing (#345) - Added `requirements.txt` +- Added to `PythonEngine` methods `Eval` and `Exec` (#389) ### Changed @@ -45,6 +46,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Fixed outdated version number in AssemblyInfo (#398) - Fixed wrong version number in `conda.recipe` (#398) - Fixed fixture location for Python tests and `Embedded_Tests` +- Fixed `PythonException` crash during Shutdown (#400) ### Removed From 2b6f8151ca0ccb35d10a85b5a09a0d53ba531fba Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 23 Feb 2017 22:24:42 -0700 Subject: [PATCH 176/245] Clarify MashalAs on runtime.cs - Shorten MarshalAsAttribute name - Put MashalAs'ed argument on own-line - Flip IF comparison --- src/runtime/runtime.cs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index fff628e29..55df701d2 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -290,13 +290,13 @@ internal static void Initialize() #if PYTHON3 IntPtr dll = IntPtr.Zero; - if ("__Internal" != Runtime.dll) + if (Runtime.dll != "__Internal") { NativeMethods.LoadLibrary(Runtime.dll); } _PyObject_NextNotImplemented = NativeMethods.GetProcAddress(dll, "_PyObject_NextNotImplemented"); #if !(MONO_LINUX || MONO_OSX) - if (IntPtr.Zero != dll) + if (dll != IntPtr.Zero) { NativeMethods.FreeLibrary(dll); } @@ -665,7 +665,10 @@ internal unsafe static extern IntPtr [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] public unsafe static extern int - Py_Main(int argc, [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] argv); + Py_Main( + int argc, + [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] argv + ); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -739,7 +742,7 @@ internal unsafe static extern string [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern void - Py_SetProgramName([MarshalAsAttribute(UnmanagedType.LPWStr)] string name); + Py_SetProgramName([MarshalAs(UnmanagedType.LPWStr)] string name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -750,7 +753,7 @@ internal unsafe static extern string [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern void - Py_SetPythonHome([MarshalAsAttribute(UnmanagedType.LPWStr)] string home); + Py_SetPythonHome([MarshalAs(UnmanagedType.LPWStr)] string home); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -761,7 +764,7 @@ internal unsafe static extern string [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] internal unsafe static extern void - Py_SetPath([MarshalAsAttribute(UnmanagedType.LPWStr)] string home); + Py_SetPath([MarshalAs(UnmanagedType.LPWStr)] string home); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -2081,7 +2084,7 @@ internal unsafe static extern IntPtr internal unsafe static extern void PySys_SetArgvEx( int argc, - [MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] argv, + [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] argv, int updatepath ); #elif PYTHON2 From ecd7e601558cd1f6cbfa9139b67caf443f817295 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 23 Feb 2017 22:56:34 -0700 Subject: [PATCH 177/245] Fix runtime Initialize dll nameclash Looks like dllLocal never changes from IntPtr.Zero --- src/runtime/runtime.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 55df701d2..b9ca4dfc7 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -289,16 +289,16 @@ internal static void Initialize() Error = new IntPtr(-1); #if PYTHON3 - IntPtr dll = IntPtr.Zero; + IntPtr dllLocal = IntPtr.Zero; if (Runtime.dll != "__Internal") { NativeMethods.LoadLibrary(Runtime.dll); } - _PyObject_NextNotImplemented = NativeMethods.GetProcAddress(dll, "_PyObject_NextNotImplemented"); + _PyObject_NextNotImplemented = NativeMethods.GetProcAddress(dllLocal, "_PyObject_NextNotImplemented"); #if !(MONO_LINUX || MONO_OSX) - if (dll != IntPtr.Zero) + if (dllLocal != IntPtr.Zero) { - NativeMethods.FreeLibrary(dll); + NativeMethods.FreeLibrary(dllLocal); } #endif #endif From 012b488af1a5f73bd7086923cbb9a437a30a5886 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 24 Feb 2017 01:09:25 -0700 Subject: [PATCH 178/245] Update test_sysargv Previous version didn't test correctly --- src/tests/_compat.py | 9 +++++++++ src/tests/conftest.py | 16 ++++++++++++++-- src/tests/fixtures/argv-fixture.py | 12 ++++++++++++ src/tests/test_sysargv.py | 19 ++++++++++++++----- 4 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 src/tests/fixtures/argv-fixture.py diff --git a/src/tests/_compat.py b/src/tests/_compat.py index 178777e4a..3751ca013 100644 --- a/src/tests/_compat.py +++ b/src/tests/_compat.py @@ -6,6 +6,7 @@ """ import operator +import subprocess import sys import types @@ -63,3 +64,11 @@ map = imap range = xrange zip = izip + + +def check_output(*args, **kwargs): + """Check output wrapper for PY2/PY3 compatibility""" + output = subprocess.check_output(*args, **kwargs) + if PY2: + return output + return output.decode("ascii") diff --git a/src/tests/conftest.py b/src/tests/conftest.py index 534334491..a93326c51 100644 --- a/src/tests/conftest.py +++ b/src/tests/conftest.py @@ -9,12 +9,13 @@ import sys import sysconfig +import pytest import clr # Add path for `Python.Test` cwd = os.path.dirname(__file__) -fixtures = os.path.join(cwd, 'fixtures') -sys.path.append(fixtures) +fixtures_path = os.path.join(cwd, "fixtures") +sys.path.append(fixtures_path) # Add References for tests clr.AddReference("Python.Test") @@ -34,3 +35,14 @@ def pytest_report_header(config): header = ("Arch: {arch}, UCS: {ucs}, LIBDIR: {libdir}, " "Py_ENABLE_SHARED: {shared}".format(**locals())) return header + + +@pytest.fixture() +def filepath(): + """Returns full filepath for file in `fixtures` directory.""" + + def make_filepath(filename): + # http://stackoverflow.com/questions/18011902/parameter-to-a-fixture + return os.path.join(fixtures_path, filename) + + return make_filepath diff --git a/src/tests/fixtures/argv-fixture.py b/src/tests/fixtures/argv-fixture.py new file mode 100644 index 000000000..d56dea4e0 --- /dev/null +++ b/src/tests/fixtures/argv-fixture.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- + +"""Helper script to test argv. +Ensures that argv isn't modified after importing clr. +For more details see GH#404 - argv not found""" + +from __future__ import print_function + +import sys +import clr + +print(sys.argv) diff --git a/src/tests/test_sysargv.py b/src/tests/test_sysargv.py index 2649bf885..2c381070b 100644 --- a/src/tests/test_sysargv.py +++ b/src/tests/test_sysargv.py @@ -4,9 +4,18 @@ import sys +import pytest -def test_sys_argv_state(): - """Test sys.argv state doesn't change after clr import.""" - argv = sys.argv - import clr - assert argv == sys.argv +from ._compat import check_output + + +@pytest.mark.xfail(reason="argv being reset on import clr. See gh#404") +def test_sys_argv_state(filepath): + """Test sys.argv state doesn't change after clr import. + To better control the arguments being passed, test on a fresh python + instance with specific arguments""" + + script = filepath("argv-fixture.py") + out = check_output([sys.executable, script, "foo", "bar"]) + assert "foo" in out + assert "bar" in out From faf5faf81e9a0151c4b004fb2ad0697f628ed077 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Fri, 24 Feb 2017 15:18:18 +0100 Subject: [PATCH 179/245] Fix the issue of sys.argv being cleared on import clr. Closes #404. --- src/runtime/pythonengine.cs | 14 ++++++++++---- src/tests/test_sysargv.py | 3 --- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index accd349c5..3a227479a 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -122,7 +122,12 @@ public static int RunSimpleString(string code) public static void Initialize() { - Initialize(Enumerable.Empty()); + Initialize(setSysArgv: true); + } + + public static void Initialize(bool setSysArgv = true) + { + Initialize(Enumerable.Empty(), setSysArgv: setSysArgv); } /// @@ -134,7 +139,7 @@ public static void Initialize() /// first call. It is *not* necessary to hold the Python global /// interpreter lock (GIL) to call this method. /// - public static void Initialize(IEnumerable args) + public static void Initialize(IEnumerable args, bool setSysArgv = true) { if (!initialized) { @@ -148,7 +153,8 @@ public static void Initialize(IEnumerable args) initialized = true; Exceptions.Clear(); - Py.SetArgv(args); + if (setSysArgv) + Py.SetArgv(args); // register the atexit callback (this doesn't use Py_AtExit as the C atexit // callbacks are called after python is fully finalized but the python ones @@ -213,7 +219,7 @@ public static void InitExt() { try { - Initialize(); + Initialize(setSysArgv: false); // Trickery - when the import hook is installed into an already // running Python, the standard import machinery is still in diff --git a/src/tests/test_sysargv.py b/src/tests/test_sysargv.py index 2c381070b..d86aa1c1d 100644 --- a/src/tests/test_sysargv.py +++ b/src/tests/test_sysargv.py @@ -4,12 +4,9 @@ import sys -import pytest - from ._compat import check_output -@pytest.mark.xfail(reason="argv being reset on import clr. See gh#404") def test_sys_argv_state(filepath): """Test sys.argv state doesn't change after clr import. To better control the arguments being passed, test on a fresh python From c5c8e579d212a7e3ce72f791a5dac731f79b5788 Mon Sep 17 00:00:00 2001 From: denfromufa Date: Fri, 24 Feb 2017 15:15:40 -0600 Subject: [PATCH 180/245] improve tests.pyproj for intellisense and running tests (#395) * Update tests.pyproj * Update folder structure After pytest folders were flatten. Add code in fixture Upstream PyImportTest was moved to within Embedded Tests Add pyproj to editorconfig --- .editorconfig | 2 +- src/tests/tests.pyproj | 23 ++++++++++------------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/.editorconfig b/.editorconfig index 25636a549..2e7c58ffe 100644 --- a/.editorconfig +++ b/.editorconfig @@ -16,7 +16,7 @@ trim_trailing_whitespace = true indent_size = 2 # Xml project files -[*.{csproj,config,build,config}] +[*.{csproj,pyproj,config}] indent_size = 2 # Solution diff --git a/src/tests/tests.pyproj b/src/tests/tests.pyproj index 5d042249e..cefa0d05e 100644 --- a/src/tests/tests.pyproj +++ b/src/tests/tests.pyproj @@ -6,7 +6,7 @@ {250c535c-c060-4f0c-bd80-41f2bf373565} runtests.py - + ..\..\ . . {888888a0-9f3d-457c-b088-3a5042f75d52} @@ -27,17 +27,17 @@ $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets + + + - - - - + @@ -50,23 +50,20 @@ + + - - - - - + + - - - + From db6c1b2f2d2542b12d6c7211fd1f1a5790320e23 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 24 Feb 2017 14:28:12 -0700 Subject: [PATCH 181/245] Add case-sensitivity tests closes #81 --- src/testing/methodtest.cs | 10 ++++++++++ src/tests/test_method.py | 13 +++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/testing/methodtest.cs b/src/testing/methodtest.cs index e76348ab4..83dc907c0 100644 --- a/src/testing/methodtest.cs +++ b/src/testing/methodtest.cs @@ -641,6 +641,16 @@ public static int Overloaded(int i, string s) { return i; } + + public static string CaseSensitive() + { + return "CaseSensitive"; + } + + public static string Casesensitive() + { + return "Casesensitive"; + } } diff --git a/src/tests/test_method.py b/src/tests/test_method.py index 12c8cb13e..ad182678d 100644 --- a/src/tests/test_method.py +++ b/src/tests/test_method.py @@ -819,3 +819,16 @@ def test_object_in_multiparam_exception(): with pytest.raises(TypeError): MethodTest.TestOverloadedObjectThree("foo", "bar") + + +def test_case_sensitive(): + """Test that case-sensitivity is respected. GH#81""" + + res = MethodTest.CaseSensitive() + assert res == "CaseSensitive" + + res = MethodTest.Casesensitive() + assert res == "Casesensitive" + + with pytest.raises(AttributeError): + MethodTest.casesensitive() From 30be9c9fb39e759031a4060775a98a38928ef92b Mon Sep 17 00:00:00 2001 From: fractus Date: Fri, 24 Feb 2017 23:26:14 +0000 Subject: [PATCH 182/245] Added branching for ldd command in OSX (#406) --- setup.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/setup.py b/setup.py index 37a936584..5e6813518 100644 --- a/setup.py +++ b/setup.py @@ -162,16 +162,15 @@ def build_extension(self, ext): defines.extend(["DEBUG", "TRACE"]) if sys.platform != "win32" and DEVTOOLS == "Mono": - if sys.platform == "darwin": - defines.append("MONO_OSX") - else: - defines.append("MONO_LINUX") + on_darwin = sys.platform == "darwin" + defines.append("MONO_OSX" if on_darwin else "MONO_LINUX") # Check if --enable-shared was set when Python was built enable_shared = sysconfig.get_config_var("Py_ENABLE_SHARED") if enable_shared: # Double-check if libpython is linked dynamically with python - lddout = _check_output(["ldd", sys.executable]) + ldd_cmd = ["otool", "-L"] if on_darwin else ["ldd"] + lddout = _check_output(ldd_cmd + [sys.executable]) if 'libpython' not in lddout: enable_shared = False From b4ed645d343ef302513b17796cdd8791c4255128 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 25 Feb 2017 08:46:51 -0700 Subject: [PATCH 183/245] Minor style clean-up runtime/pythonengine Add missing brackets Organize using/remove unused Align arguments --- src/runtime/pythonengine.cs | 7 ++++--- src/runtime/runtime.cs | 9 ++++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 3a227479a..57f6d5074 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -1,9 +1,8 @@ using System; -using System.IO; -using System.Threading; -using System.Reflection; using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Reflection; namespace Python.Runtime { @@ -154,7 +153,9 @@ public static void Initialize(IEnumerable args, bool setSysArgv = true) Exceptions.Clear(); if (setSysArgv) + { Py.SetArgv(args); + } // register the atexit callback (this doesn't use Py_AtExit as the C atexit // callbacks are called after python is fully finalized but the python ones diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index b9ca4dfc7..d0960222c 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1653,11 +1653,14 @@ internal unsafe static extern IntPtr EntryPoint = "PyUnicode_FromKindAndData", ExactSpelling = true)] internal unsafe static extern IntPtr - PyUnicode_FromKindAndString(int kind, + PyUnicode_FromKindAndString( + int kind, IntPtr s, - int size); + int size + ); - internal static unsafe IntPtr PyUnicode_FromKindAndString(int kind, + internal static unsafe IntPtr PyUnicode_FromKindAndString( + int kind, string s, int size) { From 8ff338a0783bbe0f26a2196cea736849ea7c146c Mon Sep 17 00:00:00 2001 From: dse Date: Tue, 21 Feb 2017 22:24:49 -0700 Subject: [PATCH 184/245] Fix Py_Main/PySys_SetArgvEx(...) UCS4/PY3 no mem Based on @dmitriyse work on: https://github.com/dmitriyse/pythonnet/commit/8a70f09cb8faa9461d13480fb9ee2ee60b5b9acc --- src/embed_tests/pyinitialize.cs | 5 --- src/runtime/runtime.cs | 69 ++++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/src/embed_tests/pyinitialize.cs b/src/embed_tests/pyinitialize.cs index 2bfbd1a41..2f9aae2c7 100644 --- a/src/embed_tests/pyinitialize.cs +++ b/src/embed_tests/pyinitialize.cs @@ -33,11 +33,6 @@ public static void LoadDefaultArgs() [Test] public static void LoadSpecificArgs() { - if (Environment.GetEnvironmentVariable("TRAVIS") == "true" && - Environment.GetEnvironmentVariable("TRAVIS_PYTHON_VERSION") != "2.7") - { - Assert.Ignore("FIXME: Fails on Travis/PY3+: Fatal Python error: no mem for sys.argv"); - } var args = new[] { "test1", "test2" }; using (new PythonEngine(args)) using (var argv = new PyList(Runtime.Runtime.PySys_GetObject("argv"))) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index d0960222c..3f30f86ce 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -667,8 +667,41 @@ internal unsafe static extern IntPtr public unsafe static extern int Py_Main( int argc, - [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] argv + [MarshalAs(UnmanagedType.SysUInt)] IntPtr lplpargv ); + + public static int Py_Main(int argc, string[] argv) + { + // Totally ignoring argc. + argc = argv.Length; + + var allStringsLength = 0; + foreach (string x in argv) + { + allStringsLength += x.Length + 1; + } + int requiredSize = IntPtr.Size * argc + allStringsLength * UCS; + IntPtr mem = Marshal.AllocHGlobal(requiredSize); + try + { + // Preparing array of pointers to UTF32 strings. + IntPtr curStrPtr = mem + argc * IntPtr.Size; + for (var i = 0; i < argv.Length; i++) + { + // Unicode or UTF8 work + Encoding enc = UCS == 2 ? Encoding.Unicode : Encoding.UTF32; + byte[] zstr = enc.GetBytes(argv[i] + "\0"); + Marshal.Copy(zstr, 0, curStrPtr, zstr.Length); + Marshal.WriteIntPtr(mem + IntPtr.Size * i, curStrPtr); + curStrPtr += zstr.Length; + } + return Py_Main(argc, mem); + } + finally + { + Marshal.FreeHGlobal(mem); + } + } #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -2087,9 +2120,41 @@ internal unsafe static extern IntPtr internal unsafe static extern void PySys_SetArgvEx( int argc, - [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] argv, + [MarshalAs(UnmanagedType.SysUInt)] IntPtr lplpargv, int updatepath ); + + internal static void PySys_SetArgvEx(int argc, string[] argv, int updatepath) + { + // Totally ignoring argc. + argc = argv.Length; + + var allStringsLength = 0; + foreach (string x in argv) + { + allStringsLength += x.Length + 1; + } + int requiredSize = IntPtr.Size * argc + allStringsLength * UCS; + IntPtr mem = Marshal.AllocHGlobal(requiredSize); + try + { + // Preparing array of pointers to UTF32 strings. + IntPtr curStrPtr = mem + argc * IntPtr.Size; + for (var i = 0; i < argv.Length; i++) + { + Encoding enc = UCS == 2 ? Encoding.Unicode : Encoding.UTF32; + byte[] zstr = enc.GetBytes(argv[i] + "\0"); + Marshal.Copy(zstr, 0, curStrPtr, zstr.Length); + Marshal.WriteIntPtr(mem + IntPtr.Size * i, curStrPtr); + curStrPtr += zstr.Length; + } + PySys_SetArgvEx(argc, mem, updatepath); + } + finally + { + Marshal.FreeHGlobal(mem); + } + } #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] From 9b7089209f7466a8aebe23c981186bc5a69867a4 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 24 Feb 2017 17:03:57 -0700 Subject: [PATCH 185/245] Update CHANGELOG, remove extra MarshalAs --- CHANGELOG.md | 1 + src/runtime/runtime.cs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d2d05bc4..6b9e3d8fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Fixed wrong version number in `conda.recipe` (#398) - Fixed fixture location for Python tests and `Embedded_Tests` - Fixed `PythonException` crash during Shutdown (#400) +- Fixed `Py_Main` & `PySys_SetArgvEx` no mem error on `UCS4/PY3` (#399) ### Removed diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 3f30f86ce..6398d3345 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -667,7 +667,7 @@ internal unsafe static extern IntPtr public unsafe static extern int Py_Main( int argc, - [MarshalAs(UnmanagedType.SysUInt)] IntPtr lplpargv + IntPtr lplpargv ); public static int Py_Main(int argc, string[] argv) @@ -2120,7 +2120,7 @@ internal unsafe static extern IntPtr internal unsafe static extern void PySys_SetArgvEx( int argc, - [MarshalAs(UnmanagedType.SysUInt)] IntPtr lplpargv, + IntPtr lplpargv, int updatepath ); From 9e854897bbd518220abb1bd41939c0aba84e98a3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 25 Feb 2017 18:47:38 -0700 Subject: [PATCH 186/245] Move PythonBuildDir when not defined Keep root of solution clean and out of the way from being imported because its on the `cwd`. --- src/clrmodule/clrmodule.csproj | 2 +- src/console/Console.csproj | 2 +- src/embed_tests/Python.EmbeddingTest.csproj | 2 +- src/runtime/Python.Runtime.csproj | 2 +- src/testing/Python.Test.csproj | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index 6f44789d7..a86822118 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -13,7 +13,7 @@ 1591 ..\..\ - $(SolutionDir) + $(SolutionDir)\bin\ Properties true diff --git a/src/console/Console.csproj b/src/console/Console.csproj index 138c129f8..1c2881046 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -13,7 +13,7 @@ 1591 ..\..\ - $(SolutionDir) + $(SolutionDir)\bin\ Properties python-clear.ico diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index f943ca787..d3c25bf24 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -13,7 +13,7 @@ 1591 ..\..\ - $(SolutionDir) + $(SolutionDir)\bin\ true prompt diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index fd2281d58..c32bd5dec 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -13,7 +13,7 @@ 1591 ..\..\ - $(SolutionDir) + $(SolutionDir)\bin\ Properties true diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index d433e089a..2a2f9ff54 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -13,7 +13,7 @@ 1591,0067 ..\..\ - $(SolutionDir) + $(SolutionDir)\bin\ false ..\pythonnet.snk From f2519f7a826534a884327cf59915961c6825ec72 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 25 Feb 2017 18:49:46 -0700 Subject: [PATCH 187/245] Update ARCH check Use sys for x86/x64 check --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 5e6813518..30168dfde 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,6 @@ import fnmatch import glob import os -import platform import subprocess import sys import sysconfig @@ -24,8 +23,9 @@ CONFIG = "Release" # Release or Debug VERBOSITY = "minimal" # quiet, minimal, normal, detailed, diagnostic +is_64bits = sys.maxsize > 2**32 DEVTOOLS = "MsDev" if sys.platform == "win32" else "Mono" -ARCH = "x64" if platform.architecture()[0] == "64bit" else "x86" +ARCH = "x64" if is_64bits else "x86" PY_MAJOR = sys.version_info[0] PY_MINOR = sys.version_info[1] From cef6153170351691bfebc7a3de635032e03cfe0d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 26 Feb 2017 18:01:04 -0700 Subject: [PATCH 188/245] Enable TestPyTupleInvalidAppend test `AppDomain unload` was solved by #400. Closes #397. Possibly also solved #245. --- CHANGELOG.md | 1 + src/embed_tests/dynamic.cs | 5 ----- src/embed_tests/pytuple.cs | 21 +++++++-------------- src/runtime/pythonexception.cs | 2 ++ 4 files changed, 10 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b9e3d8fa..6ec2a0fb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Fixed wrong version number in `conda.recipe` (#398) - Fixed fixture location for Python tests and `Embedded_Tests` - Fixed `PythonException` crash during Shutdown (#400) +- Fixed `AppDomain` unload during GC (#397)(#400) - Fixed `Py_Main` & `PySys_SetArgvEx` no mem error on `UCS4/PY3` (#399) ### Removed diff --git a/src/embed_tests/dynamic.cs b/src/embed_tests/dynamic.cs index 4130323fd..73277c454 100644 --- a/src/embed_tests/dynamic.cs +++ b/src/embed_tests/dynamic.cs @@ -68,8 +68,6 @@ public void AssignPyObject() if (Environment.GetEnvironmentVariable("TRAVIS") == "true" && Environment.GetEnvironmentVariable("TRAVIS_PYTHON_VERSION") == "2.7") { - // Most recently threw `auto-releasing thread-state, but no thread-state for this thread` - // instead of the error below. Maybe had bad mapping to library? Assert.Ignore("Fails on Travis/PY27: ImportError: ... undefined symbol: _PyLong_AsInt"); } @@ -84,9 +82,6 @@ public void AssignPyObject() /// /// Pass the .NET object in Python side. /// - /// - /// FIXME: Possible source of intermittent Travis PY27: Unable to unload AppDomain. - /// [Test] public void PassObjectInPython() { diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/pytuple.cs index 03c450694..ade4375c0 100644 --- a/src/embed_tests/pytuple.cs +++ b/src/embed_tests/pytuple.cs @@ -10,10 +10,6 @@ public class PyTupleTest /// Test IsTupleType without having to Initialize a tuple. /// PyTuple constructor use IsTupleType. This decouples the tests. /// - /// - /// Travis PY27 intermittently fails this test. Indicates issue is - /// most likely with PyTuple.IsTupleType - /// [Test] public void TestStringIsTupleType() { @@ -47,15 +43,16 @@ public void TestPyTupleEmpty() } } + /// + /// Test PyTuple.Concat(...) doesn't let invalid appends happen + /// and throws and exception. + /// /// - /// FIXME: Unable to unload AppDomain, Unload thread timed out. - /// Seen on Travis/AppVeyor on both PY2 and PY3. Causes Embedded_Tests - /// to hang after they are finished for ~40 seconds until nunit3 forces - /// a timeout on unloading tests. Doesn't fail the tests though but - /// greatly slows down CI. nunit2 silently has this issue. + /// Test has second purpose. Currently it generated an Exception + /// that the GC failed to remove often and caused AppDomain unload + /// errors at the end of tests. See GH#397 for more info. /// [Test] - [Ignore("GH#397: Travis/AppVeyor: Unable to unload AppDomain, Unload thread timed out")] public void TestPyTupleInvalidAppend() { using (Py.GIL()) @@ -106,10 +103,6 @@ public void TestPyTupleValidConvert() } } - /// - /// FIXME: Possible source of intermittent AppVeyor PY27: Unable to unload AppDomain. - /// FIXME: Intermittent Issue on Travis PY33: Fatal Python error: PyMUTEX_LOCK(gil_mutex) failed. Seen twice. - /// [Test] public void TestNewPyTupleFromPyTuple() { diff --git a/src/runtime/pythonexception.cs b/src/runtime/pythonexception.cs index 58b33f0f3..4fe07f3cf 100644 --- a/src/runtime/pythonexception.cs +++ b/src/runtime/pythonexception.cs @@ -135,6 +135,8 @@ public override string StackTrace /// /// The Dispose method provides a way to explicitly release the /// Python objects represented by a PythonException. + /// If object not properly disposed can cause AppDomain unload issue. + /// See GH#397 and GH#400. /// public void Dispose() { From 5070db0dfdd69345b8e62b8c47af34e16c509a1d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 26 Feb 2017 18:38:00 -0700 Subject: [PATCH 189/245] Add tests/refactor existing --- src/embed_tests/dynamic.cs | 2 +- src/embed_tests/pythonexception.cs | 14 +++++----- src/embed_tests/pytuple.cs | 42 +++++++++++++++++++++++++++++- 3 files changed, 48 insertions(+), 10 deletions(-) diff --git a/src/embed_tests/dynamic.cs b/src/embed_tests/dynamic.cs index 73277c454..bfdc8fcc2 100644 --- a/src/embed_tests/dynamic.cs +++ b/src/embed_tests/dynamic.cs @@ -5,7 +5,7 @@ namespace Python.EmbeddingTest { - public class dynamicTest + public class DynamicTest { private Py.GILState gil; diff --git a/src/embed_tests/pythonexception.cs b/src/embed_tests/pythonexception.cs index bdae9db9e..0323567d0 100644 --- a/src/embed_tests/pythonexception.cs +++ b/src/embed_tests/pythonexception.cs @@ -33,14 +33,12 @@ public void Dispose() public void TestMessage() { var list = new PyList(); - try - { - PyObject junk = list[0]; - } - catch (PythonException e) - { - Assert.AreEqual("IndexError : list index out of range", e.Message); - } + PyObject foo = null; + + var ex = Assert.Throws(() => foo = list[0]); + + Assert.AreEqual("IndexError : list index out of range", ex.Message); + Assert.IsNull(foo); } [Test] diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/pytuple.cs index ade4375c0..541e13210 100644 --- a/src/embed_tests/pytuple.cs +++ b/src/embed_tests/pytuple.cs @@ -43,6 +43,21 @@ public void TestPyTupleEmpty() } } + [Test] + public void TestPyTupleBadCtor() + { + using (Py.GIL()) + { + var i = new PyInt(5); + PyTuple t = null; + + var ex = Assert.Throws(() => t = new PyTuple(i)); + + Assert.AreEqual("object is not a tuple", ex.Message); + Assert.IsNull(t); + } + } + /// /// Test PyTuple.Concat(...) doesn't let invalid appends happen /// and throws and exception. @@ -51,6 +66,8 @@ public void TestPyTupleEmpty() /// Test has second purpose. Currently it generated an Exception /// that the GC failed to remove often and caused AppDomain unload /// errors at the end of tests. See GH#397 for more info. + /// + /// Curious, on PY27 it gets a Unicode on the ex.Message. On PY3+ its string. /// [Test] public void TestPyTupleInvalidAppend() @@ -59,7 +76,12 @@ public void TestPyTupleInvalidAppend() { PyObject s = new PyString("foo"); var t = new PyTuple(); - Assert.Throws(() => t.Concat(s)); + + var ex = Assert.Throws(() => t.Concat(s)); + + StringAssert.StartsWith("TypeError : can only concatenate tuple", ex.Message); + Assert.AreEqual(0, t.Length()); + Assert.IsEmpty(t); } } @@ -114,5 +136,23 @@ public void TestNewPyTupleFromPyTuple() Assert.IsInstanceOf(typeof(PyTuple), t); } } + + /// + /// TODO: Should this throw ArgumentError instead? + /// + [Test] + public void TestInvalidAsTuple() + { + using (Py.GIL()) + { + var i = new PyInt(5); + PyTuple t = null; + + var ex = Assert.Throws(() => t = PyTuple.AsTuple(i)); + + Assert.AreEqual("TypeError : 'int' object is not iterable", ex.Message); + Assert.IsNull(t); + } + } } } From 7dba6178186938db115519a11a46c1d51b0fab0c Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 26 Feb 2017 22:45:06 -0700 Subject: [PATCH 190/245] Set language version to 6 Prevent accidental introduction of csharp 7 features. --- src/clrmodule/clrmodule.csproj | 2 +- src/console/Console.csproj | 2 +- src/embed_tests/Python.EmbeddingTest.csproj | 2 +- src/runtime/Python.Runtime.csproj | 2 +- src/testing/Python.Test.csproj | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/clrmodule/clrmodule.csproj b/src/clrmodule/clrmodule.csproj index a86822118..6e5ff4966 100644 --- a/src/clrmodule/clrmodule.csproj +++ b/src/clrmodule/clrmodule.csproj @@ -15,7 +15,7 @@ ..\..\ $(SolutionDir)\bin\ Properties - + 6 true prompt diff --git a/src/console/Console.csproj b/src/console/Console.csproj index 1c2881046..ea88b6356 100644 --- a/src/console/Console.csproj +++ b/src/console/Console.csproj @@ -15,7 +15,7 @@ ..\..\ $(SolutionDir)\bin\ Properties - + 6 python-clear.ico prompt diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index d3c25bf24..b48c909a0 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -14,7 +14,7 @@ 1591 ..\..\ $(SolutionDir)\bin\ - + 6 true prompt diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index c32bd5dec..3dbad5f75 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -15,7 +15,7 @@ ..\..\ $(SolutionDir)\bin\ Properties - + 6 true false ..\pythonnet.snk diff --git a/src/testing/Python.Test.csproj b/src/testing/Python.Test.csproj index 2a2f9ff54..ce8dca10d 100644 --- a/src/testing/Python.Test.csproj +++ b/src/testing/Python.Test.csproj @@ -14,7 +14,7 @@ 1591,0067 ..\..\ $(SolutionDir)\bin\ - + 6 false ..\pythonnet.snk prompt From 6667669e71bf638b0dbda8ef1ffcc71befe060b0 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 24 Feb 2017 18:18:04 -0700 Subject: [PATCH 191/245] Add ICustomMarshaler StrMarshaler Useful resources https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.icustommarshaler(v=vs.110).aspx https://limbioliong.wordpress.com/2013/11/03/understanding-custom-marshaling-part-1/ https://github.com/mono/mono/blob/master/mcs/class/Mono.Posix/Mono.Unix/UnixMarshal.cs http://stackoverflow.com/a/33514037/5208670 --- src/runtime/CustomMarshaler.cs | 80 +++++++++++++++++++++++++++++++ src/runtime/Python.Runtime.csproj | 1 + src/runtime/debughelper.cs | 22 +++++++++ src/runtime/runtime.cs | 52 ++------------------ 4 files changed, 108 insertions(+), 47 deletions(-) create mode 100644 src/runtime/CustomMarshaler.cs diff --git a/src/runtime/CustomMarshaler.cs b/src/runtime/CustomMarshaler.cs new file mode 100644 index 000000000..bb3a4946b --- /dev/null +++ b/src/runtime/CustomMarshaler.cs @@ -0,0 +1,80 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +namespace Python.Runtime +{ + /// + /// Abstract class defining boiler plate methods that + /// Custom Marshalers will use. + /// + public abstract class MarshalerBase : ICustomMarshaler + { + public object MarshalNativeToManaged(IntPtr pNativeData) + { + throw new NotImplementedException(); + } + + public abstract IntPtr MarshalManagedToNative(object managedObj); + + public void CleanUpNativeData(IntPtr pNativeData) + { + Marshal.FreeHGlobal(pNativeData); + } + + public void CleanUpManagedData(object managedObj) + { + // Let GC deal with it + } + + public int GetNativeDataSize() + { + return IntPtr.Size; + } + } + + + /// + /// Custom Marshaler to deal with Managed String to Native + /// conversion differences on UCS2/UCS4. + /// + public class StrMarshaler : MarshalerBase + { + private static readonly MarshalerBase Instance = new StrMarshaler(); + + public override IntPtr MarshalManagedToNative(object managedObj) + { + Encoding encoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32; + var s = managedObj as string; + + if (s == null) + { + return IntPtr.Zero; + } + + int minByteCount = encoding.GetMaxByteCount(1); + char[] cStr = s.ToCharArray(0, s.Length); + byte[] bStr = new byte[encoding.GetByteCount(cStr) + minByteCount]; + encoding.GetBytes(cStr, 0, cStr.Length, bStr, 0); + DebugUtil.PrintHexBytes(bStr); + + IntPtr mem = Marshal.AllocHGlobal(bStr.Length); + try + { + Marshal.Copy(bStr, 0, mem, bStr.Length); + } + catch (Exception) + { + Marshal.FreeHGlobal(mem); + throw; + } + + return mem; + } + + public static ICustomMarshaler GetInstance(string cookie) + { + return Instance; + } + } +} diff --git a/src/runtime/Python.Runtime.csproj b/src/runtime/Python.Runtime.csproj index 3dbad5f75..8580b7f61 100644 --- a/src/runtime/Python.Runtime.csproj +++ b/src/runtime/Python.Runtime.csproj @@ -89,6 +89,7 @@ + diff --git a/src/runtime/debughelper.cs b/src/runtime/debughelper.cs index 777a61e35..2a91a74b4 100644 --- a/src/runtime/debughelper.cs +++ b/src/runtime/debughelper.cs @@ -115,5 +115,27 @@ internal static void debug(string msg) Console.WriteLine("thread {0} : {1}", tid, caller); Console.WriteLine(" {0}", msg); } + + /// + /// Helper function to inspect/compare managed to native conversions. + /// Especially useful when debugging CustomMarshaler. + /// + /// + [Conditional("DEBUG")] + public static void PrintHexBytes(byte[] bytes) + { + if ((bytes == null) || (bytes.Length == 0)) + { + Console.WriteLine(""); + } + else + { + foreach (byte t in bytes) + { + Console.Write("{0:X2} ", t); + } + Console.WriteLine(); + } + } } } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 6398d3345..50e09dd95 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1688,34 +1688,10 @@ internal unsafe static extern IntPtr internal unsafe static extern IntPtr PyUnicode_FromKindAndString( int kind, - IntPtr s, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, int size ); - internal static unsafe IntPtr PyUnicode_FromKindAndString( - int kind, - string s, - int size) - { - var bufLength = Math.Max(s.Length, size) * 4; - - IntPtr mem = Marshal.AllocHGlobal(bufLength); - try - { - fixed (char* ps = s) - { - Encoding.UTF32.GetBytes(ps, s.Length, (byte*)mem, bufLength); - } - - var result = PyUnicode_FromKindAndString(kind, mem, size); - return result; - } - finally - { - Marshal.FreeHGlobal(mem); - } - } - internal static IntPtr PyUnicode_FromUnicode(string s, int size) { return PyUnicode_FromKindAndString(4, s, size); @@ -1758,28 +1734,10 @@ internal unsafe static extern IntPtr EntryPoint = "PyUnicodeUCS4_FromUnicode", ExactSpelling = true)] internal unsafe static extern IntPtr - PyUnicode_FromUnicode(IntPtr s, int size); - - internal static unsafe IntPtr PyUnicode_FromUnicode(string s, int size) - { - var bufLength = Math.Max(s.Length, size) * 4; - - IntPtr mem = Marshal.AllocHGlobal(bufLength); - try - { - fixed (char* ps = s) - { - Encoding.UTF32.GetBytes(ps, s.Length, (byte*)mem, bufLength); - } - - var result = PyUnicode_FromUnicode(mem, size); - return result; - } - finally - { - Marshal.FreeHGlobal(mem); - } - } + PyUnicode_FromUnicode( + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, + int size + ); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS4_GetSize", From d01f25fffd94458aed7e1f6ef3a2d79dde12525d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 25 Feb 2017 02:15:13 -0700 Subject: [PATCH 192/245] Add ICustomMarshaler StrArrayMarshaler --- src/runtime/CustomMarshaler.cs | 54 ++++++++++++++++++++++++++ src/runtime/runtime.cs | 69 +--------------------------------- 2 files changed, 56 insertions(+), 67 deletions(-) diff --git a/src/runtime/CustomMarshaler.cs b/src/runtime/CustomMarshaler.cs index bb3a4946b..f776cb1e3 100644 --- a/src/runtime/CustomMarshaler.cs +++ b/src/runtime/CustomMarshaler.cs @@ -77,4 +77,58 @@ public static ICustomMarshaler GetInstance(string cookie) return Instance; } } + + + /// + /// Custom Marshaler to deal with Managed String Arrays to Native + /// conversion differences on UCS2/UCS4. + /// + public class StrArrayMarshaler : MarshalerBase + { + private static readonly MarshalerBase Instance = new StrArrayMarshaler(); + + public override IntPtr MarshalManagedToNative(object managedObj) + { + var argv = managedObj as string[]; + + if (argv == null) + { + return IntPtr.Zero; + } + + var totalStrLength = 0; + foreach (string arg in argv) + { + totalStrLength += arg.Length + 1; + } + int memSize = argv.Length * IntPtr.Size + totalStrLength * Runtime.UCS; + + IntPtr mem = Marshal.AllocHGlobal(memSize); + try + { + // Preparing array of pointers to strings + IntPtr curStrPtr = mem + argv.Length * IntPtr.Size; + for (var i = 0; i < argv.Length; i++) + { + Encoding encoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32; + byte[] bStr = encoding.GetBytes(argv[i] + "\0"); + Marshal.Copy(bStr, 0, curStrPtr, bStr.Length); + Marshal.WriteIntPtr(mem + i * IntPtr.Size, curStrPtr); + curStrPtr += bStr.Length; + } + } + catch (Exception) + { + Marshal.FreeHGlobal(mem); + throw; + } + + return mem; + } + + public static ICustomMarshaler GetInstance(string cookie) + { + return Instance; + } + } } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 50e09dd95..3d5eda0fe 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -667,41 +667,8 @@ internal unsafe static extern IntPtr public unsafe static extern int Py_Main( int argc, - IntPtr lplpargv + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv ); - - public static int Py_Main(int argc, string[] argv) - { - // Totally ignoring argc. - argc = argv.Length; - - var allStringsLength = 0; - foreach (string x in argv) - { - allStringsLength += x.Length + 1; - } - int requiredSize = IntPtr.Size * argc + allStringsLength * UCS; - IntPtr mem = Marshal.AllocHGlobal(requiredSize); - try - { - // Preparing array of pointers to UTF32 strings. - IntPtr curStrPtr = mem + argc * IntPtr.Size; - for (var i = 0; i < argv.Length; i++) - { - // Unicode or UTF8 work - Encoding enc = UCS == 2 ? Encoding.Unicode : Encoding.UTF32; - byte[] zstr = enc.GetBytes(argv[i] + "\0"); - Marshal.Copy(zstr, 0, curStrPtr, zstr.Length); - Marshal.WriteIntPtr(mem + IntPtr.Size * i, curStrPtr); - curStrPtr += zstr.Length; - } - return Py_Main(argc, mem); - } - finally - { - Marshal.FreeHGlobal(mem); - } - } #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] @@ -2078,41 +2045,9 @@ internal unsafe static extern IntPtr internal unsafe static extern void PySys_SetArgvEx( int argc, - IntPtr lplpargv, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv, int updatepath ); - - internal static void PySys_SetArgvEx(int argc, string[] argv, int updatepath) - { - // Totally ignoring argc. - argc = argv.Length; - - var allStringsLength = 0; - foreach (string x in argv) - { - allStringsLength += x.Length + 1; - } - int requiredSize = IntPtr.Size * argc + allStringsLength * UCS; - IntPtr mem = Marshal.AllocHGlobal(requiredSize); - try - { - // Preparing array of pointers to UTF32 strings. - IntPtr curStrPtr = mem + argc * IntPtr.Size; - for (var i = 0; i < argv.Length; i++) - { - Encoding enc = UCS == 2 ? Encoding.Unicode : Encoding.UTF32; - byte[] zstr = enc.GetBytes(argv[i] + "\0"); - Marshal.Copy(zstr, 0, curStrPtr, zstr.Length); - Marshal.WriteIntPtr(mem + IntPtr.Size * i, curStrPtr); - curStrPtr += zstr.Length; - } - PySys_SetArgvEx(argc, mem, updatepath); - } - finally - { - Marshal.FreeHGlobal(mem); - } - } #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] From 74440a6b90beaaa32a2df8bc6b3660ce5edafbcb Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 25 Feb 2017 10:05:16 -0700 Subject: [PATCH 193/245] Refactor Marshals --- src/runtime/CustomMarshaler.cs | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/src/runtime/CustomMarshaler.cs b/src/runtime/CustomMarshaler.cs index f776cb1e3..1004122cd 100644 --- a/src/runtime/CustomMarshaler.cs +++ b/src/runtime/CustomMarshaler.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Runtime.InteropServices; using System.Text; @@ -41,10 +42,10 @@ public int GetNativeDataSize() public class StrMarshaler : MarshalerBase { private static readonly MarshalerBase Instance = new StrMarshaler(); + private static readonly Encoding PyEncoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32; public override IntPtr MarshalManagedToNative(object managedObj) { - Encoding encoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32; var s = managedObj as string; if (s == null) @@ -52,12 +53,7 @@ public override IntPtr MarshalManagedToNative(object managedObj) return IntPtr.Zero; } - int minByteCount = encoding.GetMaxByteCount(1); - char[] cStr = s.ToCharArray(0, s.Length); - byte[] bStr = new byte[encoding.GetByteCount(cStr) + minByteCount]; - encoding.GetBytes(cStr, 0, cStr.Length, bStr, 0); - DebugUtil.PrintHexBytes(bStr); - + byte[] bStr = PyEncoding.GetBytes(s + "\0"); IntPtr mem = Marshal.AllocHGlobal(bStr.Length); try { @@ -86,6 +82,7 @@ public static ICustomMarshaler GetInstance(string cookie) public class StrArrayMarshaler : MarshalerBase { private static readonly MarshalerBase Instance = new StrArrayMarshaler(); + private static readonly Encoding PyEncoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32; public override IntPtr MarshalManagedToNative(object managedObj) { @@ -96,11 +93,7 @@ public override IntPtr MarshalManagedToNative(object managedObj) return IntPtr.Zero; } - var totalStrLength = 0; - foreach (string arg in argv) - { - totalStrLength += arg.Length + 1; - } + int totalStrLength = argv.Sum(arg => arg.Length + 1); int memSize = argv.Length * IntPtr.Size + totalStrLength * Runtime.UCS; IntPtr mem = Marshal.AllocHGlobal(memSize); @@ -110,8 +103,7 @@ public override IntPtr MarshalManagedToNative(object managedObj) IntPtr curStrPtr = mem + argv.Length * IntPtr.Size; for (var i = 0; i < argv.Length; i++) { - Encoding encoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32; - byte[] bStr = encoding.GetBytes(argv[i] + "\0"); + byte[] bStr = PyEncoding.GetBytes(argv[i] + "\0"); Marshal.Copy(bStr, 0, curStrPtr, bStr.Length); Marshal.WriteIntPtr(mem + i * IntPtr.Size, curStrPtr); curStrPtr += bStr.Length; From e487076d90ac86f15150c1b41113565364fb7850 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 25 Feb 2017 12:58:27 -0700 Subject: [PATCH 194/245] Add ICustomMarshaler Utf8Marshaler Refactor PyString_FromStringAndSize Link explains why `MarshalAs(UnmanagedType.LPWStr)` or `CharSet.Unicode` don't work http://stackoverflow.com/a/25128147/5208670 --- src/runtime/CustomMarshaler.cs | 45 ++++++++++++++++++++++++++++++++++ src/runtime/runtime.cs | 23 +++++------------ 2 files changed, 51 insertions(+), 17 deletions(-) diff --git a/src/runtime/CustomMarshaler.cs b/src/runtime/CustomMarshaler.cs index 1004122cd..a4947a909 100644 --- a/src/runtime/CustomMarshaler.cs +++ b/src/runtime/CustomMarshaler.cs @@ -123,4 +123,49 @@ public static ICustomMarshaler GetInstance(string cookie) return Instance; } } + + + /// + /// Custom Marshaler to deal with Managed String to Native + /// conversion on UTF-8. Use on functions that expect UTF-8 encoded + /// strings like `PyUnicode_FromStringAndSize` + /// + /// + /// If instead we used `MarshalAs(UnmanagedType.LPWStr)` the output to + /// `foo` would be `f\x00o\x00o\x00`. + /// + public class Utf8Marshaler : MarshalerBase + { + private static readonly MarshalerBase Instance = new Utf8Marshaler(); + private static readonly Encoding PyEncoding = Encoding.UTF8; + + public override IntPtr MarshalManagedToNative(object managedObj) + { + var s = managedObj as string; + + if (s == null) + { + return IntPtr.Zero; + } + + byte[] bStr = PyEncoding.GetBytes(s + "\0"); + IntPtr mem = Marshal.AllocHGlobal(bStr.Length); + try + { + Marshal.Copy(bStr, 0, mem, bStr.Length); + } + catch (Exception) + { + Marshal.FreeHGlobal(mem); + throw; + } + + return mem; + } + + public static ICustomMarshaler GetInstance(string cookie) + { + return Instance; + } + } } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 3d5eda0fe..50c31ddb4 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1508,23 +1508,12 @@ internal static IntPtr PyBytes_AS_STRING(IntPtr ob) return ob + BytesOffset.ob_sval; } - internal static IntPtr PyString_FromStringAndSize(string value, int length) - { - // copy the string into an unmanaged UTF-8 buffer - int len = Encoding.UTF8.GetByteCount(value); - byte[] buffer = new byte[len + 1]; - Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, 0); - IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length); - try - { - Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length); - return PyUnicode_FromStringAndSize(nativeUtf8, length); - } - finally - { - Marshal.FreeHGlobal(nativeUtf8); - } - } + [DllImport(Runtime.dll, EntryPoint = "PyUnicode_FromStringAndSize")] + internal static extern IntPtr + PyString_FromStringAndSize( + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(Utf8Marshaler))] string value, + int size + ); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Unicode)] From ccd4521298e87c53d1217670acbc3963371020a3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 25 Feb 2017 19:57:52 -0700 Subject: [PATCH 195/245] Match PyUnicode_AsUnicode signature in UCS2/UCS4 --- src/runtime/runtime.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 50c31ddb4..13549b581 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1572,7 +1572,7 @@ internal unsafe static extern int [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern char* + internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, @@ -1613,7 +1613,7 @@ internal unsafe static extern int [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS2_AsUnicode", ExactSpelling = true)] - internal unsafe static extern char* + internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, @@ -1749,9 +1749,9 @@ internal unsafe static string GetManagedString(IntPtr op) Marshal.Copy(p, buffer, 0, size); return Encoding.UTF32.GetString(buffer, 0, size); #elif UCS2 - char* p = Runtime.PyUnicode_AsUnicode(op); - int size = Runtime.PyUnicode_GetSize(op); - return new String(p, 0, size); + IntPtr p = Runtime.PyUnicode_AsUnicode(op); + int length = Runtime.PyUnicode_GetSize(op); + return Marshal.PtrToStringUni(p, length); #endif } From 07f87de2ae0456d7e5c09333a09ab6bbbc11cf1f Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 25 Feb 2017 23:09:48 -0700 Subject: [PATCH 196/245] Refactor GetManagedString --- src/runtime/runtime.cs | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 13549b581..a9dcdd81e 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1725,7 +1725,20 @@ internal static IntPtr PyUnicode_FromString(string s) return PyUnicode_FromUnicode(s, (s.Length)); } - internal unsafe static string GetManagedString(IntPtr op) + /// + /// Function to access the internal PyUnicode/PyString object and + /// convert it to a managed string with the correct encoding. + /// + /// + /// We can't easily do this through through the CustomMarshaler's on + /// the returns because will have access to the IntPtr but not size. + /// + /// For PyUnicodeType, we can't convert with Marshal.PtrToStringUni + /// since it only works for UCS2. + /// + /// PyStringType or PyUnicodeType object to convert + /// Managed String + internal static string GetManagedString(IntPtr op) { IntPtr type = PyObject_TYPE(op); @@ -1741,18 +1754,15 @@ internal unsafe static string GetManagedString(IntPtr op) if (type == Runtime.PyUnicodeType) { -#if UCS4 - IntPtr p = Runtime.PyUnicode_AsUnicode(op); - int length = Runtime.PyUnicode_GetSize(op); - int size = length * 4; - byte[] buffer = new byte[size]; + Encoding encoding = UCS == 2 ? Encoding.Unicode : Encoding.UTF32; + + IntPtr p = PyUnicode_AsUnicode(op); + int length = PyUnicode_GetSize(op); + + int size = length * UCS; + var buffer = new byte[size]; Marshal.Copy(p, buffer, 0, size); - return Encoding.UTF32.GetString(buffer, 0, size); -#elif UCS2 - IntPtr p = Runtime.PyUnicode_AsUnicode(op); - int length = Runtime.PyUnicode_GetSize(op); - return Marshal.PtrToStringUni(p, length); -#endif + return encoding.GetString(buffer, 0, size); } return null; From edafdf2db546908e4cc60f55656a0125e25bac4f Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 26 Feb 2017 00:18:37 -0700 Subject: [PATCH 197/245] Remove internal PyUnicode_AS_UNICODE Its redundant with PyUnicode_AsUnicode now that the signature is fixed between UCS2/UCS4. Apply char conversion that work on both UCS2/UCS4 --- src/runtime/converter.cs | 19 ++++--------------- src/runtime/runtime.cs | 24 ------------------------ 2 files changed, 4 insertions(+), 39 deletions(-) diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index aeaf2d871..8b58e5e9a 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -599,21 +599,10 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo { if (Runtime.PyUnicode_GetSize(value) == 1) { - op = Runtime.PyUnicode_AS_UNICODE(value); - if (Runtime.UCS == 2) // Don't trust linter, statement not always true. - { - // 2011-01-02: Marshal as character array because the cast - // result = (char)Marshal.ReadInt16(op); throws an OverflowException - // on negative numbers with Check Overflow option set on the project - Char[] buff = new Char[1]; - Marshal.Copy(op, buff, 0, 1); - result = buff[0]; - } - else // UCS4 - { - // XXX this is probably NOT correct? - result = (char)Marshal.ReadInt32(op); - } + op = Runtime.PyUnicode_AsUnicode(value); + Char[] buff = new Char[1]; + Marshal.Copy(op, buff, 0, 1); + result = buff[0]; return true; } goto type_error; diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index a9dcdd81e..9558a5ac3 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1575,12 +1575,6 @@ internal unsafe static extern int internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicode_AsUnicode", - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_AS_UNICODE(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr @@ -1616,12 +1610,6 @@ internal unsafe static extern int internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_AsUnicode", - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_AS_UNICODE(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS2_FromOrdinal", ExactSpelling = true, CharSet = CharSet.Unicode)] @@ -1663,12 +1651,6 @@ internal unsafe static extern int internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicode_AsUnicode", - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_AS_UNICODE(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr @@ -1707,12 +1689,6 @@ internal unsafe static extern int internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_AsUnicode", - ExactSpelling = true, CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr - PyUnicode_AS_UNICODE(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS4_FromOrdinal", ExactSpelling = true, CharSet = CharSet.Unicode)] From 78939c599eecdeccad0384feb4f584fd36171024 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 26 Feb 2017 10:30:06 -0700 Subject: [PATCH 198/245] Refactor Encoding check This won't change during runtime. --- src/runtime/CustomMarshaler.cs | 4 ++-- src/runtime/runtime.cs | 9 ++++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/runtime/CustomMarshaler.cs b/src/runtime/CustomMarshaler.cs index a4947a909..475fa05eb 100644 --- a/src/runtime/CustomMarshaler.cs +++ b/src/runtime/CustomMarshaler.cs @@ -42,7 +42,7 @@ public int GetNativeDataSize() public class StrMarshaler : MarshalerBase { private static readonly MarshalerBase Instance = new StrMarshaler(); - private static readonly Encoding PyEncoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32; + private static readonly Encoding PyEncoding = Runtime.PyEncoding; public override IntPtr MarshalManagedToNative(object managedObj) { @@ -82,7 +82,7 @@ public static ICustomMarshaler GetInstance(string cookie) public class StrArrayMarshaler : MarshalerBase { private static readonly MarshalerBase Instance = new StrArrayMarshaler(); - private static readonly Encoding PyEncoding = Runtime.UCS == 2 ? Encoding.Unicode : Encoding.UTF32; + private static readonly Encoding PyEncoding = Runtime.PyEncoding; public override IntPtr MarshalManagedToNative(object managedObj) { diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 9558a5ac3..337b82fbf 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -170,6 +170,11 @@ public class Runtime internal static bool IsPython2; internal static bool IsPython3; + /// + /// Encoding to use to convert Unicode to/from Managed to Native + /// + internal static readonly Encoding PyEncoding = UCS == 2 ? Encoding.Unicode : Encoding.UTF32; + /// /// Initialize the runtime... /// @@ -1730,15 +1735,13 @@ internal static string GetManagedString(IntPtr op) if (type == Runtime.PyUnicodeType) { - Encoding encoding = UCS == 2 ? Encoding.Unicode : Encoding.UTF32; - IntPtr p = PyUnicode_AsUnicode(op); int length = PyUnicode_GetSize(op); int size = length * UCS; var buffer = new byte[size]; Marshal.Copy(p, buffer, 0, size); - return encoding.GetString(buffer, 0, size); + return PyEncoding.GetString(buffer, 0, size); } return null; From 7114393da7ec716468b5f4cea9ac1b9099043287 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 23 Feb 2017 21:26:43 -0700 Subject: [PATCH 199/245] Remove ExactSpelling Not needed as Python doesn't define character specific functions https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.exactspelling(v=vs.110).aspx --- src/runtime/runtime.cs | 516 ++++++++++++++++++++--------------------- 1 file changed, 255 insertions(+), 261 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 337b82fbf..ff8a6caa3 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -584,91 +584,91 @@ internal unsafe static long Refcount(IntPtr op) // Py_IncRef and Py_DecRef are taking care of the extra payload // in Py_DEBUG builds of Python like _Py_RefTotal [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] private unsafe static extern void Py_IncRef(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] private unsafe static extern void Py_DecRef(IntPtr ob); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void Py_Initialize(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int Py_IsInitialized(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void Py_Finalize(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr Py_NewInterpreter(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void Py_EndInterpreter(IntPtr threadState); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyThreadState_New(IntPtr istate); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyThreadState_Get(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyThread_get_key_value(IntPtr key); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyThread_get_thread_ident(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyThread_set_key_value(IntPtr key, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyThreadState_Swap(IntPtr key); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyGILState_Ensure(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyGILState_Release(IntPtr gs); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyGILState_GetThisThreadState(); #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] public unsafe static extern int Py_Main( int argc, @@ -676,204 +676,204 @@ public unsafe static extern int ); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] public unsafe static extern int Py_Main(int argc, string[] argv); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyEval_InitThreads(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyEval_ThreadsInitialized(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyEval_AcquireLock(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyEval_ReleaseLock(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyEval_AcquireThread(IntPtr tstate); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyEval_ReleaseThread(IntPtr tstate); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyEval_SaveThread(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyEval_RestoreThread(IntPtr tstate); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyEval_GetBuiltins(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyEval_GetGlobals(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyEval_GetLocals(); #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetProgramName(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void Py_SetProgramName([MarshalAs(UnmanagedType.LPWStr)] string name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetPythonHome(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void Py_SetPythonHome([MarshalAs(UnmanagedType.LPWStr)] string home); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetPath(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void Py_SetPath([MarshalAs(UnmanagedType.LPWStr)] string home); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string Py_GetProgramName(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void Py_SetProgramName(string name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string Py_GetPythonHome(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void Py_SetPythonHome(string home); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string Py_GetPath(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void Py_SetPath(string home); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string Py_GetVersion(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string Py_GetPlatform(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string Py_GetCopyright(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string Py_GetCompiler(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string Py_GetBuildInfo(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyRun_SimpleString(string code); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr Py_CompileString(string code, string file, IntPtr tok); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyImport_ExecCodeModule(string name, IntPtr code); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyClass_New(IntPtr bases, IntPtr dict, IntPtr name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyInstance_NewRaw(IntPtr cls, IntPtr dict); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); @@ -931,68 +931,68 @@ internal static string PyObject_GetTypeName(IntPtr op) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_HasAttrString(IntPtr pointer, string name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_GetAttrString(IntPtr pointer, string name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_HasAttr(IntPtr pointer, IntPtr name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_GetAttr(IntPtr pointer, IntPtr name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_GetItem(IntPtr pointer, IntPtr key); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_DelItem(IntPtr pointer, IntPtr key); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_GetIter(IntPtr op); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args); #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); @@ -1022,72 +1022,72 @@ internal static int PyObject_Compare(IntPtr value1, IntPtr value2) } #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_Compare(IntPtr value1, IntPtr value2); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_IsInstance(IntPtr ob, IntPtr type); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_IsSubclass(IntPtr ob, IntPtr type); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyCallable_Check(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_IsTrue(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_Not(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_Size(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_Hash(IntPtr op); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_Repr(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_Str(IntPtr pointer); #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyObject_Str", - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_Unicode(IntPtr pointer); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_Unicode(IntPtr pointer); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_Dir(IntPtr pointer); @@ -1099,30 +1099,30 @@ internal unsafe static extern IntPtr #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyNumber_Long", - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Int(IntPtr ob); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Int(IntPtr ob); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Long(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Float(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern bool PyNumber_Check(IntPtr ob); @@ -1152,46 +1152,46 @@ internal static IntPtr PyInt_FromInt64(long value) #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_FromLong", - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] private unsafe static extern IntPtr PyInt_FromLong(IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_AsLong", - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyInt_AsLong(IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_FromString", - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_GetMax", - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyInt_GetMax(); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] private unsafe static extern IntPtr PyInt_FromLong(IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyInt_AsLong(IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyInt_GetMax(); #endif @@ -1202,52 +1202,52 @@ internal static bool PyLong_Check(IntPtr ob) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyLong_FromLong(long value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyLong_FromUnsignedLong(uint value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyLong_FromDouble(double value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyLong_FromLongLong(long value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyLong_FromUnsignedLongLong(ulong value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyLong_FromString(string value, IntPtr end, int radix); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyLong_AsLong(IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern uint PyLong_AsUnsignedLong(IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern long PyLong_AsLongLong(IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern ulong PyLong_AsUnsignedLongLong(IntPtr value); @@ -1258,142 +1258,142 @@ internal static bool PyFloat_Check(IntPtr ob) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyFloat_FromDouble(double value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyFloat_FromString(IntPtr value, IntPtr junk); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern double PyFloat_AsDouble(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Add(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Subtract(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Multiply(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Divide(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_And(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Xor(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Or(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Lshift(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Rshift(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Power(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Remainder(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceAdd(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceSubtract(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceMultiply(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceDivide(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceAnd(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceXor(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceOr(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceLshift(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceRshift(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlacePower(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_InPlaceRemainder(IntPtr o1, IntPtr o2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Negative(IntPtr o1); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Positive(IntPtr o1); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyNumber_Invert(IntPtr o1); @@ -1402,77 +1402,77 @@ internal unsafe static extern IntPtr //==================================================================== [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern bool PySequence_Check(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PySequence_GetItem(IntPtr pointer, int index); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PySequence_SetItem(IntPtr pointer, int index, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PySequence_DelItem(IntPtr pointer, int index); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PySequence_GetSlice(IntPtr pointer, int i1, int i2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PySequence_SetSlice(IntPtr pointer, int i1, int i2, IntPtr v); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PySequence_DelSlice(IntPtr pointer, int i1, int i2); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PySequence_Size(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PySequence_Contains(IntPtr pointer, IntPtr item); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PySequence_Concat(IntPtr pointer, IntPtr other); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PySequence_Repeat(IntPtr pointer, int count); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PySequence_Index(IntPtr pointer, IntPtr item); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PySequence_Count(IntPtr pointer, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PySequence_Tuple(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PySequence_List(IntPtr pointer); @@ -1499,12 +1499,12 @@ internal static IntPtr PyString_FromString(string value) #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyBytes_FromString(string op); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyBytes_Size(IntPtr op); @@ -1521,23 +1521,23 @@ int size ); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, int size); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyString_FromStringAndSize(string value, int size); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyString_AsString", - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyString_AS_STRING(IntPtr op); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyString_Size(IntPtr pointer); #endif @@ -1549,18 +1549,17 @@ internal static bool PyUnicode_Check(IntPtr ob) #if UCS2 && PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicode_FromKindAndData", - ExactSpelling = true, CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromKindAndString(int kind, string s, int size); @@ -1571,69 +1570,67 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS2 && PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS2_FromObject", - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS2_FromEncodedObject", - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS2_FromUnicode", - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromUnicode(string s, int size); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS2_GetSize", - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_AsUnicode", - ExactSpelling = true)] + EntryPoint = "PyUnicodeUCS2_AsUnicode")] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS2_FromOrdinal", - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicode_FromKindAndData", - ExactSpelling = true)] + EntryPoint = "PyUnicode_FromKindAndData")] internal unsafe static extern IntPtr PyUnicode_FromKindAndString( int kind, @@ -1647,35 +1644,33 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS4_FromObject", - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS4_FromEncodedObject", - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_FromUnicode", - ExactSpelling = true)] + EntryPoint = "PyUnicodeUCS4_FromUnicode")] internal unsafe static extern IntPtr PyUnicode_FromUnicode( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, @@ -1684,19 +1679,18 @@ int size [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS4_GetSize", - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_AsUnicode", - ExactSpelling = true)] + EntryPoint = "PyUnicodeUCS4_AsUnicode")] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicodeUCS4_FromOrdinal", - ExactSpelling = true, CharSet = CharSet.Unicode)] + CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #endif @@ -1757,82 +1751,82 @@ internal static bool PyDict_Check(IntPtr ob) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyDict_New(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyDictProxy_New(IntPtr dict); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyDict_GetItem(IntPtr pointer, IntPtr key); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyDict_GetItemString(IntPtr pointer, string key); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyDict_SetItemString(IntPtr pointer, string key, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyDict_DelItem(IntPtr pointer, IntPtr key); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyDict_DelItemString(IntPtr pointer, string key); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyMapping_HasKey(IntPtr pointer, IntPtr key); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyDict_Keys(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyDict_Values(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyDict_Items(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyDict_Copy(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyDict_Update(IntPtr pointer, IntPtr other); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyDict_Clear(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyDict_Size(IntPtr pointer); @@ -1847,57 +1841,57 @@ internal static bool PyList_Check(IntPtr ob) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyList_New(int size); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyList_AsTuple(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyList_GetItem(IntPtr pointer, int index); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyList_SetItem(IntPtr pointer, int index, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyList_Insert(IntPtr pointer, int index, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyList_Append(IntPtr pointer, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyList_Reverse(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyList_Sort(IntPtr pointer); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyList_GetSlice(IntPtr pointer, int start, int end); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyList_SetSlice(IntPtr pointer, int start, int end, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyList_Size(IntPtr pointer); @@ -1912,27 +1906,27 @@ internal static bool PyTuple_Check(IntPtr ob) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyTuple_New(int size); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyTuple_GetItem(IntPtr pointer, int index); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyTuple_SetItem(IntPtr pointer, int index, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyTuple_GetSlice(IntPtr pointer, int start, int end); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyTuple_Size(IntPtr pointer); @@ -1943,7 +1937,7 @@ internal unsafe static extern int #if PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern bool PyIter_Check(IntPtr pointer); #elif PYTHON3 @@ -1957,7 +1951,7 @@ internal static bool #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyIter_Next(IntPtr pointer); @@ -1966,60 +1960,60 @@ internal unsafe static extern IntPtr //==================================================================== [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyModule_New(string name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string PyModule_GetName(IntPtr module); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyModule_GetDict(IntPtr module); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern string PyModule_GetFilename(IntPtr module); #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyModule_Create2(IntPtr module, int apiver); #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyImport_Import(IntPtr name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyImport_ImportModule(string name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyImport_ReloadModule(IntPtr module); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyImport_AddModule(string name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyImport_GetModuleDict(); #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PySys_SetArgvEx( int argc, @@ -2028,7 +2022,7 @@ int updatepath ); #elif PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PySys_SetArgvEx( int argc, @@ -2038,12 +2032,12 @@ int updatepath #endif [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PySys_GetObject(string name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PySys_SetObject(string name, IntPtr ob); @@ -2058,12 +2052,12 @@ internal static bool PyType_Check(IntPtr ob) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyType_Modified(IntPtr type); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern bool PyType_IsSubtype(IntPtr t1, IntPtr t2); @@ -2074,57 +2068,57 @@ internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) } [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyType_GenericAlloc(IntPtr type, int n); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyType_Ready(IntPtr type); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr _PyType_Lookup(IntPtr type, IntPtr name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_GenericGetAttr(IntPtr obj, IntPtr name); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr _PyObject_GetDictPtr(IntPtr obj); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyObject_GC_New(IntPtr tp); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyObject_GC_Del(IntPtr tp); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyObject_GC_Track(IntPtr tp); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyObject_GC_UnTrack(IntPtr tp); @@ -2134,17 +2128,17 @@ internal unsafe static extern void //==================================================================== [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyMem_Malloc(int size); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyMem_Realloc(IntPtr ptr, int size); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyMem_Free(IntPtr ptr); @@ -2154,62 +2148,62 @@ internal unsafe static extern void //==================================================================== [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyErr_SetString(IntPtr ob, string message); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyErr_SetObject(IntPtr ob, IntPtr message); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyErr_SetFromErrno(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyErr_SetNone(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyErr_ExceptionMatches(IntPtr exception); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern int PyErr_Occurred(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyErr_Clear(); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern void PyErr_Print(); @@ -2219,12 +2213,12 @@ internal unsafe static extern void //==================================================================== [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyMethod_Self(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - ExactSpelling = true, CharSet = CharSet.Ansi)] + CharSet = CharSet.Ansi)] internal unsafe static extern IntPtr PyMethod_Function(IntPtr ob); } From 1fef331652c9e7831def9b9d93e25b432ec0490a Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 23 Feb 2017 21:34:46 -0700 Subject: [PATCH 200/245] Remove CharSet.Ansi Its default charset used https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.charset(v=vs.110).aspx#Anchor_1 --- src/runtime/runtime.cs | 702 ++++++++++++++--------------------------- 1 file changed, 234 insertions(+), 468 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index ff8a6caa3..019b2bd2f 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -583,297 +583,241 @@ internal unsafe static long Refcount(IntPtr op) #if Py_DEBUG // Py_IncRef and Py_DecRef are taking care of the extra payload // in Py_DEBUG builds of Python like _Py_RefTotal - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] private unsafe static extern void Py_IncRef(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] private unsafe static extern void Py_DecRef(IntPtr ob); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void Py_Initialize(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int Py_IsInitialized(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void Py_Finalize(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr Py_NewInterpreter(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void Py_EndInterpreter(IntPtr threadState); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyThreadState_New(IntPtr istate); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyThreadState_Get(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyThread_get_key_value(IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyThread_get_thread_ident(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyThread_set_key_value(IntPtr key, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyThreadState_Swap(IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyGILState_Ensure(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyGILState_Release(IntPtr gs); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyGILState_GetThisThreadState(); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] public unsafe static extern int Py_Main( int argc, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv ); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] public unsafe static extern int Py_Main(int argc, string[] argv); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyEval_InitThreads(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyEval_ThreadsInitialized(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyEval_AcquireLock(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyEval_ReleaseLock(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyEval_AcquireThread(IntPtr tstate); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyEval_ReleaseThread(IntPtr tstate); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyEval_SaveThread(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyEval_RestoreThread(IntPtr tstate); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyEval_GetBuiltins(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyEval_GetGlobals(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyEval_GetLocals(); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetProgramName(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void Py_SetProgramName([MarshalAs(UnmanagedType.LPWStr)] string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetPythonHome(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void Py_SetPythonHome([MarshalAs(UnmanagedType.LPWStr)] string home); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetPath(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void Py_SetPath([MarshalAs(UnmanagedType.LPWStr)] string home); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string Py_GetProgramName(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void Py_SetProgramName(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string Py_GetPythonHome(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void Py_SetPythonHome(string home); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string Py_GetPath(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void Py_SetPath(string home); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string Py_GetVersion(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string Py_GetPlatform(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string Py_GetCopyright(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string Py_GetCompiler(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string Py_GetBuildInfo(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyRun_SimpleString(string code); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr Py_CompileString(string code, string file, IntPtr tok); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyImport_ExecCodeModule(string name, IntPtr code); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyClass_New(IntPtr bases, IntPtr dict, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyInstance_NewRaw(IntPtr cls, IntPtr dict); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); @@ -930,69 +874,56 @@ internal static string PyObject_GetTypeName(IntPtr op) return Marshal.PtrToStringAnsi(ppName); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_HasAttrString(IntPtr pointer, string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_GetAttrString(IntPtr pointer, string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_HasAttr(IntPtr pointer, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_GetAttr(IntPtr pointer, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_GetItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_DelItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_GetIter(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); @@ -1021,73 +952,60 @@ internal static int PyObject_Compare(IntPtr value1, IntPtr value2) return -1; } #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_Compare(IntPtr value1, IntPtr value2); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_IsInstance(IntPtr ob, IntPtr type); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_IsSubclass(IntPtr ob, IntPtr type); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyCallable_Check(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_IsTrue(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_Not(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_Size(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_Hash(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_Repr(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_Str(IntPtr pointer); #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyObject_Str", - CharSet = CharSet.Ansi)] + EntryPoint = "PyObject_Str")] internal unsafe static extern IntPtr PyObject_Unicode(IntPtr pointer); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_Unicode(IntPtr pointer); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_Dir(IntPtr pointer); @@ -1098,31 +1016,26 @@ internal unsafe static extern IntPtr #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyNumber_Long", - CharSet = CharSet.Ansi)] + EntryPoint = "PyNumber_Long")] internal unsafe static extern IntPtr PyNumber_Int(IntPtr ob); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Int(IntPtr ob); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Long(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Float(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern bool PyNumber_Check(IntPtr ob); @@ -1151,47 +1064,39 @@ internal static IntPtr PyInt_FromInt64(long value) #if PYTHON3 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyLong_FromLong", - CharSet = CharSet.Ansi)] + EntryPoint = "PyLong_FromLong")] private unsafe static extern IntPtr PyInt_FromLong(IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyLong_AsLong", - CharSet = CharSet.Ansi)] + EntryPoint = "PyLong_AsLong")] internal unsafe static extern int PyInt_AsLong(IntPtr value); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyLong_FromString", - CharSet = CharSet.Ansi)] + EntryPoint = "PyLong_FromString")] internal unsafe static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyLong_GetMax", - CharSet = CharSet.Ansi)] + EntryPoint = "PyLong_GetMax")] internal unsafe static extern int PyInt_GetMax(); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] private unsafe static extern IntPtr PyInt_FromLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyInt_AsLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyInt_GetMax(); #endif @@ -1201,53 +1106,43 @@ internal static bool PyLong_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyLongType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyLong_FromLong(long value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyLong_FromUnsignedLong(uint value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyLong_FromDouble(double value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyLong_FromLongLong(long value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyLong_FromUnsignedLongLong(ulong value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyLong_FromString(string value, IntPtr end, int radix); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyLong_AsLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern uint PyLong_AsUnsignedLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern long PyLong_AsLongLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern ulong PyLong_AsUnsignedLongLong(IntPtr value); @@ -1257,143 +1152,115 @@ internal static bool PyFloat_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyFloatType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyFloat_FromDouble(double value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyFloat_FromString(IntPtr value, IntPtr junk); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern double PyFloat_AsDouble(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Add(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Subtract(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Multiply(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Divide(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_And(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Xor(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Or(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Lshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Rshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Power(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Remainder(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceAdd(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceSubtract(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceMultiply(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceDivide(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceAnd(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceXor(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceOr(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceLshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceRshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlacePower(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_InPlaceRemainder(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Negative(IntPtr o1); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Positive(IntPtr o1); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyNumber_Invert(IntPtr o1); @@ -1401,78 +1268,63 @@ internal unsafe static extern IntPtr // Python sequence API //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern bool PySequence_Check(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PySequence_GetItem(IntPtr pointer, int index); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PySequence_SetItem(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PySequence_DelItem(IntPtr pointer, int index); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PySequence_GetSlice(IntPtr pointer, int i1, int i2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PySequence_SetSlice(IntPtr pointer, int i1, int i2, IntPtr v); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PySequence_DelSlice(IntPtr pointer, int i1, int i2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PySequence_Size(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PySequence_Contains(IntPtr pointer, IntPtr item); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PySequence_Concat(IntPtr pointer, IntPtr other); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PySequence_Repeat(IntPtr pointer, int count); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PySequence_Index(IntPtr pointer, IntPtr item); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PySequence_Count(IntPtr pointer, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PySequence_Tuple(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PySequence_List(IntPtr pointer); @@ -1498,13 +1350,11 @@ internal static IntPtr PyString_FromString(string value) } #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyBytes_FromString(string op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyBytes_Size(IntPtr op); @@ -1525,19 +1375,16 @@ int size internal unsafe static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, int size); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyString_FromStringAndSize(string value, int size); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyString_AsString", - CharSet = CharSet.Ansi)] + EntryPoint = "PyString_AsString")] internal unsafe static extern IntPtr PyString_AS_STRING(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyString_Size(IntPtr pointer); #endif @@ -1603,8 +1450,7 @@ internal unsafe static extern IntPtr PyUnicode_FromUnicode(string s, int size); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_GetSize", - CharSet = CharSet.Ansi)] + EntryPoint = "PyUnicodeUCS2_GetSize")] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); @@ -1643,8 +1489,7 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) return PyUnicode_FromKindAndString(4, s, size); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); @@ -1678,8 +1523,7 @@ int size ); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_GetSize", - CharSet = CharSet.Ansi)] + EntryPoint = "PyUnicodeUCS4_GetSize")] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); @@ -1750,83 +1594,67 @@ internal static bool PyDict_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyDictType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyDict_New(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyDictProxy_New(IntPtr dict); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyDict_GetItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyDict_GetItemString(IntPtr pointer, string key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyDict_SetItemString(IntPtr pointer, string key, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyDict_DelItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyDict_DelItemString(IntPtr pointer, string key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyMapping_HasKey(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyDict_Keys(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyDict_Values(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyDict_Items(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyDict_Copy(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyDict_Update(IntPtr pointer, IntPtr other); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyDict_Clear(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyDict_Size(IntPtr pointer); @@ -1840,58 +1668,47 @@ internal static bool PyList_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyListType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyList_New(int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyList_AsTuple(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyList_GetItem(IntPtr pointer, int index); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyList_SetItem(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyList_Insert(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyList_Append(IntPtr pointer, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyList_Reverse(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyList_Sort(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyList_GetSlice(IntPtr pointer, int start, int end); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyList_SetSlice(IntPtr pointer, int start, int end, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyList_Size(IntPtr pointer); @@ -1905,28 +1722,23 @@ internal static bool PyTuple_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyTupleType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyTuple_New(int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyTuple_GetItem(IntPtr pointer, int index); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyTuple_SetItem(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyTuple_GetSlice(IntPtr pointer, int start, int end); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyTuple_Size(IntPtr pointer); @@ -1936,8 +1748,7 @@ internal unsafe static extern int //==================================================================== #if PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern bool PyIter_Check(IntPtr pointer); #elif PYTHON3 @@ -1950,8 +1761,7 @@ internal static bool } #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyIter_Next(IntPtr pointer); @@ -1959,61 +1769,50 @@ internal unsafe static extern IntPtr // Python module API //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyModule_New(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string PyModule_GetName(IntPtr module); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyModule_GetDict(IntPtr module); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern string PyModule_GetFilename(IntPtr module); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyModule_Create2(IntPtr module, int apiver); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyImport_Import(IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyImport_ImportModule(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyImport_ReloadModule(IntPtr module); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyImport_AddModule(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyImport_GetModuleDict(); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PySys_SetArgvEx( int argc, @@ -2021,8 +1820,7 @@ internal unsafe static extern void int updatepath ); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PySys_SetArgvEx( int argc, @@ -2031,13 +1829,11 @@ int updatepath ); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PySys_GetObject(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PySys_SetObject(string name, IntPtr ob); @@ -2051,13 +1847,11 @@ internal static bool PyType_Check(IntPtr ob) return PyObject_TypeCheck(ob, Runtime.PyTypeType); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyType_Modified(IntPtr type); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern bool PyType_IsSubtype(IntPtr t1, IntPtr t2); @@ -2067,58 +1861,47 @@ internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) return (t == tp) || PyType_IsSubtype(t, tp); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyType_GenericAlloc(IntPtr type, int n); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyType_Ready(IntPtr type); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr _PyType_Lookup(IntPtr type, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_GenericGetAttr(IntPtr obj, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr _PyObject_GetDictPtr(IntPtr obj); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyObject_GC_New(IntPtr tp); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyObject_GC_Del(IntPtr tp); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyObject_GC_Track(IntPtr tp); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyObject_GC_UnTrack(IntPtr tp); @@ -2127,18 +1910,15 @@ internal unsafe static extern void // Python memory API //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyMem_Malloc(int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyMem_Realloc(IntPtr ptr, int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyMem_Free(IntPtr ptr); @@ -2147,63 +1927,51 @@ internal unsafe static extern void // Python exception API //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyErr_SetString(IntPtr ob, string message); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyErr_SetObject(IntPtr ob, IntPtr message); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyErr_SetFromErrno(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyErr_SetNone(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyErr_ExceptionMatches(IntPtr exception); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyErr_Occurred(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyErr_Clear(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern void PyErr_Print(); @@ -2212,13 +1980,11 @@ internal unsafe static extern void // Miscellaneous //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyMethod_Self(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Ansi)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyMethod_Function(IntPtr ob); } From ef7f69f821a72e4e39d93df4bb4cb663771a6c12 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 23 Feb 2017 21:51:01 -0700 Subject: [PATCH 201/245] Remove CharSet.Unicode where not needed CharSet.Unicode is only needed when args are string type. https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.charset(v=vs.110).aspx --- src/runtime/runtime.cs | 45 ++++++++++++++---------------------------- 1 file changed, 15 insertions(+), 30 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 019b2bd2f..75e062ac2 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1370,8 +1370,7 @@ internal static extern IntPtr int size ); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Unicode)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, int size); #elif PYTHON2 @@ -1395,13 +1394,11 @@ internal static bool PyUnicode_Check(IntPtr ob) } #if UCS2 && PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Unicode)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Unicode)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); @@ -1416,30 +1413,25 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) return PyUnicode_FromKindAndString(2, s, size); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Unicode)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Unicode)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Unicode)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS2 && PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_FromObject", - CharSet = CharSet.Unicode)] + EntryPoint = "PyUnicodeUCS2_FromObject")] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_FromEncodedObject", - CharSet = CharSet.Unicode)] + EntryPoint = "PyUnicodeUCS2_FromEncodedObject")] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); @@ -1460,18 +1452,15 @@ internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_FromOrdinal", - CharSet = CharSet.Unicode)] + EntryPoint = "PyUnicodeUCS2_FromOrdinal")] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Unicode)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Unicode)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); @@ -1497,20 +1486,17 @@ internal unsafe static extern int internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - CharSet = CharSet.Unicode)] + [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON2 [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_FromObject", - CharSet = CharSet.Unicode)] + EntryPoint = "PyUnicodeUCS4_FromObject")] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_FromEncodedObject", - CharSet = CharSet.Unicode)] + EntryPoint = "PyUnicodeUCS4_FromEncodedObject")] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); @@ -1533,8 +1519,7 @@ internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_FromOrdinal", - CharSet = CharSet.Unicode)] + EntryPoint = "PyUnicodeUCS4_FromOrdinal")] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #endif From f1aa89bb4620c98b8c6eeeb6431a0ca83add7602 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 23 Feb 2017 23:51:21 -0700 Subject: [PATCH 202/245] Remove CallingConvention --- src/runtime/runtime.cs | 533 ++++++++++++++++++++--------------------- 1 file changed, 256 insertions(+), 277 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 75e062ac2..c642056ab 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -583,241 +583,241 @@ internal unsafe static long Refcount(IntPtr op) #if Py_DEBUG // Py_IncRef and Py_DecRef are taking care of the extra payload // in Py_DEBUG builds of Python like _Py_RefTotal - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] private unsafe static extern void Py_IncRef(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] private unsafe static extern void Py_DecRef(IntPtr ob); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void Py_Initialize(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int Py_IsInitialized(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void Py_Finalize(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr Py_NewInterpreter(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void Py_EndInterpreter(IntPtr threadState); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyThreadState_New(IntPtr istate); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyThreadState_Get(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyThread_get_key_value(IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyThread_get_thread_ident(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyThread_set_key_value(IntPtr key, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyThreadState_Swap(IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyGILState_Ensure(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyGILState_Release(IntPtr gs); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyGILState_GetThisThreadState(); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] public unsafe static extern int Py_Main( int argc, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv ); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] public unsafe static extern int Py_Main(int argc, string[] argv); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyEval_InitThreads(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyEval_ThreadsInitialized(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyEval_AcquireLock(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyEval_ReleaseLock(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyEval_AcquireThread(IntPtr tstate); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyEval_ReleaseThread(IntPtr tstate); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyEval_SaveThread(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyEval_RestoreThread(IntPtr tstate); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyEval_GetBuiltins(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyEval_GetGlobals(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyEval_GetLocals(); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetProgramName(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void Py_SetProgramName([MarshalAs(UnmanagedType.LPWStr)] string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetPythonHome(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void Py_SetPythonHome([MarshalAs(UnmanagedType.LPWStr)] string home); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetPath(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void Py_SetPath([MarshalAs(UnmanagedType.LPWStr)] string home); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string Py_GetProgramName(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void Py_SetProgramName(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string Py_GetPythonHome(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void Py_SetPythonHome(string home); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string Py_GetPath(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void Py_SetPath(string home); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string Py_GetVersion(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string Py_GetPlatform(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string Py_GetCopyright(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string Py_GetCompiler(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string Py_GetBuildInfo(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyRun_SimpleString(string code); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr Py_CompileString(string code, string file, IntPtr tok); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyImport_ExecCodeModule(string name, IntPtr code); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyClass_New(IntPtr bases, IntPtr dict, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyInstance_NewRaw(IntPtr cls, IntPtr dict); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); @@ -874,56 +874,56 @@ internal static string PyObject_GetTypeName(IntPtr op) return Marshal.PtrToStringAnsi(ppName); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_HasAttrString(IntPtr pointer, string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_GetAttrString(IntPtr pointer, string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_HasAttr(IntPtr pointer, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_GetAttr(IntPtr pointer, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_GetItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_DelItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_GetIter(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); @@ -952,60 +952,59 @@ internal static int PyObject_Compare(IntPtr value1, IntPtr value2) return -1; } #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_Compare(IntPtr value1, IntPtr value2); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_IsInstance(IntPtr ob, IntPtr type); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_IsSubclass(IntPtr ob, IntPtr type); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyCallable_Check(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_IsTrue(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_Not(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_Size(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_Hash(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_Repr(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_Str(IntPtr pointer); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyObject_Str")] + [DllImport(Runtime.dll, EntryPoint = "PyObject_Str")] internal unsafe static extern IntPtr PyObject_Unicode(IntPtr pointer); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_Unicode(IntPtr pointer); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_Dir(IntPtr pointer); @@ -1015,27 +1014,26 @@ internal unsafe static extern IntPtr //==================================================================== #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyNumber_Long")] + [DllImport(Runtime.dll, EntryPoint = "PyNumber_Long")] internal unsafe static extern IntPtr PyNumber_Int(IntPtr ob); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Int(IntPtr ob); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Long(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Float(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern bool PyNumber_Check(IntPtr ob); @@ -1063,40 +1061,36 @@ internal static IntPtr PyInt_FromInt64(long value) } #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyLong_FromLong")] + [DllImport(Runtime.dll, EntryPoint = "PyLong_FromLong")] private unsafe static extern IntPtr PyInt_FromLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyLong_AsLong")] + [DllImport(Runtime.dll, EntryPoint = "PyLong_AsLong")] internal unsafe static extern int PyInt_AsLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyLong_FromString")] + [DllImport(Runtime.dll, EntryPoint = "PyLong_FromString")] internal unsafe static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyLong_GetMax")] + [DllImport(Runtime.dll, EntryPoint = "PyLong_GetMax")] internal unsafe static extern int PyInt_GetMax(); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] private unsafe static extern IntPtr PyInt_FromLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyInt_AsLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyInt_GetMax(); #endif @@ -1106,43 +1100,43 @@ internal static bool PyLong_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyLongType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyLong_FromLong(long value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyLong_FromUnsignedLong(uint value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyLong_FromDouble(double value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyLong_FromLongLong(long value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyLong_FromUnsignedLongLong(ulong value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyLong_FromString(string value, IntPtr end, int radix); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyLong_AsLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern uint PyLong_AsUnsignedLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern long PyLong_AsLongLong(IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern ulong PyLong_AsUnsignedLongLong(IntPtr value); @@ -1152,115 +1146,115 @@ internal static bool PyFloat_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyFloatType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyFloat_FromDouble(double value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyFloat_FromString(IntPtr value, IntPtr junk); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern double PyFloat_AsDouble(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Add(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Subtract(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Multiply(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Divide(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_And(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Xor(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Or(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Lshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Rshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Power(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Remainder(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceAdd(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceSubtract(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceMultiply(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceDivide(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceAnd(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceXor(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceOr(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceLshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceRshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlacePower(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_InPlaceRemainder(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Negative(IntPtr o1); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Positive(IntPtr o1); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyNumber_Invert(IntPtr o1); @@ -1268,63 +1262,63 @@ internal unsafe static extern IntPtr // Python sequence API //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern bool PySequence_Check(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PySequence_GetItem(IntPtr pointer, int index); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PySequence_SetItem(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PySequence_DelItem(IntPtr pointer, int index); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PySequence_GetSlice(IntPtr pointer, int i1, int i2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PySequence_SetSlice(IntPtr pointer, int i1, int i2, IntPtr v); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PySequence_DelSlice(IntPtr pointer, int i1, int i2); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PySequence_Size(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PySequence_Contains(IntPtr pointer, IntPtr item); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PySequence_Concat(IntPtr pointer, IntPtr other); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PySequence_Repeat(IntPtr pointer, int count); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PySequence_Index(IntPtr pointer, IntPtr item); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PySequence_Count(IntPtr pointer, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PySequence_Tuple(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PySequence_List(IntPtr pointer); @@ -1350,11 +1344,11 @@ internal static IntPtr PyString_FromString(string value) } #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyBytes_FromString(string op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyBytes_Size(IntPtr op); @@ -1370,20 +1364,19 @@ internal static extern IntPtr int size ); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, int size); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyString_FromStringAndSize(string value, int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyString_AsString")] + [DllImport(Runtime.dll, EntryPoint = "PyString_AsString")] internal unsafe static extern IntPtr PyString_AS_STRING(IntPtr op); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyString_Size(IntPtr pointer); #endif @@ -1394,16 +1387,15 @@ internal static bool PyUnicode_Check(IntPtr ob) } #if UCS2 && PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicode_FromKindAndData", + [DllImport(Runtime.dll, EntryPoint = "PyUnicode_FromKindAndData", CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromKindAndString(int kind, string s, int size); @@ -1413,59 +1405,52 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) return PyUnicode_FromKindAndString(2, s, size); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS2 && PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_FromObject")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_FromObject")] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_FromEncodedObject")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_FromEncodedObject")] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_FromUnicode", + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_FromUnicode", CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromUnicode(string s, int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_GetSize")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_GetSize")] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_AsUnicode")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_AsUnicode")] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS2_FromOrdinal")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_FromOrdinal")] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicode_FromKindAndData")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicode_FromKindAndData")] internal unsafe static extern IntPtr PyUnicode_FromKindAndString( int kind, @@ -1478,48 +1463,42 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) return PyUnicode_FromKindAndString(4, s, size); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_FromObject")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_FromObject")] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_FromEncodedObject")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_FromEncodedObject")] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_FromUnicode")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_FromUnicode")] internal unsafe static extern IntPtr PyUnicode_FromUnicode( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, int size ); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_GetSize")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_GetSize")] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_AsUnicode")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_AsUnicode")] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl, - EntryPoint = "PyUnicodeUCS4_FromOrdinal")] + [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_FromOrdinal")] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #endif @@ -1579,67 +1558,67 @@ internal static bool PyDict_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyDictType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyDict_New(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyDictProxy_New(IntPtr dict); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyDict_GetItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyDict_GetItemString(IntPtr pointer, string key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyDict_SetItemString(IntPtr pointer, string key, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyDict_DelItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyDict_DelItemString(IntPtr pointer, string key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyMapping_HasKey(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyDict_Keys(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyDict_Values(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyDict_Items(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyDict_Copy(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyDict_Update(IntPtr pointer, IntPtr other); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyDict_Clear(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyDict_Size(IntPtr pointer); @@ -1653,47 +1632,47 @@ internal static bool PyList_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyListType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyList_New(int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyList_AsTuple(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyList_GetItem(IntPtr pointer, int index); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyList_SetItem(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyList_Insert(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyList_Append(IntPtr pointer, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyList_Reverse(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyList_Sort(IntPtr pointer); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyList_GetSlice(IntPtr pointer, int start, int end); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyList_SetSlice(IntPtr pointer, int start, int end, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyList_Size(IntPtr pointer); @@ -1707,23 +1686,23 @@ internal static bool PyTuple_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyTupleType; } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyTuple_New(int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyTuple_GetItem(IntPtr pointer, int index); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyTuple_SetItem(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyTuple_GetSlice(IntPtr pointer, int start, int end); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyTuple_Size(IntPtr pointer); @@ -1733,7 +1712,7 @@ internal unsafe static extern int //==================================================================== #if PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern bool PyIter_Check(IntPtr pointer); #elif PYTHON3 @@ -1746,7 +1725,7 @@ internal static bool } #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyIter_Next(IntPtr pointer); @@ -1754,50 +1733,50 @@ internal unsafe static extern IntPtr // Python module API //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyModule_New(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string PyModule_GetName(IntPtr module); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyModule_GetDict(IntPtr module); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern string PyModule_GetFilename(IntPtr module); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyModule_Create2(IntPtr module, int apiver); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyImport_Import(IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyImport_ImportModule(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyImport_ReloadModule(IntPtr module); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyImport_AddModule(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyImport_GetModuleDict(); #if PYTHON3 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PySys_SetArgvEx( int argc, @@ -1805,7 +1784,7 @@ internal unsafe static extern void int updatepath ); #elif PYTHON2 - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PySys_SetArgvEx( int argc, @@ -1814,11 +1793,11 @@ int updatepath ); #endif - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PySys_GetObject(string name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PySys_SetObject(string name, IntPtr ob); @@ -1832,11 +1811,11 @@ internal static bool PyType_Check(IntPtr ob) return PyObject_TypeCheck(ob, Runtime.PyTypeType); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyType_Modified(IntPtr type); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern bool PyType_IsSubtype(IntPtr t1, IntPtr t2); @@ -1846,47 +1825,47 @@ internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) return (t == tp) || PyType_IsSubtype(t, tp); } - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyType_GenericAlloc(IntPtr type, int n); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyType_Ready(IntPtr type); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr _PyType_Lookup(IntPtr type, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_GenericGetAttr(IntPtr obj, IntPtr name); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr _PyObject_GetDictPtr(IntPtr obj); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyObject_GC_New(IntPtr tp); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyObject_GC_Del(IntPtr tp); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyObject_GC_Track(IntPtr tp); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyObject_GC_UnTrack(IntPtr tp); @@ -1895,15 +1874,15 @@ internal unsafe static extern void // Python memory API //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyMem_Malloc(int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyMem_Realloc(IntPtr ptr, int size); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyMem_Free(IntPtr ptr); @@ -1912,51 +1891,51 @@ internal unsafe static extern void // Python exception API //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyErr_SetString(IntPtr ob, string message); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyErr_SetObject(IntPtr ob, IntPtr message); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyErr_SetFromErrno(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyErr_SetNone(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyErr_ExceptionMatches(IntPtr exception); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern int PyErr_Occurred(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyErr_Clear(); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern void PyErr_Print(); @@ -1965,11 +1944,11 @@ internal unsafe static extern void // Miscellaneous //==================================================================== - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyMethod_Self(IntPtr ob); - [DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl)] + [DllImport(Runtime.dll)] internal unsafe static extern IntPtr PyMethod_Function(IntPtr ob); } From 5b3f58afdb893abdfd2c5219b972c65daa5ea4cc Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 26 Feb 2017 15:28:43 -0700 Subject: [PATCH 203/245] Rename Runtime field `dll` to `PythonDll` Add remove full qualification --- src/runtime/runtime.cs | 524 ++++++++++++++++++++--------------------- 1 file changed, 261 insertions(+), 263 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index c642056ab..bef31d758 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -157,9 +157,9 @@ public class Runtime #endif #if PYTHON_WITHOUT_ENABLE_SHARED - public const string dll = "__Internal"; + public const string PythonDll = "__Internal"; #else - public const string dll = dllBase + dllWithPyDebug + dllWithPyMalloc + dllWithWideUnicode; + public const string PythonDll = dllBase + dllWithPyDebug + dllWithPyMalloc + dllWithWideUnicode; #endif // set to true when python is finalizing @@ -295,9 +295,9 @@ internal static void Initialize() #if PYTHON3 IntPtr dllLocal = IntPtr.Zero; - if (Runtime.dll != "__Internal") + if (PythonDll != "__Internal") { - NativeMethods.LoadLibrary(Runtime.dll); + NativeMethods.LoadLibrary(PythonDll); } _PyObject_NextNotImplemented = NativeMethods.GetProcAddress(dllLocal, "_PyObject_NextNotImplemented"); #if !(MONO_LINUX || MONO_OSX) @@ -583,241 +583,241 @@ internal unsafe static long Refcount(IntPtr op) #if Py_DEBUG // Py_IncRef and Py_DecRef are taking care of the extra payload // in Py_DEBUG builds of Python like _Py_RefTotal - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] private unsafe static extern void Py_IncRef(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] private unsafe static extern void Py_DecRef(IntPtr ob); #endif - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void Py_Initialize(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int Py_IsInitialized(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void Py_Finalize(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr Py_NewInterpreter(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void Py_EndInterpreter(IntPtr threadState); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyThreadState_New(IntPtr istate); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyThreadState_Get(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyThread_get_key_value(IntPtr key); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyThread_get_thread_ident(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyThread_set_key_value(IntPtr key, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyThreadState_Swap(IntPtr key); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyGILState_Ensure(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyGILState_Release(IntPtr gs); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyGILState_GetThisThreadState(); #if PYTHON3 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] public unsafe static extern int Py_Main( int argc, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv ); #elif PYTHON2 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] public unsafe static extern int Py_Main(int argc, string[] argv); #endif - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyEval_InitThreads(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyEval_ThreadsInitialized(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyEval_AcquireLock(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyEval_ReleaseLock(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyEval_AcquireThread(IntPtr tstate); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyEval_ReleaseThread(IntPtr tstate); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyEval_SaveThread(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyEval_RestoreThread(IntPtr tstate); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyEval_GetBuiltins(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyEval_GetGlobals(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyEval_GetLocals(); #if PYTHON3 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetProgramName(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void Py_SetProgramName([MarshalAs(UnmanagedType.LPWStr)] string name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetPythonHome(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void Py_SetPythonHome([MarshalAs(UnmanagedType.LPWStr)] string home); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] [return: MarshalAs(UnmanagedType.LPWStr)] internal unsafe static extern string Py_GetPath(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void Py_SetPath([MarshalAs(UnmanagedType.LPWStr)] string home); #elif PYTHON2 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string Py_GetProgramName(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void Py_SetProgramName(string name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string Py_GetPythonHome(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void Py_SetPythonHome(string home); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string Py_GetPath(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void Py_SetPath(string home); #endif - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string Py_GetVersion(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string Py_GetPlatform(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string Py_GetCopyright(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string Py_GetCompiler(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string Py_GetBuildInfo(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyRun_SimpleString(string code); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr Py_CompileString(string code, string file, IntPtr tok); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyImport_ExecCodeModule(string name, IntPtr code); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyClass_New(IntPtr bases, IntPtr dict, IntPtr name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyInstance_NewRaw(IntPtr cls, IntPtr dict); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); @@ -874,56 +874,56 @@ internal static string PyObject_GetTypeName(IntPtr op) return Marshal.PtrToStringAnsi(ppName); } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_HasAttrString(IntPtr pointer, string name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_GetAttrString(IntPtr pointer, string name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_HasAttr(IntPtr pointer, IntPtr name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_GetAttr(IntPtr pointer, IntPtr name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_GetItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_DelItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_GetIter(IntPtr op); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args); #if PYTHON3 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); @@ -952,59 +952,59 @@ internal static int PyObject_Compare(IntPtr value1, IntPtr value2) return -1; } #elif PYTHON2 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_Compare(IntPtr value1, IntPtr value2); #endif - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_IsInstance(IntPtr ob, IntPtr type); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_IsSubclass(IntPtr ob, IntPtr type); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyCallable_Check(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_IsTrue(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_Not(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_Size(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_Hash(IntPtr op); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_Repr(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_Str(IntPtr pointer); #if PYTHON3 - [DllImport(Runtime.dll, EntryPoint = "PyObject_Str")] + [DllImport(PythonDll, EntryPoint = "PyObject_Str")] internal unsafe static extern IntPtr PyObject_Unicode(IntPtr pointer); #elif PYTHON2 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_Unicode(IntPtr pointer); #endif - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_Dir(IntPtr pointer); @@ -1014,26 +1014,26 @@ internal unsafe static extern IntPtr //==================================================================== #if PYTHON3 - [DllImport(Runtime.dll, EntryPoint = "PyNumber_Long")] + [DllImport(PythonDll, EntryPoint = "PyNumber_Long")] internal unsafe static extern IntPtr PyNumber_Int(IntPtr ob); #elif PYTHON2 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Int(IntPtr ob); #endif - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Long(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Float(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern bool PyNumber_Check(IntPtr ob); @@ -1061,36 +1061,36 @@ internal static IntPtr PyInt_FromInt64(long value) } #if PYTHON3 - [DllImport(Runtime.dll, EntryPoint = "PyLong_FromLong")] + [DllImport(PythonDll, EntryPoint = "PyLong_FromLong")] private unsafe static extern IntPtr PyInt_FromLong(IntPtr value); - [DllImport(Runtime.dll, EntryPoint = "PyLong_AsLong")] + [DllImport(PythonDll, EntryPoint = "PyLong_AsLong")] internal unsafe static extern int PyInt_AsLong(IntPtr value); - [DllImport(Runtime.dll, EntryPoint = "PyLong_FromString")] + [DllImport(PythonDll, EntryPoint = "PyLong_FromString")] internal unsafe static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); - [DllImport(Runtime.dll, EntryPoint = "PyLong_GetMax")] + [DllImport(PythonDll, EntryPoint = "PyLong_GetMax")] internal unsafe static extern int PyInt_GetMax(); #elif PYTHON2 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] private unsafe static extern IntPtr PyInt_FromLong(IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyInt_AsLong(IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyInt_GetMax(); #endif @@ -1100,43 +1100,43 @@ internal static bool PyLong_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyLongType; } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyLong_FromLong(long value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyLong_FromUnsignedLong(uint value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyLong_FromDouble(double value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyLong_FromLongLong(long value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyLong_FromUnsignedLongLong(ulong value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyLong_FromString(string value, IntPtr end, int radix); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyLong_AsLong(IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern uint PyLong_AsUnsignedLong(IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern long PyLong_AsLongLong(IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern ulong PyLong_AsUnsignedLongLong(IntPtr value); @@ -1146,115 +1146,115 @@ internal static bool PyFloat_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyFloatType; } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyFloat_FromDouble(double value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyFloat_FromString(IntPtr value, IntPtr junk); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern double PyFloat_AsDouble(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Add(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Subtract(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Multiply(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Divide(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_And(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Xor(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Or(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Lshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Rshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Power(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Remainder(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceAdd(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceSubtract(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceMultiply(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceDivide(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceAnd(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceXor(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceOr(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceLshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceRshift(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlacePower(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_InPlaceRemainder(IntPtr o1, IntPtr o2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Negative(IntPtr o1); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Positive(IntPtr o1); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyNumber_Invert(IntPtr o1); @@ -1262,63 +1262,63 @@ internal unsafe static extern IntPtr // Python sequence API //==================================================================== - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern bool PySequence_Check(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PySequence_GetItem(IntPtr pointer, int index); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PySequence_SetItem(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PySequence_DelItem(IntPtr pointer, int index); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PySequence_GetSlice(IntPtr pointer, int i1, int i2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PySequence_SetSlice(IntPtr pointer, int i1, int i2, IntPtr v); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PySequence_DelSlice(IntPtr pointer, int i1, int i2); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PySequence_Size(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PySequence_Contains(IntPtr pointer, IntPtr item); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PySequence_Concat(IntPtr pointer, IntPtr other); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PySequence_Repeat(IntPtr pointer, int count); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PySequence_Index(IntPtr pointer, IntPtr item); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PySequence_Count(IntPtr pointer, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PySequence_Tuple(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PySequence_List(IntPtr pointer); @@ -1344,11 +1344,11 @@ internal static IntPtr PyString_FromString(string value) } #if PYTHON3 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyBytes_FromString(string op); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyBytes_Size(IntPtr op); @@ -1357,26 +1357,26 @@ internal static IntPtr PyBytes_AS_STRING(IntPtr ob) return ob + BytesOffset.ob_sval; } - [DllImport(Runtime.dll, EntryPoint = "PyUnicode_FromStringAndSize")] + [DllImport(PythonDll, EntryPoint = "PyUnicode_FromStringAndSize")] internal static extern IntPtr PyString_FromStringAndSize( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(Utf8Marshaler))] string value, int size ); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, int size); #elif PYTHON2 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyString_FromStringAndSize(string value, int size); - [DllImport(Runtime.dll, EntryPoint = "PyString_AsString")] + [DllImport(PythonDll, EntryPoint = "PyString_AsString")] internal unsafe static extern IntPtr PyString_AS_STRING(IntPtr op); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyString_Size(IntPtr pointer); #endif @@ -1387,16 +1387,15 @@ internal static bool PyUnicode_Check(IntPtr ob) } #if UCS2 && PYTHON3 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(Runtime.dll, EntryPoint = "PyUnicode_FromKindAndData", - CharSet = CharSet.Unicode)] + [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData", CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromKindAndString(int kind, string s, int size); @@ -1405,52 +1404,51 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) return PyUnicode_FromKindAndString(2, s, size); } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS2 && PYTHON2 - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_FromObject")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromObject")] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_FromEncodedObject")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromEncodedObject")] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_FromUnicode", - CharSet = CharSet.Unicode)] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromUnicode", CharSet = CharSet.Unicode)] internal unsafe static extern IntPtr PyUnicode_FromUnicode(string s, int size); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_GetSize")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_GetSize")] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_AsUnicode")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_AsUnicode")] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS2_FromOrdinal")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromOrdinal")] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON3 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(Runtime.dll, EntryPoint = "PyUnicode_FromKindAndData")] + [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData")] internal unsafe static extern IntPtr PyUnicode_FromKindAndString( int kind, @@ -1463,42 +1461,42 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) return PyUnicode_FromKindAndString(4, s, size); } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON2 - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_FromObject")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromObject")] internal unsafe static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_FromEncodedObject")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromEncodedObject")] internal unsafe static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_FromUnicode")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromUnicode")] internal unsafe static extern IntPtr PyUnicode_FromUnicode( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, int size ); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_GetSize")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_GetSize")] internal unsafe static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_AsUnicode")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_AsUnicode")] internal unsafe static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(Runtime.dll, EntryPoint = "PyUnicodeUCS4_FromOrdinal")] + [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromOrdinal")] internal unsafe static extern IntPtr PyUnicode_FromOrdinal(int c); #endif @@ -1558,67 +1556,67 @@ internal static bool PyDict_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyDictType; } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyDict_New(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyDictProxy_New(IntPtr dict); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyDict_GetItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyDict_GetItemString(IntPtr pointer, string key); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyDict_SetItemString(IntPtr pointer, string key, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyDict_DelItem(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyDict_DelItemString(IntPtr pointer, string key); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyMapping_HasKey(IntPtr pointer, IntPtr key); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyDict_Keys(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyDict_Values(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyDict_Items(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyDict_Copy(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyDict_Update(IntPtr pointer, IntPtr other); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyDict_Clear(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyDict_Size(IntPtr pointer); @@ -1632,47 +1630,47 @@ internal static bool PyList_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyListType; } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyList_New(int size); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyList_AsTuple(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyList_GetItem(IntPtr pointer, int index); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyList_SetItem(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyList_Insert(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyList_Append(IntPtr pointer, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyList_Reverse(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyList_Sort(IntPtr pointer); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyList_GetSlice(IntPtr pointer, int start, int end); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyList_SetSlice(IntPtr pointer, int start, int end, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyList_Size(IntPtr pointer); @@ -1686,23 +1684,23 @@ internal static bool PyTuple_Check(IntPtr ob) return PyObject_TYPE(ob) == Runtime.PyTupleType; } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyTuple_New(int size); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyTuple_GetItem(IntPtr pointer, int index); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyTuple_SetItem(IntPtr pointer, int index, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyTuple_GetSlice(IntPtr pointer, int start, int end); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyTuple_Size(IntPtr pointer); @@ -1712,7 +1710,7 @@ internal unsafe static extern int //==================================================================== #if PYTHON2 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern bool PyIter_Check(IntPtr pointer); #elif PYTHON3 @@ -1725,7 +1723,7 @@ internal static bool } #endif - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyIter_Next(IntPtr pointer); @@ -1733,50 +1731,50 @@ internal unsafe static extern IntPtr // Python module API //==================================================================== - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyModule_New(string name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string PyModule_GetName(IntPtr module); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyModule_GetDict(IntPtr module); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern string PyModule_GetFilename(IntPtr module); #if PYTHON3 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyModule_Create2(IntPtr module, int apiver); #endif - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyImport_Import(IntPtr name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyImport_ImportModule(string name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyImport_ReloadModule(IntPtr module); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyImport_AddModule(string name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyImport_GetModuleDict(); #if PYTHON3 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PySys_SetArgvEx( int argc, @@ -1784,7 +1782,7 @@ internal unsafe static extern void int updatepath ); #elif PYTHON2 - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PySys_SetArgvEx( int argc, @@ -1793,11 +1791,11 @@ int updatepath ); #endif - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PySys_GetObject(string name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PySys_SetObject(string name, IntPtr ob); @@ -1811,11 +1809,11 @@ internal static bool PyType_Check(IntPtr ob) return PyObject_TypeCheck(ob, Runtime.PyTypeType); } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyType_Modified(IntPtr type); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern bool PyType_IsSubtype(IntPtr t1, IntPtr t2); @@ -1825,47 +1823,47 @@ internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) return (t == tp) || PyType_IsSubtype(t, tp); } - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyType_GenericAlloc(IntPtr type, int n); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyType_Ready(IntPtr type); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr _PyType_Lookup(IntPtr type, IntPtr name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_GenericGetAttr(IntPtr obj, IntPtr name); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr _PyObject_GetDictPtr(IntPtr obj); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyObject_GC_New(IntPtr tp); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyObject_GC_Del(IntPtr tp); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyObject_GC_Track(IntPtr tp); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyObject_GC_UnTrack(IntPtr tp); @@ -1874,15 +1872,15 @@ internal unsafe static extern void // Python memory API //==================================================================== - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyMem_Malloc(int size); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyMem_Realloc(IntPtr ptr, int size); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyMem_Free(IntPtr ptr); @@ -1891,51 +1889,51 @@ internal unsafe static extern void // Python exception API //==================================================================== - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyErr_SetString(IntPtr ob, string message); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyErr_SetObject(IntPtr ob, IntPtr message); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyErr_SetFromErrno(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyErr_SetNone(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyErr_ExceptionMatches(IntPtr exception); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern int PyErr_Occurred(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyErr_Clear(); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern void PyErr_Print(); @@ -1944,11 +1942,11 @@ internal unsafe static extern void // Miscellaneous //==================================================================== - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyMethod_Self(IntPtr ob); - [DllImport(Runtime.dll)] + [DllImport(PythonDll)] internal unsafe static extern IntPtr PyMethod_Function(IntPtr ob); } From c8906911c07b82551aa4c88aae72f66d6fbf9b4f Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 27 Feb 2017 22:05:58 -0700 Subject: [PATCH 204/245] Remove unneeded unsafe keyword --- src/runtime/exceptions.cs | 5 +- src/runtime/runtime.cs | 520 +++++++++++++++++++------------------- 2 files changed, 262 insertions(+), 263 deletions(-) diff --git a/src/runtime/exceptions.cs b/src/runtime/exceptions.cs index 21300f500..9023cfcfa 100644 --- a/src/runtime/exceptions.cs +++ b/src/runtime/exceptions.cs @@ -2,7 +2,6 @@ using System.Reflection; using System.Runtime.InteropServices; - namespace Python.Runtime { /// @@ -171,7 +170,7 @@ internal static void SetArgsAndCause(IntPtr ob) /// Shortcut for (pointer == NULL) -> throw PythonException /// /// Pointer to a Python object - internal static unsafe void ErrorCheck(IntPtr pointer) + internal static void ErrorCheck(IntPtr pointer) { if (pointer == IntPtr.Zero) { @@ -182,7 +181,7 @@ internal static unsafe void ErrorCheck(IntPtr pointer) /// /// Shortcut for (pointer == NULL or ErrorOccurred()) -> throw PythonException /// - internal static unsafe void ErrorOccurredCheck(IntPtr pointer) + internal static void ErrorOccurredCheck(IntPtr pointer) { if (pointer == IntPtr.Zero || ErrorOccurred()) { diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index bef31d758..5287ead92 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -501,7 +501,7 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) /// some optimization to avoid managed <--> unmanaged transitions /// (mostly for heavily used methods). /// - internal unsafe static void XIncref(IntPtr op) + internal static unsafe void XIncref(IntPtr op) { #if Py_DEBUG // according to Python doc, Py_IncRef() is Py_XINCREF() @@ -563,7 +563,7 @@ internal static unsafe void XDecref(IntPtr op) #endif } - internal unsafe static long Refcount(IntPtr op) + internal static unsafe long Refcount(IntPtr op) { void* p = (void*)op; if ((void*)0 != p) @@ -584,241 +584,241 @@ internal unsafe static long Refcount(IntPtr op) // Py_IncRef and Py_DecRef are taking care of the extra payload // in Py_DEBUG builds of Python like _Py_RefTotal [DllImport(PythonDll)] - private unsafe static extern void + private static extern void Py_IncRef(IntPtr ob); [DllImport(PythonDll)] - private unsafe static extern void + private static extern void Py_DecRef(IntPtr ob); #endif [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void Py_Initialize(); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int Py_IsInitialized(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void Py_Finalize(); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr Py_NewInterpreter(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void Py_EndInterpreter(IntPtr threadState); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyThreadState_New(IntPtr istate); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyThreadState_Get(); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyThread_get_key_value(IntPtr key); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyThread_get_thread_ident(); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyThread_set_key_value(IntPtr key, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyThreadState_Swap(IntPtr key); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyGILState_Ensure(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyGILState_Release(IntPtr gs); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyGILState_GetThisThreadState(); #if PYTHON3 [DllImport(PythonDll)] - public unsafe static extern int + public static extern int Py_Main( int argc, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv ); #elif PYTHON2 [DllImport(PythonDll)] - public unsafe static extern int + public static extern int Py_Main(int argc, string[] argv); #endif [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyEval_InitThreads(); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyEval_ThreadsInitialized(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyEval_AcquireLock(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyEval_ReleaseLock(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyEval_AcquireThread(IntPtr tstate); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyEval_ReleaseThread(IntPtr tstate); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyEval_SaveThread(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyEval_RestoreThread(IntPtr tstate); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyEval_GetBuiltins(); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyEval_GetGlobals(); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyEval_GetLocals(); #if PYTHON3 [DllImport(PythonDll)] [return: MarshalAs(UnmanagedType.LPWStr)] - internal unsafe static extern string + internal static extern string Py_GetProgramName(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void Py_SetProgramName([MarshalAs(UnmanagedType.LPWStr)] string name); [DllImport(PythonDll)] [return: MarshalAs(UnmanagedType.LPWStr)] - internal unsafe static extern string + internal static extern string Py_GetPythonHome(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void Py_SetPythonHome([MarshalAs(UnmanagedType.LPWStr)] string home); [DllImport(PythonDll)] [return: MarshalAs(UnmanagedType.LPWStr)] - internal unsafe static extern string + internal static extern string Py_GetPath(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void Py_SetPath([MarshalAs(UnmanagedType.LPWStr)] string home); #elif PYTHON2 [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string Py_GetProgramName(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void Py_SetProgramName(string name); [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string Py_GetPythonHome(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void Py_SetPythonHome(string home); [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string Py_GetPath(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void Py_SetPath(string home); #endif [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string Py_GetVersion(); [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string Py_GetPlatform(); [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string Py_GetCopyright(); [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string Py_GetCompiler(); [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string Py_GetBuildInfo(); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyRun_SimpleString(string code); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr Py_CompileString(string code, string file, IntPtr tok); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyImport_ExecCodeModule(string name, IntPtr code); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyClass_New(IntPtr bases, IntPtr dict, IntPtr name); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyInstance_NewRaw(IntPtr cls, IntPtr dict); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); @@ -831,7 +831,7 @@ internal unsafe static extern IntPtr /// designed to be lean and mean in IL & avoid managed <-> unmanaged /// transitions. Note that this does not incref the type object. /// - internal unsafe static IntPtr + internal static unsafe IntPtr PyObject_TYPE(IntPtr op) { void* p = (void*)op; @@ -859,7 +859,7 @@ internal unsafe static IntPtr /// This version avoids a managed <-> unmanaged transition. This one /// does incref the returned type object. /// - internal unsafe static IntPtr + internal static IntPtr PyObject_Type(IntPtr op) { IntPtr tp = PyObject_TYPE(op); @@ -875,56 +875,56 @@ internal static string PyObject_GetTypeName(IntPtr op) } [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_HasAttrString(IntPtr pointer, string name); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_GetAttrString(IntPtr pointer, string name); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_HasAttr(IntPtr pointer, IntPtr name); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_GetAttr(IntPtr pointer, IntPtr name); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_GetItem(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_DelItem(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_GetIter(IntPtr op); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args); #if PYTHON3 [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); internal static int PyObject_Compare(IntPtr value1, IntPtr value2) @@ -953,59 +953,59 @@ internal static int PyObject_Compare(IntPtr value1, IntPtr value2) } #elif PYTHON2 [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_Compare(IntPtr value1, IntPtr value2); #endif [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_IsInstance(IntPtr ob, IntPtr type); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_IsSubclass(IntPtr ob, IntPtr type); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyCallable_Check(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_IsTrue(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_Not(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_Size(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_Hash(IntPtr op); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_Repr(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_Str(IntPtr pointer); #if PYTHON3 [DllImport(PythonDll, EntryPoint = "PyObject_Str")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_Unicode(IntPtr pointer); #elif PYTHON2 [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_Unicode(IntPtr pointer); #endif [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_Dir(IntPtr pointer); @@ -1015,26 +1015,26 @@ internal unsafe static extern IntPtr #if PYTHON3 [DllImport(PythonDll, EntryPoint = "PyNumber_Long")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Int(IntPtr ob); #elif PYTHON2 [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Int(IntPtr ob); #endif [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Long(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Float(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern bool + internal static extern bool PyNumber_Check(IntPtr ob); @@ -1062,36 +1062,36 @@ internal static IntPtr PyInt_FromInt64(long value) #if PYTHON3 [DllImport(PythonDll, EntryPoint = "PyLong_FromLong")] - private unsafe static extern IntPtr + private static extern IntPtr PyInt_FromLong(IntPtr value); [DllImport(PythonDll, EntryPoint = "PyLong_AsLong")] - internal unsafe static extern int + internal static extern int PyInt_AsLong(IntPtr value); [DllImport(PythonDll, EntryPoint = "PyLong_FromString")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); [DllImport(PythonDll, EntryPoint = "PyLong_GetMax")] - internal unsafe static extern int + internal static extern int PyInt_GetMax(); #elif PYTHON2 [DllImport(PythonDll)] - private unsafe static extern IntPtr + private static extern IntPtr PyInt_FromLong(IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyInt_AsLong(IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyInt_GetMax(); #endif @@ -1101,43 +1101,43 @@ internal static bool PyLong_Check(IntPtr ob) } [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyLong_FromLong(long value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyLong_FromUnsignedLong(uint value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyLong_FromDouble(double value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyLong_FromLongLong(long value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyLong_FromUnsignedLongLong(ulong value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyLong_FromString(string value, IntPtr end, int radix); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyLong_AsLong(IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern uint + internal static extern uint PyLong_AsUnsignedLong(IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern long + internal static extern long PyLong_AsLongLong(IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern ulong + internal static extern ulong PyLong_AsUnsignedLongLong(IntPtr value); @@ -1147,115 +1147,115 @@ internal static bool PyFloat_Check(IntPtr ob) } [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyFloat_FromDouble(double value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyFloat_FromString(IntPtr value, IntPtr junk); [DllImport(PythonDll)] - internal unsafe static extern double + internal static extern double PyFloat_AsDouble(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Add(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Subtract(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Multiply(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Divide(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_And(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Xor(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Or(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Lshift(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Rshift(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Power(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Remainder(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceAdd(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceSubtract(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceMultiply(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceDivide(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceAnd(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceXor(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceOr(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceLshift(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceRshift(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlacePower(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_InPlaceRemainder(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Negative(IntPtr o1); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Positive(IntPtr o1); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyNumber_Invert(IntPtr o1); //==================================================================== @@ -1263,63 +1263,63 @@ internal unsafe static extern IntPtr //==================================================================== [DllImport(PythonDll)] - internal unsafe static extern bool + internal static extern bool PySequence_Check(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PySequence_GetItem(IntPtr pointer, int index); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PySequence_SetItem(IntPtr pointer, int index, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PySequence_DelItem(IntPtr pointer, int index); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PySequence_GetSlice(IntPtr pointer, int i1, int i2); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PySequence_SetSlice(IntPtr pointer, int i1, int i2, IntPtr v); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PySequence_DelSlice(IntPtr pointer, int i1, int i2); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PySequence_Size(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PySequence_Contains(IntPtr pointer, IntPtr item); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PySequence_Concat(IntPtr pointer, IntPtr other); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PySequence_Repeat(IntPtr pointer, int count); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PySequence_Index(IntPtr pointer, IntPtr item); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PySequence_Count(IntPtr pointer, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PySequence_Tuple(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PySequence_List(IntPtr pointer); @@ -1345,11 +1345,11 @@ internal static IntPtr PyString_FromString(string value) #if PYTHON3 [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyBytes_FromString(string op); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyBytes_Size(IntPtr op); internal static IntPtr PyBytes_AS_STRING(IntPtr ob) @@ -1365,19 +1365,19 @@ int size ); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, int size); #elif PYTHON2 [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyString_FromStringAndSize(string value, int size); [DllImport(PythonDll, EntryPoint = "PyString_AsString")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyString_AS_STRING(IntPtr op); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyString_Size(IntPtr pointer); #endif @@ -1388,15 +1388,15 @@ internal static bool PyUnicode_Check(IntPtr ob) #if UCS2 && PYTHON3 [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData", CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromKindAndString(int kind, string s, int size); internal static IntPtr PyUnicode_FromUnicode(string s, int size) @@ -1405,51 +1405,51 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) } [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS2 && PYTHON2 [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromObject")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromEncodedObject")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromUnicode", CharSet = CharSet.Unicode)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromUnicode(string s, int size); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_GetSize")] - internal unsafe static extern int + internal static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_AsUnicode")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromOrdinal")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON3 [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromKindAndString( int kind, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, @@ -1462,42 +1462,42 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) } [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON2 [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromObject")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromEncodedObject")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromUnicode")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromUnicode( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, int size ); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_GetSize")] - internal unsafe static extern int + internal static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_AsUnicode")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromOrdinal")] - internal unsafe static extern IntPtr + internal static extern IntPtr PyUnicode_FromOrdinal(int c); #endif @@ -1557,67 +1557,67 @@ internal static bool PyDict_Check(IntPtr ob) } [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyDict_New(); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyDictProxy_New(IntPtr dict); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyDict_GetItem(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyDict_GetItemString(IntPtr pointer, string key); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyDict_SetItemString(IntPtr pointer, string key, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyDict_DelItem(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyDict_DelItemString(IntPtr pointer, string key); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyMapping_HasKey(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyDict_Keys(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyDict_Values(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyDict_Items(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyDict_Copy(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyDict_Update(IntPtr pointer, IntPtr other); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyDict_Clear(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyDict_Size(IntPtr pointer); @@ -1631,47 +1631,47 @@ internal static bool PyList_Check(IntPtr ob) } [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyList_New(int size); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyList_AsTuple(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyList_GetItem(IntPtr pointer, int index); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyList_SetItem(IntPtr pointer, int index, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyList_Insert(IntPtr pointer, int index, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyList_Append(IntPtr pointer, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyList_Reverse(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyList_Sort(IntPtr pointer); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyList_GetSlice(IntPtr pointer, int start, int end); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyList_SetSlice(IntPtr pointer, int start, int end, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyList_Size(IntPtr pointer); @@ -1685,23 +1685,23 @@ internal static bool PyTuple_Check(IntPtr ob) } [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyTuple_New(int size); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyTuple_GetItem(IntPtr pointer, int index); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyTuple_SetItem(IntPtr pointer, int index, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyTuple_GetSlice(IntPtr pointer, int start, int end); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyTuple_Size(IntPtr pointer); @@ -1711,7 +1711,7 @@ internal unsafe static extern int #if PYTHON2 [DllImport(PythonDll)] - internal unsafe static extern bool + internal static extern bool PyIter_Check(IntPtr pointer); #elif PYTHON3 internal static bool @@ -1724,7 +1724,7 @@ internal static bool #endif [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyIter_Next(IntPtr pointer); //==================================================================== @@ -1732,50 +1732,50 @@ internal unsafe static extern IntPtr //==================================================================== [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyModule_New(string name); [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string PyModule_GetName(IntPtr module); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyModule_GetDict(IntPtr module); [DllImport(PythonDll)] - internal unsafe static extern string + internal static extern string PyModule_GetFilename(IntPtr module); #if PYTHON3 [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyModule_Create2(IntPtr module, int apiver); #endif [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyImport_Import(IntPtr name); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyImport_ImportModule(string name); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyImport_ReloadModule(IntPtr module); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyImport_AddModule(string name); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyImport_GetModuleDict(); #if PYTHON3 [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PySys_SetArgvEx( int argc, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv, @@ -1783,7 +1783,7 @@ int updatepath ); #elif PYTHON2 [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PySys_SetArgvEx( int argc, string[] argv, @@ -1792,11 +1792,11 @@ int updatepath #endif [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PySys_GetObject(string name); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PySys_SetObject(string name, IntPtr ob); @@ -1810,11 +1810,11 @@ internal static bool PyType_Check(IntPtr ob) } [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyType_Modified(IntPtr type); [DllImport(PythonDll)] - internal unsafe static extern bool + internal static extern bool PyType_IsSubtype(IntPtr t1, IntPtr t2); internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) @@ -1824,47 +1824,47 @@ internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) } [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyType_GenericAlloc(IntPtr type, int n); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyType_Ready(IntPtr type); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr _PyType_Lookup(IntPtr type, IntPtr name); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_GenericGetAttr(IntPtr obj, IntPtr name); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr _PyObject_GetDictPtr(IntPtr obj); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyObject_GC_New(IntPtr tp); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyObject_GC_Del(IntPtr tp); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyObject_GC_Track(IntPtr tp); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyObject_GC_UnTrack(IntPtr tp); @@ -1873,15 +1873,15 @@ internal unsafe static extern void //==================================================================== [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyMem_Malloc(int size); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyMem_Realloc(IntPtr ptr, int size); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyMem_Free(IntPtr ptr); @@ -1890,51 +1890,51 @@ internal unsafe static extern void //==================================================================== [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyErr_SetString(IntPtr ob, string message); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyErr_SetObject(IntPtr ob, IntPtr message); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyErr_SetFromErrno(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyErr_SetNone(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyErr_ExceptionMatches(IntPtr exception); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb); [DllImport(PythonDll)] - internal unsafe static extern int + internal static extern int PyErr_Occurred(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyErr_Clear(); [DllImport(PythonDll)] - internal unsafe static extern void + internal static extern void PyErr_Print(); @@ -1943,11 +1943,11 @@ internal unsafe static extern void //==================================================================== [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyMethod_Self(IntPtr ob); [DllImport(PythonDll)] - internal unsafe static extern IntPtr + internal static extern IntPtr PyMethod_Function(IntPtr ob); } } From 59733ea15c1a4c66ab59d2bed7c5738ecb88c3e3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 27 Feb 2017 22:59:52 -0700 Subject: [PATCH 205/245] Update CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ec2a0fb3..f4f9a4e29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Added `tox` for local testing (#345) - Added `requirements.txt` - Added to `PythonEngine` methods `Eval` and `Exec` (#389) +- Added implementations of `ICustomMarshal` (#407) ### Changed From 46660fafb62c0b1fecdf4bc9dc592a8a5fcdf2d8 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 27 Feb 2017 23:25:42 -0700 Subject: [PATCH 206/245] Add Runtime.CheckExceptionOccurred(...) Helps refactor exceptions checks --- src/runtime/pytuple.cs | 20 +++++++------------- src/runtime/runtime.cs | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/runtime/pytuple.cs b/src/runtime/pytuple.cs index b3fb95733..45f3d8350 100644 --- a/src/runtime/pytuple.cs +++ b/src/runtime/pytuple.cs @@ -51,10 +51,7 @@ public PyTuple(PyObject o) public PyTuple() { obj = Runtime.PyTuple_New(0); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -63,6 +60,9 @@ public PyTuple() /// /// /// Creates a new PyTuple from an array of PyObject instances. + /// + /// See caveats about PyTuple_SetItem: + /// https://www.coursehero.com/file/p4j2ogg/important-exceptions-to-this-rule-PyTupleSetItem-and-PyListSetItem-These/ /// public PyTuple(PyObject[] items) { @@ -72,11 +72,8 @@ public PyTuple(PyObject[] items) { IntPtr ptr = items[i].obj; Runtime.XIncref(ptr); - int r = Runtime.PyTuple_SetItem(obj, i, ptr); - if (r < 0) - { - throw new PythonException(); - } + Runtime.PyTuple_SetItem(obj, i, ptr); + Runtime.CheckExceptionOccurred(); } } @@ -104,10 +101,7 @@ public static bool IsTupleType(PyObject value) public static PyTuple AsTuple(PyObject value) { IntPtr op = Runtime.PySequence_Tuple(value.obj); - if (op == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); return new PyTuple(op); } } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 5287ead92..0b3c429e0 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -384,6 +384,21 @@ internal static int AtExit() internal static IntPtr PyNone; internal static IntPtr Error; + /// + /// Check if any Python Exceptions occurred. + /// If any exist throw new PythonException. + /// + /// + /// Can be used instead of `obj == IntPtr.Zero` for example. + /// + internal static void CheckExceptionOccurred() + { + if (PyErr_Occurred() != 0) + { + throw new PythonException(); + } + } + internal static IntPtr GetBoundArgTuple(IntPtr obj, IntPtr args) { if (Runtime.PyObject_TYPE(args) != Runtime.PyTupleType) From 4616921fa693e396664f21ca3132358e0c06fe96 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Mon, 27 Feb 2017 23:27:02 -0700 Subject: [PATCH 207/245] Replace Py.Throw with Runtime.CheckExceptionOccurred --- src/runtime/pythonengine.cs | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 57f6d5074..eb6f9fa4d 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -362,7 +362,7 @@ public static void EndAllowThreads(IntPtr ts) public static PyObject ImportModule(string name) { IntPtr op = Runtime.PyImport_ImportModule(name); - Py.Throw(); + Runtime.CheckExceptionOccurred(); return new PyObject(op); } @@ -377,7 +377,7 @@ public static PyObject ImportModule(string name) public static PyObject ReloadModule(PyObject module) { IntPtr op = Runtime.PyImport_ReloadModule(module.Handle); - Py.Throw(); + Runtime.CheckExceptionOccurred(); return new PyObject(op); } @@ -392,9 +392,9 @@ public static PyObject ReloadModule(PyObject module) public static PyObject ModuleFromString(string name, string code) { IntPtr c = Runtime.Py_CompileString(code, "none", (IntPtr)257); - Py.Throw(); + Runtime.CheckExceptionOccurred(); IntPtr m = Runtime.PyImport_ExecCodeModule(name, c); - Py.Throw(); + Runtime.CheckExceptionOccurred(); return new PyObject(m); } @@ -473,7 +473,7 @@ public static PyObject RunString( code, flag, globals.Value, locals.Value ); - Py.Throw(); + Runtime.CheckExceptionOccurred(); return new PyObject(result); } @@ -600,18 +600,7 @@ public static void SetArgv(IEnumerable argv) { string[] arr = argv.ToArray(); Runtime.PySys_SetArgvEx(arr.Length, arr, 0); - Py.Throw(); - } - } - - internal static void Throw() - { - using (GIL()) - { - if (Runtime.PyErr_Occurred() != 0) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } } } From 6095de8c997661a29c9e8ac60ab5605a3639e83f Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 28 Feb 2017 02:43:59 -0700 Subject: [PATCH 208/245] Whitespace clean-up Runtime --- src/runtime/runtime.cs | 846 ++++++++++++++--------------------------- 1 file changed, 292 insertions(+), 554 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 0b3c429e0..5ec66150d 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -163,7 +163,7 @@ public class Runtime #endif // set to true when python is finalizing - internal static Object IsFinalizingLock = new Object(); + internal static object IsFinalizingLock = new object(); internal static bool IsFinalizing = false; internal static bool Is32Bit; @@ -599,242 +599,190 @@ internal static unsafe long Refcount(IntPtr op) // Py_IncRef and Py_DecRef are taking care of the extra payload // in Py_DEBUG builds of Python like _Py_RefTotal [DllImport(PythonDll)] - private static extern void - Py_IncRef(IntPtr ob); + private static extern void Py_IncRef(IntPtr ob); [DllImport(PythonDll)] - private static extern void - Py_DecRef(IntPtr ob); + private static extern void Py_DecRef(IntPtr ob); #endif [DllImport(PythonDll)] - internal static extern void - Py_Initialize(); + internal static extern void Py_Initialize(); [DllImport(PythonDll)] - internal static extern int - Py_IsInitialized(); + internal static extern int Py_IsInitialized(); [DllImport(PythonDll)] - internal static extern void - Py_Finalize(); + internal static extern void Py_Finalize(); [DllImport(PythonDll)] - internal static extern IntPtr - Py_NewInterpreter(); + internal static extern IntPtr Py_NewInterpreter(); [DllImport(PythonDll)] - internal static extern void - Py_EndInterpreter(IntPtr threadState); + internal static extern void Py_EndInterpreter(IntPtr threadState); [DllImport(PythonDll)] - internal static extern IntPtr - PyThreadState_New(IntPtr istate); + internal static extern IntPtr PyThreadState_New(IntPtr istate); [DllImport(PythonDll)] - internal static extern IntPtr - PyThreadState_Get(); + internal static extern IntPtr PyThreadState_Get(); [DllImport(PythonDll)] - internal static extern IntPtr - PyThread_get_key_value(IntPtr key); + internal static extern IntPtr PyThread_get_key_value(IntPtr key); [DllImport(PythonDll)] - internal static extern int - PyThread_get_thread_ident(); + internal static extern int PyThread_get_thread_ident(); [DllImport(PythonDll)] - internal static extern int - PyThread_set_key_value(IntPtr key, IntPtr value); + internal static extern int PyThread_set_key_value(IntPtr key, IntPtr value); [DllImport(PythonDll)] - internal static extern IntPtr - PyThreadState_Swap(IntPtr key); - + internal static extern IntPtr PyThreadState_Swap(IntPtr key); [DllImport(PythonDll)] - internal static extern IntPtr - PyGILState_Ensure(); + internal static extern IntPtr PyGILState_Ensure(); [DllImport(PythonDll)] - internal static extern void - PyGILState_Release(IntPtr gs); + internal static extern void PyGILState_Release(IntPtr gs); [DllImport(PythonDll)] - internal static extern IntPtr - PyGILState_GetThisThreadState(); + internal static extern IntPtr PyGILState_GetThisThreadState(); #if PYTHON3 [DllImport(PythonDll)] - public static extern int - Py_Main( - int argc, - [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv - ); + public static extern int Py_Main( + int argc, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv + ); #elif PYTHON2 [DllImport(PythonDll)] - public static extern int - Py_Main(int argc, string[] argv); + public static extern int Py_Main(int argc, string[] argv); #endif [DllImport(PythonDll)] - internal static extern void - PyEval_InitThreads(); + internal static extern void PyEval_InitThreads(); [DllImport(PythonDll)] - internal static extern int - PyEval_ThreadsInitialized(); + internal static extern int PyEval_ThreadsInitialized(); [DllImport(PythonDll)] - internal static extern void - PyEval_AcquireLock(); + internal static extern void PyEval_AcquireLock(); [DllImport(PythonDll)] - internal static extern void - PyEval_ReleaseLock(); + internal static extern void PyEval_ReleaseLock(); [DllImport(PythonDll)] - internal static extern void - PyEval_AcquireThread(IntPtr tstate); + internal static extern void PyEval_AcquireThread(IntPtr tstate); [DllImport(PythonDll)] - internal static extern void - PyEval_ReleaseThread(IntPtr tstate); + internal static extern void PyEval_ReleaseThread(IntPtr tstate); [DllImport(PythonDll)] - internal static extern IntPtr - PyEval_SaveThread(); + internal static extern IntPtr PyEval_SaveThread(); [DllImport(PythonDll)] - internal static extern void - PyEval_RestoreThread(IntPtr tstate); + internal static extern void PyEval_RestoreThread(IntPtr tstate); [DllImport(PythonDll)] - internal static extern IntPtr - PyEval_GetBuiltins(); + internal static extern IntPtr PyEval_GetBuiltins(); [DllImport(PythonDll)] - internal static extern IntPtr - PyEval_GetGlobals(); + internal static extern IntPtr PyEval_GetGlobals(); [DllImport(PythonDll)] - internal static extern IntPtr - PyEval_GetLocals(); - + internal static extern IntPtr PyEval_GetLocals(); #if PYTHON3 [DllImport(PythonDll)] [return: MarshalAs(UnmanagedType.LPWStr)] - internal static extern string - Py_GetProgramName(); + internal static extern string Py_GetProgramName(); [DllImport(PythonDll)] - internal static extern void - Py_SetProgramName([MarshalAs(UnmanagedType.LPWStr)] string name); + internal static extern void Py_SetProgramName( + [MarshalAs(UnmanagedType.LPWStr)] string name + ); [DllImport(PythonDll)] [return: MarshalAs(UnmanagedType.LPWStr)] - internal static extern string - Py_GetPythonHome(); + internal static extern string Py_GetPythonHome(); [DllImport(PythonDll)] - internal static extern void - Py_SetPythonHome([MarshalAs(UnmanagedType.LPWStr)] string home); + internal static extern void Py_SetPythonHome( + [MarshalAs(UnmanagedType.LPWStr)] string home + ); [DllImport(PythonDll)] [return: MarshalAs(UnmanagedType.LPWStr)] - internal static extern string - Py_GetPath(); + internal static extern string Py_GetPath(); [DllImport(PythonDll)] - internal static extern void - Py_SetPath([MarshalAs(UnmanagedType.LPWStr)] string home); + internal static extern void Py_SetPath( + [MarshalAs(UnmanagedType.LPWStr)] string home + ); #elif PYTHON2 [DllImport(PythonDll)] - internal static extern string - Py_GetProgramName(); + internal static extern string Py_GetProgramName(); [DllImport(PythonDll)] - internal static extern void - Py_SetProgramName(string name); + internal static extern void Py_SetProgramName(string name); [DllImport(PythonDll)] - internal static extern string - Py_GetPythonHome(); + internal static extern string Py_GetPythonHome(); [DllImport(PythonDll)] - internal static extern void - Py_SetPythonHome(string home); + internal static extern void Py_SetPythonHome(string home); [DllImport(PythonDll)] - internal static extern string - Py_GetPath(); + internal static extern string Py_GetPath(); [DllImport(PythonDll)] - internal static extern void - Py_SetPath(string home); + internal static extern void Py_SetPath(string home); #endif [DllImport(PythonDll)] - internal static extern string - Py_GetVersion(); + internal static extern string Py_GetVersion(); [DllImport(PythonDll)] - internal static extern string - Py_GetPlatform(); + internal static extern string Py_GetPlatform(); [DllImport(PythonDll)] - internal static extern string - Py_GetCopyright(); + internal static extern string Py_GetCopyright(); [DllImport(PythonDll)] - internal static extern string - Py_GetCompiler(); + internal static extern string Py_GetCompiler(); [DllImport(PythonDll)] - internal static extern string - Py_GetBuildInfo(); + internal static extern string Py_GetBuildInfo(); [DllImport(PythonDll)] - internal static extern int - PyRun_SimpleString(string code); + internal static extern int PyRun_SimpleString(string code); [DllImport(PythonDll)] - internal static extern IntPtr - PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals); + internal static extern IntPtr PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals); [DllImport(PythonDll)] - internal static extern IntPtr - Py_CompileString(string code, string file, IntPtr tok); + internal static extern IntPtr Py_CompileString(string code, string file, IntPtr tok); [DllImport(PythonDll)] - internal static extern IntPtr - PyImport_ExecCodeModule(string name, IntPtr code); + internal static extern IntPtr PyImport_ExecCodeModule(string name, IntPtr code); [DllImport(PythonDll)] - internal static extern IntPtr - PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod); + internal static extern IntPtr PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod); [DllImport(PythonDll)] - internal static extern IntPtr - PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw); + internal static extern IntPtr PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw); [DllImport(PythonDll)] - internal static extern IntPtr - PyClass_New(IntPtr bases, IntPtr dict, IntPtr name); + internal static extern IntPtr PyClass_New(IntPtr bases, IntPtr dict, IntPtr name); [DllImport(PythonDll)] - internal static extern IntPtr - PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw); + internal static extern IntPtr PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw); [DllImport(PythonDll)] - internal static extern IntPtr - PyInstance_NewRaw(IntPtr cls, IntPtr dict); + internal static extern IntPtr PyInstance_NewRaw(IntPtr cls, IntPtr dict); [DllImport(PythonDll)] - internal static extern IntPtr - PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); + internal static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); //==================================================================== @@ -846,8 +794,7 @@ internal static extern IntPtr /// designed to be lean and mean in IL & avoid managed <-> unmanaged /// transitions. Note that this does not incref the type object. /// - internal static unsafe IntPtr - PyObject_TYPE(IntPtr op) + internal static unsafe IntPtr PyObject_TYPE(IntPtr op) { void* p = (void*)op; if ((void*)0 == p) @@ -874,8 +821,7 @@ internal static unsafe IntPtr /// This version avoids a managed <-> unmanaged transition. This one /// does incref the returned type object. /// - internal static IntPtr - PyObject_Type(IntPtr op) + internal static IntPtr PyObject_Type(IntPtr op) { IntPtr tp = PyObject_TYPE(op); Runtime.XIncref(tp); @@ -890,57 +836,44 @@ internal static string PyObject_GetTypeName(IntPtr op) } [DllImport(PythonDll)] - internal static extern int - PyObject_HasAttrString(IntPtr pointer, string name); + internal static extern int PyObject_HasAttrString(IntPtr pointer, string name); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_GetAttrString(IntPtr pointer, string name); + internal static extern IntPtr PyObject_GetAttrString(IntPtr pointer, string name); [DllImport(PythonDll)] - internal static extern int - PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value); + internal static extern int PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value); [DllImport(PythonDll)] - internal static extern int - PyObject_HasAttr(IntPtr pointer, IntPtr name); + internal static extern int PyObject_HasAttr(IntPtr pointer, IntPtr name); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_GetAttr(IntPtr pointer, IntPtr name); + internal static extern IntPtr PyObject_GetAttr(IntPtr pointer, IntPtr name); [DllImport(PythonDll)] - internal static extern int - PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value); + internal static extern int PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_GetItem(IntPtr pointer, IntPtr key); + internal static extern IntPtr PyObject_GetItem(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal static extern int - PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value); + internal static extern int PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value); [DllImport(PythonDll)] - internal static extern int - PyObject_DelItem(IntPtr pointer, IntPtr key); + internal static extern int PyObject_DelItem(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_GetIter(IntPtr op); + internal static extern IntPtr PyObject_GetIter(IntPtr op); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw); + internal static extern IntPtr PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_CallObject(IntPtr pointer, IntPtr args); + internal static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args); #if PYTHON3 [DllImport(PythonDll)] - internal static extern int - PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); + internal static extern int PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); internal static int PyObject_Compare(IntPtr value1, IntPtr value2) { @@ -968,60 +901,46 @@ internal static int PyObject_Compare(IntPtr value1, IntPtr value2) } #elif PYTHON2 [DllImport(PythonDll)] - internal static extern int - PyObject_Compare(IntPtr value1, IntPtr value2); + internal static extern int PyObject_Compare(IntPtr value1, IntPtr value2); #endif - [DllImport(PythonDll)] - internal static extern int - PyObject_IsInstance(IntPtr ob, IntPtr type); + internal static extern int PyObject_IsInstance(IntPtr ob, IntPtr type); [DllImport(PythonDll)] - internal static extern int - PyObject_IsSubclass(IntPtr ob, IntPtr type); + internal static extern int PyObject_IsSubclass(IntPtr ob, IntPtr type); [DllImport(PythonDll)] - internal static extern int - PyCallable_Check(IntPtr pointer); + internal static extern int PyCallable_Check(IntPtr pointer); [DllImport(PythonDll)] - internal static extern int - PyObject_IsTrue(IntPtr pointer); + internal static extern int PyObject_IsTrue(IntPtr pointer); [DllImport(PythonDll)] - internal static extern int - PyObject_Not(IntPtr pointer); + internal static extern int PyObject_Not(IntPtr pointer); [DllImport(PythonDll)] - internal static extern int - PyObject_Size(IntPtr pointer); + internal static extern int PyObject_Size(IntPtr pointer); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_Hash(IntPtr op); + internal static extern IntPtr PyObject_Hash(IntPtr op); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_Repr(IntPtr pointer); + internal static extern IntPtr PyObject_Repr(IntPtr pointer); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_Str(IntPtr pointer); + internal static extern IntPtr PyObject_Str(IntPtr pointer); #if PYTHON3 [DllImport(PythonDll, EntryPoint = "PyObject_Str")] - internal static extern IntPtr - PyObject_Unicode(IntPtr pointer); + internal static extern IntPtr PyObject_Unicode(IntPtr pointer); #elif PYTHON2 [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_Unicode(IntPtr pointer); + internal static extern IntPtr PyObject_Unicode(IntPtr pointer); #endif [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_Dir(IntPtr pointer); + internal static extern IntPtr PyObject_Dir(IntPtr pointer); //==================================================================== @@ -1030,28 +949,20 @@ internal static extern IntPtr #if PYTHON3 [DllImport(PythonDll, EntryPoint = "PyNumber_Long")] - internal static extern IntPtr - PyNumber_Int(IntPtr ob); + internal static extern IntPtr PyNumber_Int(IntPtr ob); #elif PYTHON2 - [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Int(IntPtr ob); + internal static extern IntPtr PyNumber_Int(IntPtr ob); #endif [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Long(IntPtr ob); + internal static extern IntPtr PyNumber_Long(IntPtr ob); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Float(IntPtr ob); - + internal static extern IntPtr PyNumber_Float(IntPtr ob); [DllImport(PythonDll)] - internal static extern bool - PyNumber_Check(IntPtr ob); - + internal static extern bool PyNumber_Check(IntPtr ob); internal static bool PyInt_Check(IntPtr ob) { @@ -1077,37 +988,28 @@ internal static IntPtr PyInt_FromInt64(long value) #if PYTHON3 [DllImport(PythonDll, EntryPoint = "PyLong_FromLong")] - private static extern IntPtr - PyInt_FromLong(IntPtr value); + private static extern IntPtr PyInt_FromLong(IntPtr value); [DllImport(PythonDll, EntryPoint = "PyLong_AsLong")] - internal static extern int - PyInt_AsLong(IntPtr value); + internal static extern int PyInt_AsLong(IntPtr value); [DllImport(PythonDll, EntryPoint = "PyLong_FromString")] - internal static extern IntPtr - PyInt_FromString(string value, IntPtr end, int radix); + internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); [DllImport(PythonDll, EntryPoint = "PyLong_GetMax")] - internal static extern int - PyInt_GetMax(); + internal static extern int PyInt_GetMax(); #elif PYTHON2 - [DllImport(PythonDll)] - private static extern IntPtr - PyInt_FromLong(IntPtr value); + private static extern IntPtr PyInt_FromLong(IntPtr value); [DllImport(PythonDll)] - internal static extern int - PyInt_AsLong(IntPtr value); + internal static extern int PyInt_AsLong(IntPtr value); [DllImport(PythonDll)] - internal static extern IntPtr - PyInt_FromString(string value, IntPtr end, int radix); + internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); [DllImport(PythonDll)] - internal static extern int - PyInt_GetMax(); + internal static extern int PyInt_GetMax(); #endif internal static bool PyLong_Check(IntPtr ob) @@ -1116,45 +1018,34 @@ internal static bool PyLong_Check(IntPtr ob) } [DllImport(PythonDll)] - internal static extern IntPtr - PyLong_FromLong(long value); + internal static extern IntPtr PyLong_FromLong(long value); [DllImport(PythonDll)] - internal static extern IntPtr - PyLong_FromUnsignedLong(uint value); + internal static extern IntPtr PyLong_FromUnsignedLong(uint value); [DllImport(PythonDll)] - internal static extern IntPtr - PyLong_FromDouble(double value); + internal static extern IntPtr PyLong_FromDouble(double value); [DllImport(PythonDll)] - internal static extern IntPtr - PyLong_FromLongLong(long value); + internal static extern IntPtr PyLong_FromLongLong(long value); [DllImport(PythonDll)] - internal static extern IntPtr - PyLong_FromUnsignedLongLong(ulong value); + internal static extern IntPtr PyLong_FromUnsignedLongLong(ulong value); [DllImport(PythonDll)] - internal static extern IntPtr - PyLong_FromString(string value, IntPtr end, int radix); + internal static extern IntPtr PyLong_FromString(string value, IntPtr end, int radix); [DllImport(PythonDll)] - internal static extern int - PyLong_AsLong(IntPtr value); + internal static extern int PyLong_AsLong(IntPtr value); [DllImport(PythonDll)] - internal static extern uint - PyLong_AsUnsignedLong(IntPtr value); + internal static extern uint PyLong_AsUnsignedLong(IntPtr value); [DllImport(PythonDll)] - internal static extern long - PyLong_AsLongLong(IntPtr value); + internal static extern long PyLong_AsLongLong(IntPtr value); [DllImport(PythonDll)] - internal static extern ulong - PyLong_AsUnsignedLongLong(IntPtr value); - + internal static extern ulong PyLong_AsUnsignedLongLong(IntPtr value); internal static bool PyFloat_Check(IntPtr ob) { @@ -1162,180 +1053,138 @@ internal static bool PyFloat_Check(IntPtr ob) } [DllImport(PythonDll)] - internal static extern IntPtr - PyFloat_FromDouble(double value); + internal static extern IntPtr PyFloat_FromDouble(double value); [DllImport(PythonDll)] - internal static extern IntPtr - PyFloat_FromString(IntPtr value, IntPtr junk); + internal static extern IntPtr PyFloat_FromString(IntPtr value, IntPtr junk); [DllImport(PythonDll)] - internal static extern double - PyFloat_AsDouble(IntPtr ob); + internal static extern double PyFloat_AsDouble(IntPtr ob); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Add(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Add(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Subtract(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Subtract(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Multiply(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Multiply(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Divide(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Divide(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_And(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_And(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Xor(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Xor(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Or(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Or(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Lshift(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Lshift(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Rshift(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Rshift(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Power(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Power(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Remainder(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_Remainder(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceAdd(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceAdd(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceSubtract(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceSubtract(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceMultiply(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceMultiply(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceDivide(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceDivide(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceAnd(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceAnd(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceXor(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceXor(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceOr(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceOr(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceLshift(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceLshift(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceRshift(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceRshift(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlacePower(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlacePower(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_InPlaceRemainder(IntPtr o1, IntPtr o2); + internal static extern IntPtr PyNumber_InPlaceRemainder(IntPtr o1, IntPtr o2); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Negative(IntPtr o1); + internal static extern IntPtr PyNumber_Negative(IntPtr o1); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Positive(IntPtr o1); + internal static extern IntPtr PyNumber_Positive(IntPtr o1); [DllImport(PythonDll)] - internal static extern IntPtr - PyNumber_Invert(IntPtr o1); + internal static extern IntPtr PyNumber_Invert(IntPtr o1); + //==================================================================== // Python sequence API //==================================================================== [DllImport(PythonDll)] - internal static extern bool - PySequence_Check(IntPtr pointer); + internal static extern bool PySequence_Check(IntPtr pointer); [DllImport(PythonDll)] - internal static extern IntPtr - PySequence_GetItem(IntPtr pointer, int index); + internal static extern IntPtr PySequence_GetItem(IntPtr pointer, int index); [DllImport(PythonDll)] - internal static extern int - PySequence_SetItem(IntPtr pointer, int index, IntPtr value); + internal static extern int PySequence_SetItem(IntPtr pointer, int index, IntPtr value); [DllImport(PythonDll)] - internal static extern int - PySequence_DelItem(IntPtr pointer, int index); + internal static extern int PySequence_DelItem(IntPtr pointer, int index); [DllImport(PythonDll)] - internal static extern IntPtr - PySequence_GetSlice(IntPtr pointer, int i1, int i2); + internal static extern IntPtr PySequence_GetSlice(IntPtr pointer, int i1, int i2); [DllImport(PythonDll)] - internal static extern int - PySequence_SetSlice(IntPtr pointer, int i1, int i2, IntPtr v); + internal static extern int PySequence_SetSlice(IntPtr pointer, int i1, int i2, IntPtr v); [DllImport(PythonDll)] - internal static extern int - PySequence_DelSlice(IntPtr pointer, int i1, int i2); + internal static extern int PySequence_DelSlice(IntPtr pointer, int i1, int i2); [DllImport(PythonDll)] - internal static extern int - PySequence_Size(IntPtr pointer); + internal static extern int PySequence_Size(IntPtr pointer); [DllImport(PythonDll)] - internal static extern int - PySequence_Contains(IntPtr pointer, IntPtr item); + internal static extern int PySequence_Contains(IntPtr pointer, IntPtr item); [DllImport(PythonDll)] - internal static extern IntPtr - PySequence_Concat(IntPtr pointer, IntPtr other); + internal static extern IntPtr PySequence_Concat(IntPtr pointer, IntPtr other); [DllImport(PythonDll)] - internal static extern IntPtr - PySequence_Repeat(IntPtr pointer, int count); + internal static extern IntPtr PySequence_Repeat(IntPtr pointer, int count); [DllImport(PythonDll)] - internal static extern int - PySequence_Index(IntPtr pointer, IntPtr item); + internal static extern int PySequence_Index(IntPtr pointer, IntPtr item); [DllImport(PythonDll)] - internal static extern int - PySequence_Count(IntPtr pointer, IntPtr value); + internal static extern int PySequence_Count(IntPtr pointer, IntPtr value); [DllImport(PythonDll)] - internal static extern IntPtr - PySequence_Tuple(IntPtr pointer); + internal static extern IntPtr PySequence_Tuple(IntPtr pointer); [DllImport(PythonDll)] - internal static extern IntPtr - PySequence_List(IntPtr pointer); + internal static extern IntPtr PySequence_List(IntPtr pointer); //==================================================================== @@ -1360,12 +1209,10 @@ internal static IntPtr PyString_FromString(string value) #if PYTHON3 [DllImport(PythonDll)] - internal static extern IntPtr - PyBytes_FromString(string op); + internal static extern IntPtr PyBytes_FromString(string op); [DllImport(PythonDll)] - internal static extern int - PyBytes_Size(IntPtr op); + internal static extern int PyBytes_Size(IntPtr op); internal static IntPtr PyBytes_AS_STRING(IntPtr ob) { @@ -1373,27 +1220,22 @@ internal static IntPtr PyBytes_AS_STRING(IntPtr ob) } [DllImport(PythonDll, EntryPoint = "PyUnicode_FromStringAndSize")] - internal static extern IntPtr - PyString_FromStringAndSize( - [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(Utf8Marshaler))] string value, - int size - ); + internal static extern IntPtr PyString_FromStringAndSize( + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(Utf8Marshaler))] string value, + int size + ); [DllImport(PythonDll)] - internal static extern IntPtr - PyUnicode_FromStringAndSize(IntPtr value, int size); + internal static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, int size); #elif PYTHON2 [DllImport(PythonDll)] - internal static extern IntPtr - PyString_FromStringAndSize(string value, int size); + internal static extern IntPtr PyString_FromStringAndSize(string value, int size); [DllImport(PythonDll, EntryPoint = "PyString_AsString")] - internal static extern IntPtr - PyString_AS_STRING(IntPtr op); + internal static extern IntPtr PyString_AS_STRING(IntPtr op); [DllImport(PythonDll)] - internal static extern int - PyString_Size(IntPtr pointer); + internal static extern int PyString_Size(IntPtr pointer); #endif internal static bool PyUnicode_Check(IntPtr ob) @@ -1403,16 +1245,13 @@ internal static bool PyUnicode_Check(IntPtr ob) #if UCS2 && PYTHON3 [DllImport(PythonDll)] - internal static extern IntPtr - PyUnicode_FromObject(IntPtr ob); + internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(PythonDll)] - internal static extern IntPtr - PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); + internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData", CharSet = CharSet.Unicode)] - internal static extern IntPtr - PyUnicode_FromKindAndString(int kind, string s, int size); + internal static extern IntPtr PyUnicode_FromKindAndString(int kind, string s, int size); internal static IntPtr PyUnicode_FromUnicode(string s, int size) { @@ -1420,56 +1259,44 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) } [DllImport(PythonDll)] - internal static extern int - PyUnicode_GetSize(IntPtr ob); + internal static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(PythonDll)] - internal static extern IntPtr - PyUnicode_AsUnicode(IntPtr ob); + internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(PythonDll)] - internal static extern IntPtr - PyUnicode_FromOrdinal(int c); + internal static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS2 && PYTHON2 [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromObject")] - internal static extern IntPtr - PyUnicode_FromObject(IntPtr ob); + internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromEncodedObject")] - internal static extern IntPtr - PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); + internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromUnicode", CharSet = CharSet.Unicode)] - internal static extern IntPtr - PyUnicode_FromUnicode(string s, int size); + internal static extern IntPtr PyUnicode_FromUnicode(string s, int size); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_GetSize")] - internal static extern int - PyUnicode_GetSize(IntPtr ob); + internal static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_AsUnicode")] - internal static extern IntPtr - PyUnicode_AsUnicode(IntPtr ob); + internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromOrdinal")] - internal static extern IntPtr - PyUnicode_FromOrdinal(int c); + internal static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON3 [DllImport(PythonDll)] - internal static extern IntPtr - PyUnicode_FromObject(IntPtr ob); + internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(PythonDll)] - internal static extern IntPtr - PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); + internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData")] - internal static extern IntPtr - PyUnicode_FromKindAndString( - int kind, - [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, - int size - ); + internal static extern IntPtr PyUnicode_FromKindAndString( + int kind, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, + int size + ); internal static IntPtr PyUnicode_FromUnicode(string s, int size) { @@ -1477,43 +1304,34 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) } [DllImport(PythonDll)] - internal static extern int - PyUnicode_GetSize(IntPtr ob); + internal static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(PythonDll)] - internal static extern IntPtr - PyUnicode_AsUnicode(IntPtr ob); + internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(PythonDll)] - internal static extern IntPtr - PyUnicode_FromOrdinal(int c); + internal static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON2 [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromObject")] - internal static extern IntPtr - PyUnicode_FromObject(IntPtr ob); + internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromEncodedObject")] - internal static extern IntPtr - PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); + internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromUnicode")] - internal static extern IntPtr - PyUnicode_FromUnicode( - [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, - int size - ); + internal static extern IntPtr PyUnicode_FromUnicode( + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, + int size + ); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_GetSize")] - internal static extern int - PyUnicode_GetSize(IntPtr ob); + internal static extern int PyUnicode_GetSize(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_AsUnicode")] - internal static extern IntPtr - PyUnicode_AsUnicode(IntPtr ob); + internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromOrdinal")] - internal static extern IntPtr - PyUnicode_FromOrdinal(int c); + internal static extern IntPtr PyUnicode_FromOrdinal(int c); #endif internal static IntPtr PyUnicode_FromString(string s) @@ -1541,10 +1359,7 @@ internal static string GetManagedString(IntPtr op) #if PYTHON2 // Python 3 strings are all Unicode if (type == Runtime.PyStringType) { - return Marshal.PtrToStringAnsi( - PyString_AS_STRING(op), - Runtime.PyString_Size(op) - ); + return Marshal.PtrToStringAnsi(PyString_AS_STRING(op), Runtime.PyString_Size(op)); } #endif @@ -1562,6 +1377,7 @@ internal static string GetManagedString(IntPtr op) return null; } + //==================================================================== // Python dictionary API //==================================================================== @@ -1572,68 +1388,52 @@ internal static bool PyDict_Check(IntPtr ob) } [DllImport(PythonDll)] - internal static extern IntPtr - PyDict_New(); + internal static extern IntPtr PyDict_New(); [DllImport(PythonDll)] - internal static extern IntPtr - PyDictProxy_New(IntPtr dict); + internal static extern IntPtr PyDictProxy_New(IntPtr dict); [DllImport(PythonDll)] - internal static extern IntPtr - PyDict_GetItem(IntPtr pointer, IntPtr key); + internal static extern IntPtr PyDict_GetItem(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal static extern IntPtr - PyDict_GetItemString(IntPtr pointer, string key); + internal static extern IntPtr PyDict_GetItemString(IntPtr pointer, string key); [DllImport(PythonDll)] - internal static extern int - PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value); + internal static extern int PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value); [DllImport(PythonDll)] - internal static extern int - PyDict_SetItemString(IntPtr pointer, string key, IntPtr value); + internal static extern int PyDict_SetItemString(IntPtr pointer, string key, IntPtr value); [DllImport(PythonDll)] - internal static extern int - PyDict_DelItem(IntPtr pointer, IntPtr key); + internal static extern int PyDict_DelItem(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal static extern int - PyDict_DelItemString(IntPtr pointer, string key); + internal static extern int PyDict_DelItemString(IntPtr pointer, string key); [DllImport(PythonDll)] - internal static extern int - PyMapping_HasKey(IntPtr pointer, IntPtr key); + internal static extern int PyMapping_HasKey(IntPtr pointer, IntPtr key); [DllImport(PythonDll)] - internal static extern IntPtr - PyDict_Keys(IntPtr pointer); + internal static extern IntPtr PyDict_Keys(IntPtr pointer); [DllImport(PythonDll)] - internal static extern IntPtr - PyDict_Values(IntPtr pointer); + internal static extern IntPtr PyDict_Values(IntPtr pointer); [DllImport(PythonDll)] - internal static extern IntPtr - PyDict_Items(IntPtr pointer); + internal static extern IntPtr PyDict_Items(IntPtr pointer); [DllImport(PythonDll)] - internal static extern IntPtr - PyDict_Copy(IntPtr pointer); + internal static extern IntPtr PyDict_Copy(IntPtr pointer); [DllImport(PythonDll)] - internal static extern int - PyDict_Update(IntPtr pointer, IntPtr other); + internal static extern int PyDict_Update(IntPtr pointer, IntPtr other); [DllImport(PythonDll)] - internal static extern void - PyDict_Clear(IntPtr pointer); + internal static extern void PyDict_Clear(IntPtr pointer); [DllImport(PythonDll)] - internal static extern int - PyDict_Size(IntPtr pointer); + internal static extern int PyDict_Size(IntPtr pointer); //==================================================================== @@ -1646,48 +1446,37 @@ internal static bool PyList_Check(IntPtr ob) } [DllImport(PythonDll)] - internal static extern IntPtr - PyList_New(int size); + internal static extern IntPtr PyList_New(int size); [DllImport(PythonDll)] - internal static extern IntPtr - PyList_AsTuple(IntPtr pointer); + internal static extern IntPtr PyList_AsTuple(IntPtr pointer); [DllImport(PythonDll)] - internal static extern IntPtr - PyList_GetItem(IntPtr pointer, int index); + internal static extern IntPtr PyList_GetItem(IntPtr pointer, int index); [DllImport(PythonDll)] - internal static extern int - PyList_SetItem(IntPtr pointer, int index, IntPtr value); + internal static extern int PyList_SetItem(IntPtr pointer, int index, IntPtr value); [DllImport(PythonDll)] - internal static extern int - PyList_Insert(IntPtr pointer, int index, IntPtr value); + internal static extern int PyList_Insert(IntPtr pointer, int index, IntPtr value); [DllImport(PythonDll)] - internal static extern int - PyList_Append(IntPtr pointer, IntPtr value); + internal static extern int PyList_Append(IntPtr pointer, IntPtr value); [DllImport(PythonDll)] - internal static extern int - PyList_Reverse(IntPtr pointer); + internal static extern int PyList_Reverse(IntPtr pointer); [DllImport(PythonDll)] - internal static extern int - PyList_Sort(IntPtr pointer); + internal static extern int PyList_Sort(IntPtr pointer); [DllImport(PythonDll)] - internal static extern IntPtr - PyList_GetSlice(IntPtr pointer, int start, int end); + internal static extern IntPtr PyList_GetSlice(IntPtr pointer, int start, int end); [DllImport(PythonDll)] - internal static extern int - PyList_SetSlice(IntPtr pointer, int start, int end, IntPtr value); + internal static extern int PyList_SetSlice(IntPtr pointer, int start, int end, IntPtr value); [DllImport(PythonDll)] - internal static extern int - PyList_Size(IntPtr pointer); + internal static extern int PyList_Size(IntPtr pointer); //==================================================================== @@ -1700,24 +1489,19 @@ internal static bool PyTuple_Check(IntPtr ob) } [DllImport(PythonDll)] - internal static extern IntPtr - PyTuple_New(int size); + internal static extern IntPtr PyTuple_New(int size); [DllImport(PythonDll)] - internal static extern IntPtr - PyTuple_GetItem(IntPtr pointer, int index); + internal static extern IntPtr PyTuple_GetItem(IntPtr pointer, int index); [DllImport(PythonDll)] - internal static extern int - PyTuple_SetItem(IntPtr pointer, int index, IntPtr value); + internal static extern int PyTuple_SetItem(IntPtr pointer, int index, IntPtr value); [DllImport(PythonDll)] - internal static extern IntPtr - PyTuple_GetSlice(IntPtr pointer, int start, int end); + internal static extern IntPtr PyTuple_GetSlice(IntPtr pointer, int start, int end); [DllImport(PythonDll)] - internal static extern int - PyTuple_Size(IntPtr pointer); + internal static extern int PyTuple_Size(IntPtr pointer); //==================================================================== @@ -1726,11 +1510,9 @@ internal static extern int #if PYTHON2 [DllImport(PythonDll)] - internal static extern bool - PyIter_Check(IntPtr pointer); + internal static extern bool PyIter_Check(IntPtr pointer); #elif PYTHON3 - internal static bool - PyIter_Check(IntPtr pointer) + internal static bool PyIter_Check(IntPtr pointer) { IntPtr ob_type = (IntPtr)Marshal.PtrToStructure(pointer + ObjectOffset.ob_type, typeof(IntPtr)); IntPtr tp_iternext = ob_type + TypeOffset.tp_iternext; @@ -1739,80 +1521,66 @@ internal static bool #endif [DllImport(PythonDll)] - internal static extern IntPtr - PyIter_Next(IntPtr pointer); + internal static extern IntPtr PyIter_Next(IntPtr pointer); + //==================================================================== // Python module API //==================================================================== [DllImport(PythonDll)] - internal static extern IntPtr - PyModule_New(string name); + internal static extern IntPtr PyModule_New(string name); [DllImport(PythonDll)] - internal static extern string - PyModule_GetName(IntPtr module); + internal static extern string PyModule_GetName(IntPtr module); [DllImport(PythonDll)] - internal static extern IntPtr - PyModule_GetDict(IntPtr module); + internal static extern IntPtr PyModule_GetDict(IntPtr module); [DllImport(PythonDll)] - internal static extern string - PyModule_GetFilename(IntPtr module); + internal static extern string PyModule_GetFilename(IntPtr module); #if PYTHON3 [DllImport(PythonDll)] - internal static extern IntPtr - PyModule_Create2(IntPtr module, int apiver); + internal static extern IntPtr PyModule_Create2(IntPtr module, int apiver); #endif [DllImport(PythonDll)] - internal static extern IntPtr - PyImport_Import(IntPtr name); + internal static extern IntPtr PyImport_Import(IntPtr name); [DllImport(PythonDll)] - internal static extern IntPtr - PyImport_ImportModule(string name); + internal static extern IntPtr PyImport_ImportModule(string name); [DllImport(PythonDll)] - internal static extern IntPtr - PyImport_ReloadModule(IntPtr module); + internal static extern IntPtr PyImport_ReloadModule(IntPtr module); [DllImport(PythonDll)] - internal static extern IntPtr - PyImport_AddModule(string name); + internal static extern IntPtr PyImport_AddModule(string name); [DllImport(PythonDll)] - internal static extern IntPtr - PyImport_GetModuleDict(); + internal static extern IntPtr PyImport_GetModuleDict(); #if PYTHON3 [DllImport(PythonDll)] - internal static extern void - PySys_SetArgvEx( - int argc, - [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv, - int updatepath - ); + internal static extern void PySys_SetArgvEx( + int argc, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv, + int updatepath + ); #elif PYTHON2 [DllImport(PythonDll)] - internal static extern void - PySys_SetArgvEx( - int argc, - string[] argv, - int updatepath - ); + internal static extern void PySys_SetArgvEx( + int argc, + string[] argv, + int updatepath + ); #endif [DllImport(PythonDll)] - internal static extern IntPtr - PySys_GetObject(string name); + internal static extern IntPtr PySys_GetObject(string name); [DllImport(PythonDll)] - internal static extern int - PySys_SetObject(string name, IntPtr ob); + internal static extern int PySys_SetObject(string name, IntPtr ob); //==================================================================== @@ -1825,12 +1593,10 @@ internal static bool PyType_Check(IntPtr ob) } [DllImport(PythonDll)] - internal static extern void - PyType_Modified(IntPtr type); + internal static extern void PyType_Modified(IntPtr type); [DllImport(PythonDll)] - internal static extern bool - PyType_IsSubtype(IntPtr t1, IntPtr t2); + internal static extern bool PyType_IsSubtype(IntPtr t1, IntPtr t2); internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) { @@ -1839,48 +1605,37 @@ internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) } [DllImport(PythonDll)] - internal static extern IntPtr - PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw); + internal static extern IntPtr PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw); [DllImport(PythonDll)] - internal static extern IntPtr - PyType_GenericAlloc(IntPtr type, int n); + internal static extern IntPtr PyType_GenericAlloc(IntPtr type, int n); [DllImport(PythonDll)] - internal static extern int - PyType_Ready(IntPtr type); + internal static extern int PyType_Ready(IntPtr type); [DllImport(PythonDll)] - internal static extern IntPtr - _PyType_Lookup(IntPtr type, IntPtr name); + internal static extern IntPtr _PyType_Lookup(IntPtr type, IntPtr name); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_GenericGetAttr(IntPtr obj, IntPtr name); + internal static extern IntPtr PyObject_GenericGetAttr(IntPtr obj, IntPtr name); [DllImport(PythonDll)] - internal static extern int - PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value); + internal static extern int PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value); [DllImport(PythonDll)] - internal static extern IntPtr - _PyObject_GetDictPtr(IntPtr obj); + internal static extern IntPtr _PyObject_GetDictPtr(IntPtr obj); [DllImport(PythonDll)] - internal static extern IntPtr - PyObject_GC_New(IntPtr tp); + internal static extern IntPtr PyObject_GC_New(IntPtr tp); [DllImport(PythonDll)] - internal static extern void - PyObject_GC_Del(IntPtr tp); + internal static extern void PyObject_GC_Del(IntPtr tp); [DllImport(PythonDll)] - internal static extern void - PyObject_GC_Track(IntPtr tp); + internal static extern void PyObject_GC_Track(IntPtr tp); [DllImport(PythonDll)] - internal static extern void - PyObject_GC_UnTrack(IntPtr tp); + internal static extern void PyObject_GC_UnTrack(IntPtr tp); //==================================================================== @@ -1888,16 +1643,13 @@ internal static extern void //==================================================================== [DllImport(PythonDll)] - internal static extern IntPtr - PyMem_Malloc(int size); + internal static extern IntPtr PyMem_Malloc(int size); [DllImport(PythonDll)] - internal static extern IntPtr - PyMem_Realloc(IntPtr ptr, int size); + internal static extern IntPtr PyMem_Realloc(IntPtr ptr, int size); [DllImport(PythonDll)] - internal static extern void - PyMem_Free(IntPtr ptr); + internal static extern void PyMem_Free(IntPtr ptr); //==================================================================== @@ -1905,52 +1657,40 @@ internal static extern void //==================================================================== [DllImport(PythonDll)] - internal static extern void - PyErr_SetString(IntPtr ob, string message); + internal static extern void PyErr_SetString(IntPtr ob, string message); [DllImport(PythonDll)] - internal static extern void - PyErr_SetObject(IntPtr ob, IntPtr message); + internal static extern void PyErr_SetObject(IntPtr ob, IntPtr message); [DllImport(PythonDll)] - internal static extern IntPtr - PyErr_SetFromErrno(IntPtr ob); + internal static extern IntPtr PyErr_SetFromErrno(IntPtr ob); [DllImport(PythonDll)] - internal static extern void - PyErr_SetNone(IntPtr ob); + internal static extern void PyErr_SetNone(IntPtr ob); [DllImport(PythonDll)] - internal static extern int - PyErr_ExceptionMatches(IntPtr exception); + internal static extern int PyErr_ExceptionMatches(IntPtr exception); [DllImport(PythonDll)] - internal static extern int - PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val); + internal static extern int PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val); [DllImport(PythonDll)] - internal static extern void - PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb); + internal static extern void PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb); [DllImport(PythonDll)] - internal static extern int - PyErr_Occurred(); + internal static extern int PyErr_Occurred(); [DllImport(PythonDll)] - internal static extern void - PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb); + internal static extern void PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb); [DllImport(PythonDll)] - internal static extern void - PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb); + internal static extern void PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb); [DllImport(PythonDll)] - internal static extern void - PyErr_Clear(); + internal static extern void PyErr_Clear(); [DllImport(PythonDll)] - internal static extern void - PyErr_Print(); + internal static extern void PyErr_Print(); //==================================================================== @@ -1958,11 +1698,9 @@ internal static extern void //==================================================================== [DllImport(PythonDll)] - internal static extern IntPtr - PyMethod_Self(IntPtr ob); + internal static extern IntPtr PyMethod_Self(IntPtr ob); [DllImport(PythonDll)] - internal static extern IntPtr - PyMethod_Function(IntPtr ob); + internal static extern IntPtr PyMethod_Function(IntPtr ob); } } From c7b4c212407168c9c2246536aa16e57a36c2acaa Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Mar 2017 10:04:54 -0700 Subject: [PATCH 209/245] Apply consistent name qualification to runtime.cs --- src/runtime/runtime.cs | 206 ++++++++++++++++++++--------------------- 1 file changed, 103 insertions(+), 103 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 5ec66150d..df0d8e64d 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -184,111 +184,111 @@ internal static void Initialize() IsPython2 = pyversionnumber < 30; IsPython3 = pyversionnumber >= 30; - if (Runtime.Py_IsInitialized() == 0) + if (Py_IsInitialized() == 0) { - Runtime.Py_Initialize(); + Py_Initialize(); } - if (Runtime.PyEval_ThreadsInitialized() == 0) + if (PyEval_ThreadsInitialized() == 0) { - Runtime.PyEval_InitThreads(); + PyEval_InitThreads(); } IntPtr op; IntPtr dict; if (IsPython3) { - op = Runtime.PyImport_ImportModule("builtins"); - dict = Runtime.PyObject_GetAttrString(op, "__dict__"); + op = PyImport_ImportModule("builtins"); + dict = PyObject_GetAttrString(op, "__dict__"); } else // Python2 { - dict = Runtime.PyImport_GetModuleDict(); - op = Runtime.PyDict_GetItemString(dict, "__builtin__"); + dict = PyImport_GetModuleDict(); + op = PyDict_GetItemString(dict, "__builtin__"); } - PyNotImplemented = Runtime.PyObject_GetAttrString(op, "NotImplemented"); - PyBaseObjectType = Runtime.PyObject_GetAttrString(op, "object"); + PyNotImplemented = PyObject_GetAttrString(op, "NotImplemented"); + PyBaseObjectType = PyObject_GetAttrString(op, "object"); - PyModuleType = Runtime.PyObject_Type(op); - PyNone = Runtime.PyObject_GetAttrString(op, "None"); - PyTrue = Runtime.PyObject_GetAttrString(op, "True"); - PyFalse = Runtime.PyObject_GetAttrString(op, "False"); + PyModuleType = PyObject_Type(op); + PyNone = PyObject_GetAttrString(op, "None"); + PyTrue = PyObject_GetAttrString(op, "True"); + PyFalse = PyObject_GetAttrString(op, "False"); - PyBoolType = Runtime.PyObject_Type(PyTrue); - PyNoneType = Runtime.PyObject_Type(PyNone); - PyTypeType = Runtime.PyObject_Type(PyNoneType); + PyBoolType = PyObject_Type(PyTrue); + PyNoneType = PyObject_Type(PyNone); + PyTypeType = PyObject_Type(PyNoneType); - op = Runtime.PyObject_GetAttrString(dict, "keys"); - PyMethodType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyObject_GetAttrString(dict, "keys"); + PyMethodType = PyObject_Type(op); + XDecref(op); // For some arcane reason, builtins.__dict__.__setitem__ is *not* // a wrapper_descriptor, even though dict.__setitem__ is. // // object.__init__ seems safe, though. - op = Runtime.PyObject_GetAttrString(PyBaseObjectType, "__init__"); - PyWrapperDescriptorType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyObject_GetAttrString(PyBaseObjectType, "__init__"); + PyWrapperDescriptorType = PyObject_Type(op); + XDecref(op); #if PYTHON3 - Runtime.XDecref(dict); + XDecref(dict); #endif - op = Runtime.PyString_FromString("string"); - PyStringType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyString_FromString("string"); + PyStringType = PyObject_Type(op); + XDecref(op); - op = Runtime.PyUnicode_FromString("unicode"); - PyUnicodeType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyUnicode_FromString("unicode"); + PyUnicodeType = PyObject_Type(op); + XDecref(op); #if PYTHON3 - op = Runtime.PyBytes_FromString("bytes"); - PyBytesType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyBytes_FromString("bytes"); + PyBytesType = PyObject_Type(op); + XDecref(op); #endif - op = Runtime.PyTuple_New(0); - PyTupleType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyTuple_New(0); + PyTupleType = PyObject_Type(op); + XDecref(op); - op = Runtime.PyList_New(0); - PyListType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyList_New(0); + PyListType = PyObject_Type(op); + XDecref(op); - op = Runtime.PyDict_New(); - PyDictType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyDict_New(); + PyDictType = PyObject_Type(op); + XDecref(op); - op = Runtime.PyInt_FromInt32(0); - PyIntType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyInt_FromInt32(0); + PyIntType = PyObject_Type(op); + XDecref(op); - op = Runtime.PyLong_FromLong(0); - PyLongType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyLong_FromLong(0); + PyLongType = PyObject_Type(op); + XDecref(op); - op = Runtime.PyFloat_FromDouble(0); - PyFloatType = Runtime.PyObject_Type(op); - Runtime.XDecref(op); + op = PyFloat_FromDouble(0); + PyFloatType = PyObject_Type(op); + XDecref(op); #if PYTHON3 PyClassType = IntPtr.Zero; PyInstanceType = IntPtr.Zero; #elif PYTHON2 - IntPtr s = Runtime.PyString_FromString("_temp"); - IntPtr d = Runtime.PyDict_New(); + IntPtr s = PyString_FromString("_temp"); + IntPtr d = PyDict_New(); - IntPtr c = Runtime.PyClass_New(IntPtr.Zero, d, s); - PyClassType = Runtime.PyObject_Type(c); + IntPtr c = PyClass_New(IntPtr.Zero, d, s); + PyClassType = PyObject_Type(c); - IntPtr i = Runtime.PyInstance_New(c, IntPtr.Zero, IntPtr.Zero); - PyInstanceType = Runtime.PyObject_Type(i); + IntPtr i = PyInstance_New(c, IntPtr.Zero, IntPtr.Zero); + PyInstanceType = PyObject_Type(i); - Runtime.XDecref(s); - Runtime.XDecref(i); - Runtime.XDecref(c); - Runtime.XDecref(d); + XDecref(s); + XDecref(i); + XDecref(c); + XDecref(d); #endif Error = new IntPtr(-1); @@ -317,10 +317,10 @@ internal static void Initialize() // Need to add the runtime directory to sys.path so that we // can find built-in assemblies like System.Data, et. al. string rtdir = RuntimeEnvironment.GetRuntimeDirectory(); - IntPtr path = Runtime.PySys_GetObject("path"); - IntPtr item = Runtime.PyString_FromString(rtdir); - Runtime.PyList_Append(path, item); - Runtime.XDecref(item); + IntPtr path = PySys_GetObject("path"); + IntPtr item = PyString_FromString(rtdir); + PyList_Append(path, item); + XDecref(item); AssemblyManager.UpdatePath(); } @@ -401,21 +401,21 @@ internal static void CheckExceptionOccurred() internal static IntPtr GetBoundArgTuple(IntPtr obj, IntPtr args) { - if (Runtime.PyObject_TYPE(args) != Runtime.PyTupleType) + if (PyObject_TYPE(args) != PyTupleType) { Exceptions.SetError(Exceptions.TypeError, "tuple expected"); return IntPtr.Zero; } - int size = Runtime.PyTuple_Size(args); - IntPtr items = Runtime.PyTuple_New(size + 1); - Runtime.PyTuple_SetItem(items, 0, obj); - Runtime.XIncref(obj); + int size = PyTuple_Size(args); + IntPtr items = PyTuple_New(size + 1); + PyTuple_SetItem(items, 0, obj); + XIncref(obj); for (int i = 0; i < size; i++) { - IntPtr item = Runtime.PyTuple_GetItem(args, i); - Runtime.XIncref(item); - Runtime.PyTuple_SetItem(items, i + 1, item); + IntPtr item = PyTuple_GetItem(args, i); + XIncref(item); + PyTuple_SetItem(items, i + 1, item); } return items; @@ -424,23 +424,23 @@ internal static IntPtr GetBoundArgTuple(IntPtr obj, IntPtr args) internal static IntPtr ExtendTuple(IntPtr t, params IntPtr[] args) { - int size = Runtime.PyTuple_Size(t); + int size = PyTuple_Size(t); int add = args.Length; IntPtr item; - IntPtr items = Runtime.PyTuple_New(size + add); + IntPtr items = PyTuple_New(size + add); for (int i = 0; i < size; i++) { - item = Runtime.PyTuple_GetItem(t, i); - Runtime.XIncref(item); - Runtime.PyTuple_SetItem(items, i, item); + item = PyTuple_GetItem(t, i); + XIncref(item); + PyTuple_SetItem(items, i, item); } for (int n = 0; n < add; n++) { item = args[n]; - Runtime.XIncref(item); - Runtime.PyTuple_SetItem(items, size + n, item); + XIncref(item); + PyTuple_SetItem(items, size + n, item); } return items; @@ -459,24 +459,24 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) IntPtr args = arg; bool free = false; - if (!Runtime.PyTuple_Check(arg)) + if (!PyTuple_Check(arg)) { - args = Runtime.PyTuple_New(1); - Runtime.XIncref(arg); - Runtime.PyTuple_SetItem(args, 0, arg); + args = PyTuple_New(1); + XIncref(arg); + PyTuple_SetItem(args, 0, arg); free = true; } - int n = Runtime.PyTuple_Size(args); + int n = PyTuple_Size(args); Type[] types = new Type[n]; Type t = null; for (int i = 0; i < n; i++) { - IntPtr op = Runtime.PyTuple_GetItem(args, i); - if (mangleObjects && (!Runtime.PyType_Check(op))) + IntPtr op = PyTuple_GetItem(args, i); + if (mangleObjects && (!PyType_Check(op))) { - op = Runtime.PyObject_TYPE(op); + op = PyObject_TYPE(op); } ManagedType mt = ManagedType.GetManagedObject(op); @@ -506,7 +506,7 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) } if (free) { - Runtime.XDecref(args); + XDecref(args); } return types; } @@ -824,7 +824,7 @@ internal static unsafe IntPtr PyObject_TYPE(IntPtr op) internal static IntPtr PyObject_Type(IntPtr op) { IntPtr tp = PyObject_TYPE(op); - Runtime.XIncref(tp); + XIncref(tp); return tp; } @@ -966,12 +966,12 @@ internal static int PyObject_Compare(IntPtr value1, IntPtr value2) internal static bool PyInt_Check(IntPtr ob) { - return PyObject_TypeCheck(ob, Runtime.PyIntType); + return PyObject_TypeCheck(ob, PyIntType); } internal static bool PyBool_Check(IntPtr ob) { - return PyObject_TypeCheck(ob, Runtime.PyBoolType); + return PyObject_TypeCheck(ob, PyBoolType); } internal static IntPtr PyInt_FromInt32(int value) @@ -1014,7 +1014,7 @@ internal static IntPtr PyInt_FromInt64(long value) internal static bool PyLong_Check(IntPtr ob) { - return PyObject_TYPE(ob) == Runtime.PyLongType; + return PyObject_TYPE(ob) == PyLongType; } [DllImport(PythonDll)] @@ -1049,7 +1049,7 @@ internal static bool PyLong_Check(IntPtr ob) internal static bool PyFloat_Check(IntPtr ob) { - return PyObject_TYPE(ob) == Runtime.PyFloatType; + return PyObject_TYPE(ob) == PyFloatType; } [DllImport(PythonDll)] @@ -1199,7 +1199,7 @@ internal static bool IsStringType(IntPtr op) internal static bool PyString_Check(IntPtr ob) { - return PyObject_TYPE(ob) == Runtime.PyStringType; + return PyObject_TYPE(ob) == PyStringType; } internal static IntPtr PyString_FromString(string value) @@ -1240,7 +1240,7 @@ int size internal static bool PyUnicode_Check(IntPtr ob) { - return PyObject_TYPE(ob) == Runtime.PyUnicodeType; + return PyObject_TYPE(ob) == PyUnicodeType; } #if UCS2 && PYTHON3 @@ -1357,13 +1357,13 @@ internal static string GetManagedString(IntPtr op) IntPtr type = PyObject_TYPE(op); #if PYTHON2 // Python 3 strings are all Unicode - if (type == Runtime.PyStringType) + if (type == PyStringType) { - return Marshal.PtrToStringAnsi(PyString_AS_STRING(op), Runtime.PyString_Size(op)); + return Marshal.PtrToStringAnsi(PyString_AS_STRING(op), PyString_Size(op)); } #endif - if (type == Runtime.PyUnicodeType) + if (type == PyUnicodeType) { IntPtr p = PyUnicode_AsUnicode(op); int length = PyUnicode_GetSize(op); @@ -1384,7 +1384,7 @@ internal static string GetManagedString(IntPtr op) internal static bool PyDict_Check(IntPtr ob) { - return PyObject_TYPE(ob) == Runtime.PyDictType; + return PyObject_TYPE(ob) == PyDictType; } [DllImport(PythonDll)] @@ -1442,7 +1442,7 @@ internal static bool PyDict_Check(IntPtr ob) internal static bool PyList_Check(IntPtr ob) { - return PyObject_TYPE(ob) == Runtime.PyListType; + return PyObject_TYPE(ob) == PyListType; } [DllImport(PythonDll)] @@ -1485,7 +1485,7 @@ internal static bool PyList_Check(IntPtr ob) internal static bool PyTuple_Check(IntPtr ob) { - return PyObject_TYPE(ob) == Runtime.PyTupleType; + return PyObject_TYPE(ob) == PyTupleType; } [DllImport(PythonDll)] @@ -1589,7 +1589,7 @@ int updatepath internal static bool PyType_Check(IntPtr ob) { - return PyObject_TypeCheck(ob, Runtime.PyTypeType); + return PyObject_TypeCheck(ob, PyTypeType); } [DllImport(PythonDll)] From 6e9fed9f96f3833383e8a3a9d6d98f8fc728d0cf Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 28 Feb 2017 19:25:08 -0700 Subject: [PATCH 210/245] Unify PY3 UCS2/UCS4 unicode methods CustomMarshal implementation deals w UCS2/4 differences --- src/runtime/runtime.cs | 39 ++++++++------------------------------- 1 file changed, 8 insertions(+), 31 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index df0d8e64d..6629657fc 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1243,19 +1243,23 @@ internal static bool PyUnicode_Check(IntPtr ob) return PyObject_TYPE(ob) == PyUnicodeType; } -#if UCS2 && PYTHON3 +#if PYTHON3 [DllImport(PythonDll)] internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(PythonDll)] internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData", CharSet = CharSet.Unicode)] - internal static extern IntPtr PyUnicode_FromKindAndString(int kind, string s, int size); + [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData")] + internal static extern IntPtr PyUnicode_FromKindAndString( + int kind, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, + int size + ); internal static IntPtr PyUnicode_FromUnicode(string s, int size) { - return PyUnicode_FromKindAndString(2, s, size); + return PyUnicode_FromKindAndString(UCS, s, size); } [DllImport(PythonDll)] @@ -1284,33 +1288,6 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromOrdinal")] internal static extern IntPtr PyUnicode_FromOrdinal(int c); -#elif UCS4 && PYTHON3 - [DllImport(PythonDll)] - internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); - - [DllImport(PythonDll)] - internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - - [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData")] - internal static extern IntPtr PyUnicode_FromKindAndString( - int kind, - [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, - int size - ); - - internal static IntPtr PyUnicode_FromUnicode(string s, int size) - { - return PyUnicode_FromKindAndString(4, s, size); - } - - [DllImport(PythonDll)] - internal static extern int PyUnicode_GetSize(IntPtr ob); - - [DllImport(PythonDll)] - internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - - [DllImport(PythonDll)] - internal static extern IntPtr PyUnicode_FromOrdinal(int c); #elif UCS4 && PYTHON2 [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromObject")] internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); From 464080f08e3df2f639b8e1a3abcb88489f0a75a1 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 28 Feb 2017 19:35:31 -0700 Subject: [PATCH 211/245] Unify PY2 UCS2/UCS4 unicode methods PyUnicodeEntryPoint is not used for PY3 since it was unified by PEP393. It could be defined as "PyUnicode_" for PY3 and further unify the code between PY2/PY3. Not implementing since not all PY3 methods exist in PY2 --- src/runtime/runtime.cs | 44 ++++++++++++++++++------------------------ 1 file changed, 19 insertions(+), 25 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 6629657fc..bde0fb660 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -82,8 +82,20 @@ public class Runtime { #if UCS4 public const int UCS = 4; + + /// + /// EntryPoint to be used in DllImport to map to correct Unicode + /// methods prior to PEP393. Only used for PY27. + /// + private const string PyUnicodeEntryPoint = "PyUnicodeUCS4_"; #elif UCS2 public const int UCS = 2; + + /// + /// EntryPoint to be used in DllImport to map to correct Unicode + /// methods prior to PEP393. Only used for PY27. + /// + private const string PyUnicodeEntryPoint = "PyUnicodeUCS2_"; #else #error You must define either UCS2 or UCS4! #endif @@ -1270,44 +1282,26 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) [DllImport(PythonDll)] internal static extern IntPtr PyUnicode_FromOrdinal(int c); -#elif UCS2 && PYTHON2 - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromObject")] - internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); - - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromEncodedObject")] - internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromUnicode", CharSet = CharSet.Unicode)] - internal static extern IntPtr PyUnicode_FromUnicode(string s, int size); - - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_GetSize")] - internal static extern int PyUnicode_GetSize(IntPtr ob); - - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_AsUnicode")] - internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS2_FromOrdinal")] - internal static extern IntPtr PyUnicode_FromOrdinal(int c); -#elif UCS4 && PYTHON2 - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromObject")] +#elif PYTHON2 + [DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "FromObject")] internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromEncodedObject")] + [DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "FromEncodedObject")] internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromUnicode")] + [DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "FromUnicode")] internal static extern IntPtr PyUnicode_FromUnicode( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, int size ); - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_GetSize")] + [DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "GetSize")] internal static extern int PyUnicode_GetSize(IntPtr ob); - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_AsUnicode")] + [DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "AsUnicode")] internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); - [DllImport(PythonDll, EntryPoint = "PyUnicodeUCS4_FromOrdinal")] + [DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "FromOrdinal")] internal static extern IntPtr PyUnicode_FromOrdinal(int c); #endif From 0fdb80a7ca068d0db5a99446c1004bc713ee13f5 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 28 Feb 2017 19:44:51 -0700 Subject: [PATCH 212/245] Rename internal methods to proper Python API name - PyUnicode_FromKindAndString to PyUnicode_FromKindAndData - PyString_AS_STRING to PyString_AsString --- src/runtime/converter.cs | 6 +++--- src/runtime/runtime.cs | 12 ++++++------ src/runtime/typemanager.cs | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 8b58e5e9a..b66150a29 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -498,7 +498,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo { if (Runtime.PyString_Size(value) == 1) { - op = Runtime.PyString_AS_STRING(value); + op = Runtime.PyString_AsString(value); result = (byte)Marshal.ReadByte(op); return true; } @@ -543,7 +543,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo { if (Runtime.PyString_Size(value) == 1) { - op = Runtime.PyString_AS_STRING(value); + op = Runtime.PyString_AsString(value); result = (sbyte)Marshal.ReadByte(op); return true; } @@ -588,7 +588,7 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo { if (Runtime.PyString_Size(value) == 1) { - op = Runtime.PyString_AS_STRING(value); + op = Runtime.PyString_AsString(value); result = (char)Marshal.ReadByte(op); return true; } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index bde0fb660..75b2a2a9d 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1243,8 +1243,8 @@ int size [DllImport(PythonDll)] internal static extern IntPtr PyString_FromStringAndSize(string value, int size); - [DllImport(PythonDll, EntryPoint = "PyString_AsString")] - internal static extern IntPtr PyString_AS_STRING(IntPtr op); + [DllImport(PythonDll)] + internal static extern IntPtr PyString_AsString(IntPtr op); [DllImport(PythonDll)] internal static extern int PyString_Size(IntPtr pointer); @@ -1262,8 +1262,8 @@ internal static bool PyUnicode_Check(IntPtr ob) [DllImport(PythonDll)] internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); - [DllImport(PythonDll, EntryPoint = "PyUnicode_FromKindAndData")] - internal static extern IntPtr PyUnicode_FromKindAndString( + [DllImport(PythonDll)] + internal static extern IntPtr PyUnicode_FromKindAndData( int kind, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, int size @@ -1271,7 +1271,7 @@ int size internal static IntPtr PyUnicode_FromUnicode(string s, int size) { - return PyUnicode_FromKindAndString(UCS, s, size); + return PyUnicode_FromKindAndData(UCS, s, size); } [DllImport(PythonDll)] @@ -1330,7 +1330,7 @@ internal static string GetManagedString(IntPtr op) #if PYTHON2 // Python 3 strings are all Unicode if (type == PyStringType) { - return Marshal.PtrToStringAnsi(PyString_AS_STRING(op), PyString_Size(op)); + return Marshal.PtrToStringAnsi(PyString_AsString(op), PyString_Size(op)); } #endif diff --git a/src/runtime/typemanager.cs b/src/runtime/typemanager.cs index b3b065cc4..6f373f036 100644 --- a/src/runtime/typemanager.cs +++ b/src/runtime/typemanager.cs @@ -415,7 +415,7 @@ internal static IntPtr AllocateTypeObject(string name) temp = Runtime.PyUnicode_FromString(name); #elif PYTHON2 IntPtr temp = Runtime.PyString_FromString(name); - IntPtr raw = Runtime.PyString_AS_STRING(temp); + IntPtr raw = Runtime.PyString_AsString(temp); #endif Marshal.WriteIntPtr(type, TypeOffset.tp_name, raw); Marshal.WriteIntPtr(type, TypeOffset.name, temp); From 9650e8bee8905f1baef7526bb5795fcc33564ee0 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Mar 2017 10:59:50 -0700 Subject: [PATCH 213/245] Fix PY27 dll mapping in Linux/macOS On 5062377296e3594d461ff9459b85c5eb9d660957 this was fixed for PY3 but left unchanged for PY2. On linux/macOS the library is aliased `python2.7` while in windows its `python 27`. Since internally it wasn't mapped to the correct library in Linux/macOS, we had to remap it again using the dll.config file. Closes #120 --- .travis.yml | 2 -- CHANGELOG.md | 6 ++++-- Python.Runtime.dll.config | 15 --------------- setup.py | 4 ++-- src/runtime/runtime.cs | 2 +- 5 files changed, 7 insertions(+), 22 deletions(-) delete mode 100644 Python.Runtime.dll.config diff --git a/.travis.yml b/.travis.yml index 95e13b574..c20f935ee 100644 --- a/.travis.yml +++ b/.travis.yml @@ -40,8 +40,6 @@ install: script: - python -m pytest - - - cp Python.Runtime.dll.config src/embed_tests/bin/ - mono ./packages/NUnit.*/tools/nunit3-console.exe src/embed_tests/bin/Python.EmbeddingTest.dll after_script: diff --git a/CHANGELOG.md b/CHANGELOG.md index f4f9a4e29..35d449ebd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,12 +49,14 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Fixed fixture location for Python tests and `Embedded_Tests` - Fixed `PythonException` crash during Shutdown (#400) - Fixed `AppDomain` unload during GC (#397)(#400) -- Fixed `Py_Main` & `PySys_SetArgvEx` no mem error on `UCS4/PY3` (#399) +- Fixed `Py_Main` & `PySys_SetArgvEx` `no mem error` on `UCS4/PY3` (#399) +- Fixed `Python.Runtime.dll.config` on macOS (#120) ### Removed - Removed `six` dependency for `unittests` (#329) - Removed `Mono.Unix` dependency for `UCS4` (#360) +- Removed need for `Python.Runtime.dll.config` ## [2.2.2][] - 2017-01-29 @@ -64,7 +66,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. ## [2.2.1][] - 2017-01-26 -- `v2.2.0` had a release issue on pypi. Bumped to `v2.2.1` +- `v2.2.0` had a release issue on PyPi. Bumped to `v2.2.1` ### Added diff --git a/Python.Runtime.dll.config b/Python.Runtime.dll.config deleted file mode 100644 index b820676cf..000000000 --- a/Python.Runtime.dll.config +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - diff --git a/setup.py b/setup.py index 30168dfde..6e14b91ec 100644 --- a/setup.py +++ b/setup.py @@ -104,7 +104,7 @@ def _get_interop_filename(): def _get_source_files(): """Walk project and collect the files needed for ext_module""" - for ext in (".sln", ".config"): + for ext in (".sln", ): for path in glob.glob("*" + ext): yield path @@ -381,7 +381,7 @@ def run(self): data_files=[ ("{install_platlib}", [ "{build_lib}/Python.Runtime.dll", - "Python.Runtime.dll.config"]), + ]), ], cmdclass={ "build_ext": BuildExtPythonnet, diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 75b2a2a9d..c5135f752 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -124,7 +124,7 @@ public class Runtime #if MONO_LINUX || MONO_OSX #if PYTHON27 - internal const string dllBase = "python27"; + internal const string dllBase = "python2.7"; #elif PYTHON33 internal const string dllBase = "python3.3"; #elif PYTHON34 From 044edfebea9da124307d0bddc5fc86aaec4c7b4a Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Mar 2017 11:41:36 -0700 Subject: [PATCH 214/245] Refactor runtime's dllBase As long as the API doesn't change on new python minor releases, all changes needed for new minor versions is isolated to a small section of code. --- src/runtime/runtime.cs | 44 +++++++++++------------------------------- 1 file changed, 11 insertions(+), 33 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index c5135f752..044fee51f 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -102,54 +102,30 @@ public class Runtime #if PYTHON27 public const string pyversion = "2.7"; - public const int pyversionnumber = 27; + public const string pyver = "27"; #elif PYTHON33 public const string pyversion = "3.3"; - public const int pyversionnumber = 33; + public const string pyver = "33"; #elif PYTHON34 public const string pyversion = "3.4"; - public const int pyversionnumber = 34; + public const string pyver = "34"; #elif PYTHON35 public const string pyversion = "3.5"; - public const int pyversionnumber = 35; + public const string pyver = "35"; #elif PYTHON36 public const string pyversion = "3.6"; - public const int pyversionnumber = 36; + public const string pyver = "36"; #elif PYTHON37 // TODO: Add interop37 after Python3.7 is released public const string pyversion = "3.7"; - public const int pyversionnumber = 37; + public const string pyver = "37"; #else #error You must define one of PYTHON33 to PYTHON37 or PYTHON27 #endif -#if MONO_LINUX || MONO_OSX -#if PYTHON27 - internal const string dllBase = "python2.7"; -#elif PYTHON33 - internal const string dllBase = "python3.3"; -#elif PYTHON34 - internal const string dllBase = "python3.4"; -#elif PYTHON35 - internal const string dllBase = "python3.5"; -#elif PYTHON36 - internal const string dllBase = "python3.6"; -#elif PYTHON37 - internal const string dllBase = "python3.7"; -#endif +#if MONO_LINUX || MONO_OSX // Linux/macOS use dotted version string + internal const string dllBase = "python" + pyversion; #else // Windows -#if PYTHON27 - internal const string dllBase = "python27"; -#elif PYTHON33 - internal const string dllBase = "python33"; -#elif PYTHON34 - internal const string dllBase = "python34"; -#elif PYTHON35 - internal const string dllBase = "python35"; -#elif PYTHON36 - internal const string dllBase = "python36"; -#elif PYTHON37 - internal const string dllBase = "python37"; -#endif + internal const string dllBase = "python" + pyver; #endif #if PYTHON_WITH_PYDEBUG @@ -174,6 +150,8 @@ public class Runtime public const string PythonDll = dllBase + dllWithPyDebug + dllWithPyMalloc + dllWithWideUnicode; #endif + public static readonly int pyversionnumber = Convert.ToInt32(pyver); + // set to true when python is finalizing internal static object IsFinalizingLock = new object(); internal static bool IsFinalizing = false; From 445531dff1a2c314ff495cfb755355c323f239ea Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Mar 2017 12:58:07 -0700 Subject: [PATCH 215/245] Style clean-up runtime.cs --- src/runtime/runtime.cs | 37 ++++++++++++++++++------------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 044fee51f..3611893aa 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -115,7 +115,7 @@ public class Runtime #elif PYTHON36 public const string pyversion = "3.6"; public const string pyver = "36"; -#elif PYTHON37 // TODO: Add interop37 after Python3.7 is released +#elif PYTHON37 // TODO: Add `interop37.cs` after PY37 is released public const string pyversion = "3.7"; public const string pyver = "37"; #else @@ -154,7 +154,7 @@ public class Runtime // set to true when python is finalizing internal static object IsFinalizingLock = new object(); - internal static bool IsFinalizing = false; + internal static bool IsFinalizing; internal static bool Is32Bit; internal static bool IsPython2; @@ -401,7 +401,7 @@ internal static IntPtr GetBoundArgTuple(IntPtr obj, IntPtr args) PyTuple_SetItem(items, 0, obj); XIncref(obj); - for (int i = 0; i < size; i++) + for (var i = 0; i < size; i++) { IntPtr item = PyTuple_GetItem(args, i); XIncref(item); @@ -419,14 +419,14 @@ internal static IntPtr ExtendTuple(IntPtr t, params IntPtr[] args) IntPtr item; IntPtr items = PyTuple_New(size + add); - for (int i = 0; i < size; i++) + for (var i = 0; i < size; i++) { item = PyTuple_GetItem(t, i); XIncref(item); PyTuple_SetItem(items, i, item); } - for (int n = 0; n < add; n++) + for (var n = 0; n < add; n++) { item = args[n]; XIncref(item); @@ -447,7 +447,7 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) // tuple of (managed or unmanaged) type objects, return a Type[] // containing the CLR Type objects that map to those types. IntPtr args = arg; - bool free = false; + var free = false; if (!PyTuple_Check(arg)) { @@ -458,10 +458,10 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) } int n = PyTuple_Size(args); - Type[] types = new Type[n]; + var types = new Type[n]; Type t = null; - for (int i = 0; i < n; i++) + for (var i = 0; i < n; i++) { IntPtr op = PyTuple_GetItem(args, i); if (mangleObjects && (!PyType_Check(op))) @@ -513,7 +513,7 @@ internal static unsafe void XIncref(IntPtr op) Py_IncRef(op); return; #else - void* p = (void*)op; + var p = (void*)op; if ((void*)0 != p) { if (Is32Bit) @@ -536,7 +536,7 @@ internal static unsafe void XDecref(IntPtr op) Py_DecRef(op); return; #else - void* p = (void*)op; + var p = (void*)op; if ((void*)0 != p) { if (Is32Bit) @@ -562,7 +562,6 @@ internal static unsafe void XDecref(IntPtr op) return; } NativeCall.Impl.Void_Call_1(new IntPtr(f), op); - return; } } #endif @@ -570,7 +569,7 @@ internal static unsafe void XDecref(IntPtr op) internal static unsafe long Refcount(IntPtr op) { - void* p = (void*)op; + var p = (void*)op; if ((void*)0 != p) { if (Is32Bit) @@ -786,15 +785,15 @@ internal static extern void Py_SetPath( /// internal static unsafe IntPtr PyObject_TYPE(IntPtr op) { - void* p = (void*)op; + var p = (void*)op; if ((void*)0 == p) { return IntPtr.Zero; } #if Py_DEBUG - int n = 3; + var n = 3; #else - int n = 1; + var n = 1; #endif if (Is32Bit) { @@ -966,13 +965,13 @@ internal static bool PyBool_Check(IntPtr ob) internal static IntPtr PyInt_FromInt32(int value) { - IntPtr v = new IntPtr(value); + var v = new IntPtr(value); return PyInt_FromLong(v); } internal static IntPtr PyInt_FromInt64(long value) { - IntPtr v = new IntPtr(value); + var v = new IntPtr(value); return PyInt_FromLong(v); } @@ -1285,7 +1284,7 @@ int size internal static IntPtr PyUnicode_FromString(string s) { - return PyUnicode_FromUnicode(s, (s.Length)); + return PyUnicode_FromUnicode(s, s.Length); } /// @@ -1463,7 +1462,7 @@ internal static bool PyTuple_Check(IntPtr ob) #elif PYTHON3 internal static bool PyIter_Check(IntPtr pointer) { - IntPtr ob_type = (IntPtr)Marshal.PtrToStructure(pointer + ObjectOffset.ob_type, typeof(IntPtr)); + var ob_type = (IntPtr)Marshal.PtrToStructure(pointer + ObjectOffset.ob_type, typeof(IntPtr)); IntPtr tp_iternext = ob_type + TypeOffset.tp_iternext; return tp_iternext != null && tp_iternext != _PyObject_NextNotImplemented; } From 3a7d56b75f768cc20ebd617c9f72fce247ebdedc Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Mar 2017 15:15:16 -0700 Subject: [PATCH 216/245] Temporary disable Codecov flags Codecov added a limit of 20 uploads due to current on-going bug https://docs.codecov.io/blog/week-8-2017 Also fixed flags casing, documentations says has to be lowercase. --- .travis.yml | 2 +- appveyor.yml | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index c20f935ee..bf336dc9f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -48,7 +48,7 @@ after_script: # Waiting on mono-coverage, SharpCover or xr.Baboon - coverage xml -i - - codecov --file coverage.xml --flags Setup_Linux + - codecov --file coverage.xml --flags setup_linux notifications: email: false diff --git a/appveyor.yml b/appveyor.yml index e973ac581..c108801e7 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -45,10 +45,13 @@ test_script: - ps: .\ci\appveyor_build_recipe.ps1 on_finish: - - coverage xml -i - - codecov --file coverage.xml --flags Setup_Windows - - codecov --file py.coverage --flags Python_Tests - - codecov --file cs.coverage --flags Embedded_Tests + # Temporary disable multiple upload due to codecov limit of 20 per commit. + # https://docs.codecov.io/blog/week-8-2017 + # - coverage xml -i + # - codecov --file coverage.xml --flags setup_windows + # - codecov --file py.coverage --flags python_tests + # - codecov --file cs.coverage --flags embedded_tests + - codecov --flags setup_windows artifacts: - path: dist\* From 50365862234d06d7793a202472feee34ba188aca Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 1 Mar 2017 20:46:08 -0700 Subject: [PATCH 217/245] Fix test_multiple_calls_to_initialize Exception check didn't upgrade syntax from unittests. Didn't cause issues because test was passing. --- src/tests/test_engine.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tests/test_engine.py b/src/tests/test_engine.py index cca08a4d2..60fdbf45d 100644 --- a/src/tests/test_engine.py +++ b/src/tests/test_engine.py @@ -15,8 +15,8 @@ def test_multiple_calls_to_initialize(): PythonEngine.Initialize() PythonEngine.Initialize() PythonEngine.Initialize() - except BaseException: - self.fail("Initialize() raise an exception.") + except Exception: + assert False # Initialize() raise an exception. @pytest.mark.skip(reason="FIXME: test crashes") From 6f3f3571229ba8674e09cbee6843911eacc4d311 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Mar 2017 09:10:18 -0700 Subject: [PATCH 218/245] Fix PythonEngine.Version Add TestPythonEngineProperties. Ensure PythonEngine properties are working correctly. Currently only work on 32bit machines. Closes #413 --- CHANGELOG.md | 1 + src/embed_tests/Python.EmbeddingTest.csproj | 1 + src/embed_tests/TestPythonEngineProperties.cs | 70 +++++++++++++++++++ src/runtime/pythonengine.cs | 14 ++-- src/runtime/runtime.cs | 10 +-- 5 files changed, 87 insertions(+), 9 deletions(-) create mode 100644 src/embed_tests/TestPythonEngineProperties.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 35d449ebd..bf3f3b2da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Fixed `AppDomain` unload during GC (#397)(#400) - Fixed `Py_Main` & `PySys_SetArgvEx` `no mem error` on `UCS4/PY3` (#399) - Fixed `Python.Runtime.dll.config` on macOS (#120) +- Fixed crash on `PythonEngine.Version` (#413) ### Removed diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index b48c909a0..3cca9da70 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -89,6 +89,7 @@ + diff --git a/src/embed_tests/TestPythonEngineProperties.cs b/src/embed_tests/TestPythonEngineProperties.cs new file mode 100644 index 000000000..c11eca6db --- /dev/null +++ b/src/embed_tests/TestPythonEngineProperties.cs @@ -0,0 +1,70 @@ +using System; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + public class TestPythonEngineProperties + { + [Test] + public static void GetBuildinfoDoesntCrash() + { + using (Py.GIL()) + { + string s = PythonEngine.BuildInfo; + + Assert.IsTrue(s.Length > 5); + Assert.IsTrue(s.Contains(",")); + } + } + + [Test] + public static void GetCompilerDoesntCrash() + { + using (Py.GIL()) + { + string s = PythonEngine.Compiler; + + Assert.IsTrue(s.Length > 0); + Assert.IsTrue(s.Contains("[")); + Assert.IsTrue(s.Contains("]")); + } + } + + [Test] + public static void GetCopyrightDoesntCrash() + { + using (Py.GIL()) + { + string s = PythonEngine.Copyright; + + Assert.IsTrue(s.Length > 0); + Assert.IsTrue(s.Contains("Python Software Foundation")); + } + } + + [Test] + public static void GetPlatformDoesntCrash() + { + using (Py.GIL()) + { + string s = PythonEngine.Platform; + + Assert.IsTrue(s.Length > 0); + Assert.IsTrue(s.Contains("x") || s.Contains("win")); + } + } + + [Test] + public static void GetVersionDoesntCrash() + { + using (Py.GIL()) + { + string s = PythonEngine.Version; + + Assert.IsTrue(s.Length > 0); + Assert.IsTrue(s.Contains(",")); + } + } + } +} diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index eb6f9fa4d..b199bcd2e 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.InteropServices; namespace Python.Runtime { @@ -96,22 +97,27 @@ public static string PythonPath public static string Version { - get { return Runtime.Py_GetVersion(); } + get { return Marshal.PtrToStringAnsi(Runtime.Py_GetVersion()); } } public static string BuildInfo { - get { return Runtime.Py_GetBuildInfo(); } + get { return Marshal.PtrToStringAnsi(Runtime.Py_GetBuildInfo()); } } public static string Platform { - get { return Runtime.Py_GetPlatform(); } + get { return Marshal.PtrToStringAnsi(Runtime.Py_GetPlatform()); } } public static string Copyright { - get { return Runtime.Py_GetCopyright(); } + get { return Marshal.PtrToStringAnsi(Runtime.Py_GetCopyright()); } + } + + public static string Compiler + { + get { return Marshal.PtrToStringAnsi(Runtime.Py_GetCompiler()); } } public static int RunSimpleString(string code) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 3611893aa..ad929b230 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -729,19 +729,19 @@ internal static extern void Py_SetPath( #endif [DllImport(PythonDll)] - internal static extern string Py_GetVersion(); + internal static extern IntPtr Py_GetVersion(); [DllImport(PythonDll)] - internal static extern string Py_GetPlatform(); + internal static extern IntPtr Py_GetPlatform(); [DllImport(PythonDll)] - internal static extern string Py_GetCopyright(); + internal static extern IntPtr Py_GetCopyright(); [DllImport(PythonDll)] - internal static extern string Py_GetCompiler(); + internal static extern IntPtr Py_GetCompiler(); [DllImport(PythonDll)] - internal static extern string Py_GetBuildInfo(); + internal static extern IntPtr Py_GetBuildInfo(); [DllImport(PythonDll)] internal static extern int PyRun_SimpleString(string code); From e200cae68134fdafe5baf87f953d81fcd79badb4 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Mar 2017 10:42:39 -0700 Subject: [PATCH 219/245] Add PYTHONPATH/PYTHONHOME default value tests Current tests crash on 64bit python on windows, and results get truncated on Linux. When working, PYTHONHOME should match ENV VAR if set. AppVeyor has been updated to test against not blank --- appveyor.yml | 3 ++ src/embed_tests/TestPythonEngineProperties.cs | 39 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/appveyor.yml b/appveyor.yml index c108801e7..53fada6d7 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -27,6 +27,9 @@ init: # Put desired Python version first in PATH - set PATH=%PYTHON%;%PYTHON%\Scripts;%PATH% + # Needed for test `GetPythonHomeDefault` + - set PYTHONHOME=%PYTHON% + install: - pip install --upgrade -r requirements.txt --quiet diff --git a/src/embed_tests/TestPythonEngineProperties.cs b/src/embed_tests/TestPythonEngineProperties.cs index c11eca6db..25da158f2 100644 --- a/src/embed_tests/TestPythonEngineProperties.cs +++ b/src/embed_tests/TestPythonEngineProperties.cs @@ -66,5 +66,44 @@ public static void GetVersionDoesntCrash() Assert.IsTrue(s.Contains(",")); } } + + [Test] + public static void GetPythonPathDefault() + { + PythonEngine.Initialize(); + string s = PythonEngine.PythonPath; + + StringAssert.Contains("python", s.ToLower()); + PythonEngine.Shutdown(); + } + + [Test] + public static void GetProgramNameDefault() + { + PythonEngine.Initialize(); + string s = PythonEngine.PythonHome; + + Assert.NotNull(s); + PythonEngine.Shutdown(); + } + + /// + /// Test default behavior of PYTHONHOME. If ENVVAR is set it will + /// return the same value. If not, returns EmptyString. + /// + /// + /// AppVeyor.yml has been update to tests with ENVVAR set. + /// + [Test] + public static void GetPythonHomeDefault() + { + string envPythonHome = Environment.GetEnvironmentVariable("PYTHONHOME") ?? ""; + + PythonEngine.Initialize(); + string enginePythonHome = PythonEngine.PythonHome; + + Assert.AreEqual(envPythonHome, enginePythonHome); + PythonEngine.Shutdown(); + } } } From 0cfc67a106ba0d69bf958e80ab3aab0a65262828 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Mar 2017 11:38:27 -0700 Subject: [PATCH 220/245] Fix get PYTHONHOME/PYTHONPATH marshal Unlike #413, the return type changes between PY2/PY3. Extended Custom Marshaler to convert IntPtr to Unicode String --- src/runtime/CustomMarshaler.cs | 27 +++++++++++++++++++++++++ src/runtime/pythonengine.cs | 36 +++++++++++++++++----------------- src/runtime/runtime.cs | 15 ++++++-------- 3 files changed, 51 insertions(+), 27 deletions(-) diff --git a/src/runtime/CustomMarshaler.cs b/src/runtime/CustomMarshaler.cs index 475fa05eb..bdc32b9d9 100644 --- a/src/runtime/CustomMarshaler.cs +++ b/src/runtime/CustomMarshaler.cs @@ -72,6 +72,33 @@ public static ICustomMarshaler GetInstance(string cookie) { return Instance; } + + public static string PtrToStringUni(IntPtr p) + { + if (p == IntPtr.Zero) + { + return null; + } + + int size = GetUnicodeByteLength(p); + var buffer = new byte[size]; + Marshal.Copy(p, buffer, 0, size); + return PyEncoding.GetString(buffer, 0, size); + } + + public static int GetUnicodeByteLength(IntPtr p) + { + var len = 0; + while (true) + { + int c = Runtime.UCS == 2 + ? Marshal.ReadInt16(p, len * 2) + : Marshal.ReadInt32(p, len * 4); + + if (c == 0) return len* Runtime.UCS; + checked{ ++len; } + } + } } diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index b199bcd2e..e6808a514 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -57,12 +57,12 @@ public static string ProgramName { get { - string result = Runtime.Py_GetProgramName(); - if (result == null) - { - return ""; - } - return result; + IntPtr p = Runtime.Py_GetProgramName(); + string result = Runtime.IsPython3 + ? StrMarshaler.PtrToStringUni(p) + : Marshal.PtrToStringAnsi(p); + + return result ?? ""; } set { Runtime.Py_SetProgramName(value); } } @@ -71,12 +71,12 @@ public static string PythonHome { get { - string result = Runtime.Py_GetPythonHome(); - if (result == null) - { - return ""; - } - return result; + IntPtr p = Runtime.Py_GetPythonHome(); + string result = Runtime.IsPython3 + ? StrMarshaler.PtrToStringUni(p) + : Marshal.PtrToStringAnsi(p); + + return result ?? ""; } set { Runtime.Py_SetPythonHome(value); } } @@ -85,12 +85,12 @@ public static string PythonPath { get { - string result = Runtime.Py_GetPath(); - if (result == null) - { - return ""; - } - return result; + IntPtr p = Runtime.Py_GetPath(); + string result = Runtime.IsPython3 + ? StrMarshaler.PtrToStringUni(p) + : Marshal.PtrToStringAnsi(p); + + return result ?? ""; } set { Runtime.Py_SetPath(value); } } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index ad929b230..eaf55c91b 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -683,8 +683,7 @@ public static extern int Py_Main( #if PYTHON3 [DllImport(PythonDll)] - [return: MarshalAs(UnmanagedType.LPWStr)] - internal static extern string Py_GetProgramName(); + internal static extern IntPtr Py_GetProgramName(); [DllImport(PythonDll)] internal static extern void Py_SetProgramName( @@ -692,8 +691,7 @@ internal static extern void Py_SetProgramName( ); [DllImport(PythonDll)] - [return: MarshalAs(UnmanagedType.LPWStr)] - internal static extern string Py_GetPythonHome(); + internal static extern IntPtr Py_GetPythonHome(); [DllImport(PythonDll)] internal static extern void Py_SetPythonHome( @@ -701,8 +699,7 @@ internal static extern void Py_SetPythonHome( ); [DllImport(PythonDll)] - [return: MarshalAs(UnmanagedType.LPWStr)] - internal static extern string Py_GetPath(); + internal static extern IntPtr Py_GetPath(); [DllImport(PythonDll)] internal static extern void Py_SetPath( @@ -710,19 +707,19 @@ internal static extern void Py_SetPath( ); #elif PYTHON2 [DllImport(PythonDll)] - internal static extern string Py_GetProgramName(); + internal static extern IntPtr Py_GetProgramName(); [DllImport(PythonDll)] internal static extern void Py_SetProgramName(string name); [DllImport(PythonDll)] - internal static extern string Py_GetPythonHome(); + internal static extern IntPtr Py_GetPythonHome(); [DllImport(PythonDll)] internal static extern void Py_SetPythonHome(string home); [DllImport(PythonDll)] - internal static extern string Py_GetPath(); + internal static extern IntPtr Py_GetPath(); [DllImport(PythonDll)] internal static extern void Py_SetPath(string home); From ffe64486b42aa6365e9af967d213caaaf22168f5 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Mar 2017 13:40:12 -0700 Subject: [PATCH 221/245] Rename internal StrMarshaler to UcsMarshaler To clarify that this is meant to be applied on Unicode type IntPtr and not strings like ones. Made Marshalers internal, don't see a reason to expose it. --- src/runtime/CustomMarshaler.cs | 10 +++++----- src/runtime/pythonengine.cs | 6 +++--- src/runtime/runtime.cs | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/runtime/CustomMarshaler.cs b/src/runtime/CustomMarshaler.cs index bdc32b9d9..2241f29ae 100644 --- a/src/runtime/CustomMarshaler.cs +++ b/src/runtime/CustomMarshaler.cs @@ -9,7 +9,7 @@ namespace Python.Runtime /// Abstract class defining boiler plate methods that /// Custom Marshalers will use. /// - public abstract class MarshalerBase : ICustomMarshaler + internal abstract class MarshalerBase : ICustomMarshaler { public object MarshalNativeToManaged(IntPtr pNativeData) { @@ -39,9 +39,9 @@ public int GetNativeDataSize() /// Custom Marshaler to deal with Managed String to Native /// conversion differences on UCS2/UCS4. /// - public class StrMarshaler : MarshalerBase + internal class UcsMarshaler : MarshalerBase { - private static readonly MarshalerBase Instance = new StrMarshaler(); + private static readonly MarshalerBase Instance = new UcsMarshaler(); private static readonly Encoding PyEncoding = Runtime.PyEncoding; public override IntPtr MarshalManagedToNative(object managedObj) @@ -106,7 +106,7 @@ public static int GetUnicodeByteLength(IntPtr p) /// Custom Marshaler to deal with Managed String Arrays to Native /// conversion differences on UCS2/UCS4. /// - public class StrArrayMarshaler : MarshalerBase + internal class StrArrayMarshaler : MarshalerBase { private static readonly MarshalerBase Instance = new StrArrayMarshaler(); private static readonly Encoding PyEncoding = Runtime.PyEncoding; @@ -161,7 +161,7 @@ public static ICustomMarshaler GetInstance(string cookie) /// If instead we used `MarshalAs(UnmanagedType.LPWStr)` the output to /// `foo` would be `f\x00o\x00o\x00`. /// - public class Utf8Marshaler : MarshalerBase + internal class Utf8Marshaler : MarshalerBase { private static readonly MarshalerBase Instance = new Utf8Marshaler(); private static readonly Encoding PyEncoding = Encoding.UTF8; diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index e6808a514..4a641e538 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -59,7 +59,7 @@ public static string ProgramName { IntPtr p = Runtime.Py_GetProgramName(); string result = Runtime.IsPython3 - ? StrMarshaler.PtrToStringUni(p) + ? UcsMarshaler.PtrToStringUni(p) : Marshal.PtrToStringAnsi(p); return result ?? ""; @@ -73,7 +73,7 @@ public static string PythonHome { IntPtr p = Runtime.Py_GetPythonHome(); string result = Runtime.IsPython3 - ? StrMarshaler.PtrToStringUni(p) + ? UcsMarshaler.PtrToStringUni(p) : Marshal.PtrToStringAnsi(p); return result ?? ""; @@ -87,7 +87,7 @@ public static string PythonPath { IntPtr p = Runtime.Py_GetPath(); string result = Runtime.IsPython3 - ? StrMarshaler.PtrToStringUni(p) + ? UcsMarshaler.PtrToStringUni(p) : Marshal.PtrToStringAnsi(p); return result ?? ""; diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index eaf55c91b..540e2c45c 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -1239,7 +1239,7 @@ internal static bool PyUnicode_Check(IntPtr ob) [DllImport(PythonDll)] internal static extern IntPtr PyUnicode_FromKindAndData( int kind, - [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UcsMarshaler))] string s, int size ); @@ -1265,7 +1265,7 @@ internal static IntPtr PyUnicode_FromUnicode(string s, int size) [DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "FromUnicode")] internal static extern IntPtr PyUnicode_FromUnicode( - [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrMarshaler))] string s, + [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UcsMarshaler))] string s, int size ); From f4c2ca2a2e57b94a8ebd9efb67decd0f5956ac14 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Mar 2017 18:03:59 -0700 Subject: [PATCH 222/245] Unset PYTHONHOME in AppVeyor Its messing with `conda` causing it to fail to start. Tests in the `pr` #415 make this unnecessary. --- appveyor.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 53fada6d7..c108801e7 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -27,9 +27,6 @@ init: # Put desired Python version first in PATH - set PATH=%PYTHON%;%PYTHON%\Scripts;%PATH% - # Needed for test `GetPythonHomeDefault` - - set PYTHONHOME=%PYTHON% - install: - pip install --upgrade -r requirements.txt --quiet From 0a478024175e52106d9d4ff2230e1f505e56d7d8 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Mar 2017 18:17:01 -0700 Subject: [PATCH 223/245] Update conda Update to using conda based on PY36. Remove reference to deleted `dll.config` file --- ci/appveyor_build_recipe.ps1 | 2 +- conda.recipe/bld.bat | 7 ------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/ci/appveyor_build_recipe.ps1 b/ci/appveyor_build_recipe.ps1 index 278e292b0..52520f4c2 100644 --- a/ci/appveyor_build_recipe.ps1 +++ b/ci/appveyor_build_recipe.ps1 @@ -2,7 +2,7 @@ $env:CONDA_PY = "$env:PY_VER" # Use pre-installed miniconda. Note that location differs if 64bit -$env:CONDA_BLD = "C:\miniconda35" +$env:CONDA_BLD = "C:\miniconda36" if ($env:PLATFORM -eq "x86"){ $env:CONDA_BLD_ARCH=32 diff --git a/conda.recipe/bld.bat b/conda.recipe/bld.bat index d846fc738..1495f877d 100644 --- a/conda.recipe/bld.bat +++ b/conda.recipe/bld.bat @@ -4,10 +4,3 @@ set PATH=C:\Program Files (x86)\MSBuild\14.0\Bin;%PATH% %PYTHON% setup.py install - -:: copy our compiled library -set SRC=%RECIPE_DIR%\.. -set DEST=%SP_DIR% - -:: Install step -copy %SRC%\Python.Runtime.dll.config %DEST% From 6668ebf5fef1a28246d5c691bf1d05d86b25fd32 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Mar 2017 01:24:34 -0700 Subject: [PATCH 224/245] Fix PythonEngine PYTHONHOME setter Keep memory reference & fix PY3 marshal --- src/embed_tests/TestPythonEngineProperties.cs | 25 +++++++++++++++++++ src/runtime/pythonengine.cs | 15 ++++++++++- src/runtime/runtime.cs | 6 ++--- 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/embed_tests/TestPythonEngineProperties.cs b/src/embed_tests/TestPythonEngineProperties.cs index 25da158f2..c7bf0870b 100644 --- a/src/embed_tests/TestPythonEngineProperties.cs +++ b/src/embed_tests/TestPythonEngineProperties.cs @@ -105,5 +105,30 @@ public static void GetPythonHomeDefault() Assert.AreEqual(envPythonHome, enginePythonHome); PythonEngine.Shutdown(); } + + [Test] + public void SetPythonHome() + { + var pythonHome = "/dummypath/"; + + PythonEngine.PythonHome = pythonHome; + PythonEngine.Initialize(); + + Assert.AreEqual(pythonHome, PythonEngine.PythonHome); + PythonEngine.Shutdown(); + } + + [Test] + public void SetPythonHomeTwice() + { + var pythonHome = "/dummypath/"; + + PythonEngine.PythonHome = "/dummypath2/"; + PythonEngine.PythonHome = pythonHome; + PythonEngine.Initialize(); + + Assert.AreEqual(pythonHome, PythonEngine.PythonHome); + PythonEngine.Shutdown(); + } } } diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 4a641e538..8a00bb39f 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -14,6 +14,7 @@ public class PythonEngine : IDisposable { private static DelegateManager delegateManager; private static bool initialized; + private static IntPtr _pythonHome = IntPtr.Zero; public PythonEngine() { @@ -78,7 +79,17 @@ public static string PythonHome return result ?? ""; } - set { Runtime.Py_SetPythonHome(value); } + set + { + if (_pythonHome != IntPtr.Zero) + { + Marshal.FreeHGlobal(_pythonHome); + } + _pythonHome = Runtime.IsPython3 + ? UcsMarshaler.GetInstance("").MarshalManagedToNative(value) + : Marshal.StringToHGlobalAnsi(value); + Runtime.Py_SetPythonHome(_pythonHome); + } } public static string PythonPath @@ -284,6 +295,8 @@ public static void Shutdown() { if (initialized) { + Marshal.FreeHGlobal(_pythonHome); + _pythonHome = IntPtr.Zero; Runtime.Shutdown(); initialized = false; } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 540e2c45c..e73ce07c3 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -694,9 +694,7 @@ internal static extern void Py_SetProgramName( internal static extern IntPtr Py_GetPythonHome(); [DllImport(PythonDll)] - internal static extern void Py_SetPythonHome( - [MarshalAs(UnmanagedType.LPWStr)] string home - ); + internal static extern void Py_SetPythonHome(IntPtr home); [DllImport(PythonDll)] internal static extern IntPtr Py_GetPath(); @@ -716,7 +714,7 @@ internal static extern void Py_SetPath( internal static extern IntPtr Py_GetPythonHome(); [DllImport(PythonDll)] - internal static extern void Py_SetPythonHome(string home); + internal static extern void Py_SetPythonHome(IntPtr home); [DllImport(PythonDll)] internal static extern IntPtr Py_GetPath(); From 321aa28ba6229bf5eea619c6d484093c16f12700 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Mar 2017 16:40:12 -0700 Subject: [PATCH 225/245] Fix set PythonPath, set ProgramName Note on PythonPath. Its actually mapping to `Py_SetPath` which is very different from PYTHONPATH env var. There is no test on it because it should be set to real paths with libraries. Otherwise it crashes. 2nd Note. `Py_SetPath` doesn't exist on PY27. --- src/embed_tests/TestPythonEngineProperties.cs | 12 ++++++++ src/runtime/pythonengine.cs | 30 +++++++++++++++---- src/runtime/runtime.cs | 12 +++----- 3 files changed, 40 insertions(+), 14 deletions(-) diff --git a/src/embed_tests/TestPythonEngineProperties.cs b/src/embed_tests/TestPythonEngineProperties.cs index c7bf0870b..11db57b3d 100644 --- a/src/embed_tests/TestPythonEngineProperties.cs +++ b/src/embed_tests/TestPythonEngineProperties.cs @@ -130,5 +130,17 @@ public void SetPythonHomeTwice() Assert.AreEqual(pythonHome, PythonEngine.PythonHome); PythonEngine.Shutdown(); } + + [Test] + public void SetProgramName() + { + var programName = "FooBar"; + + PythonEngine.ProgramName = programName; + PythonEngine.Initialize(); + + Assert.AreEqual(programName, PythonEngine.ProgramName); + PythonEngine.Shutdown(); + } } } diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 8a00bb39f..b5f609630 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -15,6 +15,8 @@ public class PythonEngine : IDisposable private static DelegateManager delegateManager; private static bool initialized; private static IntPtr _pythonHome = IntPtr.Zero; + private static IntPtr _programName = IntPtr.Zero; + private static IntPtr _pythonPath = IntPtr.Zero; public PythonEngine() { @@ -65,7 +67,14 @@ public static string ProgramName return result ?? ""; } - set { Runtime.Py_SetProgramName(value); } + set + { + Marshal.FreeHGlobal(_programName); + _programName = Runtime.IsPython3 + ? UcsMarshaler.GetInstance("").MarshalManagedToNative(value) + : Marshal.StringToHGlobalAnsi(value); + Runtime.Py_SetProgramName(_programName); + } } public static string PythonHome @@ -81,10 +90,7 @@ public static string PythonHome } set { - if (_pythonHome != IntPtr.Zero) - { - Marshal.FreeHGlobal(_pythonHome); - } + Marshal.FreeHGlobal(_pythonHome); _pythonHome = Runtime.IsPython3 ? UcsMarshaler.GetInstance("").MarshalManagedToNative(value) : Marshal.StringToHGlobalAnsi(value); @@ -103,7 +109,14 @@ public static string PythonPath return result ?? ""; } - set { Runtime.Py_SetPath(value); } + set + { + Marshal.FreeHGlobal(_pythonPath); + _pythonPath = Runtime.IsPython3 + ? UcsMarshaler.GetInstance("").MarshalManagedToNative(value) + : Marshal.StringToHGlobalAnsi(value); + Runtime.Py_SetPath(_pythonPath); + } } public static string Version @@ -297,6 +310,11 @@ public static void Shutdown() { Marshal.FreeHGlobal(_pythonHome); _pythonHome = IntPtr.Zero; + Marshal.FreeHGlobal(_programName); + _programName = IntPtr.Zero; + Marshal.FreeHGlobal(_pythonPath); + _pythonPath = IntPtr.Zero; + Runtime.Shutdown(); initialized = false; } diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index e73ce07c3..d47c02490 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -686,9 +686,7 @@ public static extern int Py_Main( internal static extern IntPtr Py_GetProgramName(); [DllImport(PythonDll)] - internal static extern void Py_SetProgramName( - [MarshalAs(UnmanagedType.LPWStr)] string name - ); + internal static extern void Py_SetProgramName(IntPtr name); [DllImport(PythonDll)] internal static extern IntPtr Py_GetPythonHome(); @@ -700,15 +698,13 @@ internal static extern void Py_SetProgramName( internal static extern IntPtr Py_GetPath(); [DllImport(PythonDll)] - internal static extern void Py_SetPath( - [MarshalAs(UnmanagedType.LPWStr)] string home - ); + internal static extern void Py_SetPath(IntPtr home); #elif PYTHON2 [DllImport(PythonDll)] internal static extern IntPtr Py_GetProgramName(); [DllImport(PythonDll)] - internal static extern void Py_SetProgramName(string name); + internal static extern void Py_SetProgramName(IntPtr name); [DllImport(PythonDll)] internal static extern IntPtr Py_GetPythonHome(); @@ -720,7 +716,7 @@ internal static extern void Py_SetPath( internal static extern IntPtr Py_GetPath(); [DllImport(PythonDll)] - internal static extern void Py_SetPath(string home); + internal static extern void Py_SetPath(IntPtr home); #endif [DllImport(PythonDll)] From 3225465c39298f6205975dc24b41c3a2766ae1f6 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Mar 2017 09:57:12 -0700 Subject: [PATCH 226/245] Deprecate public RunString Had to remove defaults to disambiguate call on `internal RunString`. Can re-add after removing `public RunString` Closes #401 --- CHANGELOG.md | 6 +++++- src/runtime/pythonengine.cs | 20 +++++++++++++------- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c768b9946..ad9868020 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,10 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Unfroze Mono version on Travis (#345) - Changed `conda.recipe` build to only pull-requests (#345) +### Deprecated + +- Deprecated `RunString` (#401) + ### Fixed - Fixed crash during Initialization (#262)(#343) @@ -52,7 +56,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Fixed `Py_Main` & `PySys_SetArgvEx` `no mem error` on `UCS4/PY3` (#399) - Fixed `Python.Runtime.dll.config` on macOS (#120) - Fixed crash on `PythonEngine.Version` (#413) -- Fixed `PythonEngine.PythonPath` issues (#414) +- Fixed `PythonEngine.PythonPath` issues (#179)(#414)(#415) ### Removed diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index b5f609630..97d4eb693 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -469,16 +469,24 @@ public static void Exec(string code, IntPtr? globals = null, IntPtr? locals = nu /// - /// RunString Method + /// RunString Method. Function has been deprecated and will be removed. + /// Use Exec/Eval/RunSimpleString instead. + /// + [Obsolete("RunString is deprecated and will be removed. Use Exec/Eval/RunSimpleString instead.")] + public static PyObject RunString(string code, IntPtr? globals = null, IntPtr? locals = null) + { + return RunString(code, globals, locals, RunFlagType.File); + } + + /// + /// Internal RunString Method. /// /// /// Run a string containing Python code. Returns the result of /// executing the code string as a PyObject instance, or null if /// an exception was raised. /// - public static PyObject RunString( - string code, IntPtr? globals = null, IntPtr? locals = null, RunFlagType _flag = RunFlagType.File - ) + internal static PyObject RunString(string code, IntPtr? globals, IntPtr? locals, RunFlagType flag) { var borrowedGlobals = true; if (globals == null) @@ -502,12 +510,10 @@ public static PyObject RunString( borrowedLocals = false; } - var flag = (IntPtr)_flag; - try { IntPtr result = Runtime.PyRun_String( - code, flag, globals.Value, locals.Value + code, (IntPtr)flag, globals.Value, locals.Value ); Runtime.CheckExceptionOccurred(); From a14ff1479babf15519cbf1d775d56a90c7b621b7 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Mar 2017 10:31:46 -0700 Subject: [PATCH 227/245] Combine Py_DEBUG and PYTHON_WITH_PYDEBUG flags They both refer to the PyDebug builds but were added at different times. Closes #362 --- src/runtime/interop.cs | 8 ++++---- src/runtime/runtime.cs | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/runtime/interop.cs b/src/runtime/interop.cs index 14a69591c..4ae4b61e0 100644 --- a/src/runtime/interop.cs +++ b/src/runtime/interop.cs @@ -75,7 +75,7 @@ static ObjectOffset() { int size = IntPtr.Size; var n = 0; // Py_TRACE_REFS add two pointers to PyObject_HEAD -#if Py_DEBUG +#if PYTHON_WITH_PYDEBUG _ob_next = 0; _ob_prev = 1 * size; n = 2; @@ -113,14 +113,14 @@ public static int Size(IntPtr ob) { return ExceptionOffset.Size(); } -#if Py_DEBUG +#if PYTHON_WITH_PYDEBUG return 6 * IntPtr.Size; #else return 4 * IntPtr.Size; #endif } -#if Py_DEBUG +#if PYTHON_WITH_PYDEBUG public static int _ob_next; public static int _ob_prev; #endif @@ -185,7 +185,7 @@ static BytesOffset() /* The *real* layout of a type object when allocated on the heap */ //typedef struct _heaptypeobject { -#if Py_DEBUG // #ifdef Py_TRACE_REFS +#if PYTHON_WITH_PYDEBUG /* _PyObject_HEAD_EXTRA defines pointers to support a doubly-linked list of all live heap objects. */ public static int _ob_next = 0; public static int _ob_prev = 0; diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index d47c02490..3fee90fa5 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -508,7 +508,7 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) /// internal static unsafe void XIncref(IntPtr op) { -#if Py_DEBUG +#if PYTHON_WITH_PYDEBUG // according to Python doc, Py_IncRef() is Py_XINCREF() Py_IncRef(op); return; @@ -530,7 +530,7 @@ internal static unsafe void XIncref(IntPtr op) internal static unsafe void XDecref(IntPtr op) { -#if Py_DEBUG +#if PYTHON_WITH_PYDEBUG // Py_DecRef calls Python's Py_DECREF // according to Python doc, Py_DecRef() is Py_XDECREF() Py_DecRef(op); @@ -584,7 +584,7 @@ internal static unsafe long Refcount(IntPtr op) return 0; } -#if Py_DEBUG +#if PYTHON_WITH_PYDEBUG // Py_IncRef and Py_DecRef are taking care of the extra payload // in Py_DEBUG builds of Python like _Py_RefTotal [DllImport(PythonDll)] @@ -781,7 +781,7 @@ internal static unsafe IntPtr PyObject_TYPE(IntPtr op) { return IntPtr.Zero; } -#if Py_DEBUG +#if PYTHON_WITH_PYDEBUG var n = 3; #else var n = 1; From 8fba051956060aa325a7825a7e41910b2116c2ce Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Mar 2017 12:49:13 -0700 Subject: [PATCH 228/245] Remove PYTHON_WITH_WIDE_UNICODE flag ABIFlags were introduced in PY32, and --with_wide_unicode was removed in PY33. https://docs.python.org/3/whatsnew/3.3.html#functionality Closes #417 --- CHANGELOG.md | 2 ++ setup.py | 2 -- src/runtime/runtime.cs | 7 +------ 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad9868020..bf2384e9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Upgraded NUnit framework from `2.6.4` to `3.6.0` (#371) - Unfroze Mono version on Travis (#345) - Changed `conda.recipe` build to only pull-requests (#345) +- Combine `Py_DEBUG` and `PYTHON_WITH_PYDEBUG` flags (#362) ### Deprecated @@ -63,6 +64,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Removed `six` dependency for `unittests` (#329) - Removed `Mono.Unix` dependency for `UCS4` (#360) - Removed need for `Python.Runtime.dll.config` +- Removed PY32 build option `PYTHON_WITH_WIDE_UNICODE` (#417) ## [2.2.2][] - 2017-01-29 diff --git a/setup.py b/setup.py index 6e14b91ec..bb2a4d140 100644 --- a/setup.py +++ b/setup.py @@ -182,8 +182,6 @@ def build_extension(self, ext): defines.append("PYTHON_WITH_PYDEBUG") if "m" in sys.abiflags: defines.append("PYTHON_WITH_PYMALLOC") - if "u" in sys.abiflags: - defines.append("PYTHON_WITH_WIDE_UNICODE") # check the interop file exists, and create it if it doesn't interop_file = _get_interop_filename() diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index 3fee90fa5..d98a20c0a 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -138,16 +138,11 @@ public class Runtime #else internal const string dllWithPyMalloc = ""; #endif -#if PYTHON_WITH_WIDE_UNICODE - internal const string dllWithWideUnicode = "u"; -#else - internal const string dllWithWideUnicode = ""; -#endif #if PYTHON_WITHOUT_ENABLE_SHARED public const string PythonDll = "__Internal"; #else - public const string PythonDll = dllBase + dllWithPyDebug + dllWithPyMalloc + dllWithWideUnicode; + public const string PythonDll = dllBase + dllWithPyDebug + dllWithPyMalloc; #endif public static readonly int pyversionnumber = Convert.ToInt32(pyver); From 85c85f2f7152967e1177f24f48a148db2e810365 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Mar 2017 14:48:45 -0700 Subject: [PATCH 229/245] Refactor PY2/PY3 Marshal in/out String/Unicode --- src/runtime/CustomMarshaler.cs | 46 ++++++++++++++++++++++++++++++++-- src/runtime/pythonengine.cs | 30 +++++----------------- 2 files changed, 50 insertions(+), 26 deletions(-) diff --git a/src/runtime/CustomMarshaler.cs b/src/runtime/CustomMarshaler.cs index 2241f29ae..90bb77a71 100644 --- a/src/runtime/CustomMarshaler.cs +++ b/src/runtime/CustomMarshaler.cs @@ -95,10 +95,52 @@ public static int GetUnicodeByteLength(IntPtr p) ? Marshal.ReadInt16(p, len * 2) : Marshal.ReadInt32(p, len * 4); - if (c == 0) return len* Runtime.UCS; - checked{ ++len; } + if (c == 0) + { + return len * Runtime.UCS; + } + checked + { + ++len; + } } } + + /// + /// Utility function for Marshaling Unicode on PY3 and AnsiStr on PY2. + /// Use on functions whose Input signatures changed between PY2/PY3. + /// Ex. Py_SetPythonHome + /// + /// Managed String + /// + /// Ptr to Native String ANSI(PY2)/Unicode(PY3/UCS2)/UTF32(PY3/UCS4. + /// + /// + /// You MUST deallocate the IntPtr of the Return when done with it. + /// + public static IntPtr Py3UnicodePy2StringtoPtr(string s) + { + return Runtime.IsPython3 + ? Instance.MarshalManagedToNative(s) + : Marshal.StringToHGlobalAnsi(s); + } + + /// + /// Utility function for Marshaling Unicode IntPtr on PY3 and + /// AnsiStr IntPtr on PY2 to Managed Strings. Use on Python functions + /// whose return type changed between PY2/PY3. + /// Ex. Py_GetPythonHome + /// + /// Native Ansi/Unicode/UTF32 String + /// + /// Managed String + /// + public static string PtrToPy3UnicodePy2String(IntPtr p) + { + return Runtime.IsPython3 + ? PtrToStringUni(p) + : Marshal.PtrToStringAnsi(p); + } } diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index 97d4eb693..b97bea01b 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -61,18 +61,12 @@ public static string ProgramName get { IntPtr p = Runtime.Py_GetProgramName(); - string result = Runtime.IsPython3 - ? UcsMarshaler.PtrToStringUni(p) - : Marshal.PtrToStringAnsi(p); - - return result ?? ""; + return UcsMarshaler.PtrToPy3UnicodePy2String(p) ?? ""; } set { Marshal.FreeHGlobal(_programName); - _programName = Runtime.IsPython3 - ? UcsMarshaler.GetInstance("").MarshalManagedToNative(value) - : Marshal.StringToHGlobalAnsi(value); + _programName = UcsMarshaler.Py3UnicodePy2StringtoPtr(value); Runtime.Py_SetProgramName(_programName); } } @@ -82,18 +76,12 @@ public static string PythonHome get { IntPtr p = Runtime.Py_GetPythonHome(); - string result = Runtime.IsPython3 - ? UcsMarshaler.PtrToStringUni(p) - : Marshal.PtrToStringAnsi(p); - - return result ?? ""; + return UcsMarshaler.PtrToPy3UnicodePy2String(p) ?? ""; } set { Marshal.FreeHGlobal(_pythonHome); - _pythonHome = Runtime.IsPython3 - ? UcsMarshaler.GetInstance("").MarshalManagedToNative(value) - : Marshal.StringToHGlobalAnsi(value); + _pythonHome = UcsMarshaler.Py3UnicodePy2StringtoPtr(value); Runtime.Py_SetPythonHome(_pythonHome); } } @@ -103,18 +91,12 @@ public static string PythonPath get { IntPtr p = Runtime.Py_GetPath(); - string result = Runtime.IsPython3 - ? UcsMarshaler.PtrToStringUni(p) - : Marshal.PtrToStringAnsi(p); - - return result ?? ""; + return UcsMarshaler.PtrToPy3UnicodePy2String(p) ?? ""; } set { Marshal.FreeHGlobal(_pythonPath); - _pythonPath = Runtime.IsPython3 - ? UcsMarshaler.GetInstance("").MarshalManagedToNative(value) - : Marshal.StringToHGlobalAnsi(value); + _pythonPath = UcsMarshaler.Py3UnicodePy2StringtoPtr(value); Runtime.Py_SetPath(_pythonPath); } } From 895516e52bdb016208442c57613a356ca1a53bdb Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Mar 2017 15:36:57 -0700 Subject: [PATCH 230/245] Refactor runtime.cs --- src/runtime/runtime.cs | 48 +++++++----------------------------------- 1 file changed, 8 insertions(+), 40 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index d98a20c0a..d3c756adf 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -565,18 +565,11 @@ internal static unsafe void XDecref(IntPtr op) internal static unsafe long Refcount(IntPtr op) { var p = (void*)op; - if ((void*)0 != p) + if ((void*)0 == p) { - if (Is32Bit) - { - return (*(int*)p); - } - else - { - return (*(long*)p); - } + return 0; } - return 0; + return Is32Bit ? (*(int*)p) : (*(long*)p); } #if PYTHON_WITH_PYDEBUG @@ -676,25 +669,6 @@ public static extern int Py_Main( [DllImport(PythonDll)] internal static extern IntPtr PyEval_GetLocals(); -#if PYTHON3 - [DllImport(PythonDll)] - internal static extern IntPtr Py_GetProgramName(); - - [DllImport(PythonDll)] - internal static extern void Py_SetProgramName(IntPtr name); - - [DllImport(PythonDll)] - internal static extern IntPtr Py_GetPythonHome(); - - [DllImport(PythonDll)] - internal static extern void Py_SetPythonHome(IntPtr home); - - [DllImport(PythonDll)] - internal static extern IntPtr Py_GetPath(); - - [DllImport(PythonDll)] - internal static extern void Py_SetPath(IntPtr home); -#elif PYTHON2 [DllImport(PythonDll)] internal static extern IntPtr Py_GetProgramName(); @@ -712,7 +686,6 @@ public static extern int Py_Main( [DllImport(PythonDll)] internal static extern void Py_SetPath(IntPtr home); -#endif [DllImport(PythonDll)] internal static extern IntPtr Py_GetVersion(); @@ -781,20 +754,15 @@ internal static unsafe IntPtr PyObject_TYPE(IntPtr op) #else var n = 1; #endif - if (Is32Bit) - { - return new IntPtr((void*)(*((uint*)p + n))); - } - else - { - return new IntPtr((void*)(*((ulong*)p + n))); - } + return Is32Bit + ? new IntPtr((void*)(*((uint*)p + n))) + : new IntPtr((void*)(*((ulong*)p + n))); } /// /// Managed version of the standard Python C API PyObject_Type call. - /// This version avoids a managed <-> unmanaged transition. This one - /// does incref the returned type object. + /// This version avoids a managed <-> unmanaged transition. + /// This one does incref the returned type object. /// internal static IntPtr PyObject_Type(IntPtr op) { From 7db41a9eaca9e702d9b7cc9363f99c3520fc930a Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Thu, 2 Mar 2017 21:47:11 -0700 Subject: [PATCH 231/245] Fix Py_SetPath not available in PY2 Closes #418 --- src/embed_tests/TestPythonEngineProperties.cs | 41 +++++++++++++++++++ src/runtime/pythonengine.cs | 4 ++ 2 files changed, 45 insertions(+) diff --git a/src/embed_tests/TestPythonEngineProperties.cs b/src/embed_tests/TestPythonEngineProperties.cs index 11db57b3d..9623ff25d 100644 --- a/src/embed_tests/TestPythonEngineProperties.cs +++ b/src/embed_tests/TestPythonEngineProperties.cs @@ -142,5 +142,46 @@ public void SetProgramName() Assert.AreEqual(programName, PythonEngine.ProgramName); PythonEngine.Shutdown(); } + + [Test] + public void SetPythonPath() + { + if (Runtime.Runtime.pyversion == "2.7") + { + // Assert.Skip outputs as a warning (ie. pending to fix) + Assert.Pass(); + } + + PythonEngine.Initialize(); + string path = PythonEngine.PythonPath; + PythonEngine.Shutdown(); + + PythonEngine.ProgramName = path; + PythonEngine.Initialize(); + + Assert.AreEqual(path, PythonEngine.PythonPath); + PythonEngine.Shutdown(); + } + + [Test] + public void SetPythonPathExceptionOn27() + { + if (Runtime.Runtime.pyversion != "2.7") + { + Assert.Pass(); + } + + // Get previous path to avoid crashing Python + PythonEngine.Initialize(); + string path = PythonEngine.PythonPath; + PythonEngine.Shutdown(); + + var ex = Assert.Throws(() => PythonEngine.PythonPath = "foo"); + Assert.AreEqual("Set PythonPath not supported on Python 2", ex.Message); + + PythonEngine.Initialize(); + Assert.AreEqual(path, PythonEngine.PythonPath); + PythonEngine.Shutdown(); + } } } diff --git a/src/runtime/pythonengine.cs b/src/runtime/pythonengine.cs index b97bea01b..1fd3b239a 100644 --- a/src/runtime/pythonengine.cs +++ b/src/runtime/pythonengine.cs @@ -95,6 +95,10 @@ public static string PythonPath } set { + if (Runtime.IsPython2) + { + throw new NotSupportedException("Set PythonPath not supported on Python 2"); + } Marshal.FreeHGlobal(_pythonPath); _pythonPath = UcsMarshaler.Py3UnicodePy2StringtoPtr(value); Runtime.Py_SetPath(_pythonPath); From 563f6a6f5024fa90beb8b872c3331f2626b111c9 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Fri, 3 Mar 2017 12:39:54 -0700 Subject: [PATCH 232/245] Calculate Runtime fields before Initialization --- src/runtime/runtime.cs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index d3c756adf..b3520913a 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -151,9 +151,9 @@ public class Runtime internal static object IsFinalizingLock = new object(); internal static bool IsFinalizing; - internal static bool Is32Bit; - internal static bool IsPython2; - internal static bool IsPython3; + internal static bool Is32Bit = IntPtr.Size == 4; + internal static bool IsPython2 = pyversionnumber < 30; + internal static bool IsPython3 = pyversionnumber >= 30; /// /// Encoding to use to convert Unicode to/from Managed to Native @@ -165,10 +165,6 @@ public class Runtime /// internal static void Initialize() { - Is32Bit = IntPtr.Size == 4; - IsPython2 = pyversionnumber < 30; - IsPython3 = pyversionnumber >= 30; - if (Py_IsInitialized() == 0) { Py_Initialize(); From 92996a103d392306b85c85cdedab1919efc1f4c3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 4 Mar 2017 12:42:40 -0700 Subject: [PATCH 233/245] Add timing to detect slow tests on pytest --- setup.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index d1a72ff31..38aa3eb3d 100644 --- a/setup.cfg +++ b/setup.cfg @@ -7,4 +7,4 @@ [tool:pytest] xfail_strict = True # -r fsxX: show extra summary info for: (f)ailed, (s)kip, (x)failed, (X)passed -addopts = -r fsxX --color=yes +addopts = -r fsxX --color=yes --durations=5 From 305040d7443406e1851d57040d250f778e6f94ee Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 4 Mar 2017 19:34:07 -0700 Subject: [PATCH 234/245] Rename test classes/files Make it easier to distinguish if editor tab refers to class or test. --- src/embed_tests/Python.EmbeddingTest.csproj | 12 ++++++------ src/embed_tests/{pyiter.cs => TestPyList.cs} | 2 +- src/embed_tests/{pylong.cs => TestPyLong.cs} | 2 +- src/embed_tests/{pyobject.cs => TestPyString.cs} | 2 +- src/embed_tests/{pytuple.cs => TestPyTuple.cs} | 2 +- .../{pythonexception.cs => TestPythonException.cs} | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) rename src/embed_tests/{pyiter.cs => TestPyList.cs} (96%) rename src/embed_tests/{pylong.cs => TestPyLong.cs} (93%) rename src/embed_tests/{pyobject.cs => TestPyString.cs} (92%) rename src/embed_tests/{pytuple.cs => TestPyTuple.cs} (99%) rename src/embed_tests/{pythonexception.cs => TestPythonException.cs} (96%) diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 3cca9da70..0db3567ae 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -80,16 +80,16 @@ - - - - + - - + + + + + diff --git a/src/embed_tests/pyiter.cs b/src/embed_tests/TestPyList.cs similarity index 96% rename from src/embed_tests/pyiter.cs rename to src/embed_tests/TestPyList.cs index b896ab4c9..7a0a132b9 100644 --- a/src/embed_tests/pyiter.cs +++ b/src/embed_tests/TestPyList.cs @@ -5,7 +5,7 @@ namespace Python.EmbeddingTest { - public class PyIterTest + public class TestPyList { [Test] public void TestOnPyList() diff --git a/src/embed_tests/pylong.cs b/src/embed_tests/TestPyLong.cs similarity index 93% rename from src/embed_tests/pylong.cs rename to src/embed_tests/TestPyLong.cs index 0c57a0a74..ce9fa2ecb 100644 --- a/src/embed_tests/pylong.cs +++ b/src/embed_tests/TestPyLong.cs @@ -4,7 +4,7 @@ namespace Python.EmbeddingTest { - public class PyLongTest + public class TestPyLong { [Test] public void TestToInt64() diff --git a/src/embed_tests/pyobject.cs b/src/embed_tests/TestPyString.cs similarity index 92% rename from src/embed_tests/pyobject.cs rename to src/embed_tests/TestPyString.cs index be35ed3ca..943bd7fd4 100644 --- a/src/embed_tests/pyobject.cs +++ b/src/embed_tests/TestPyString.cs @@ -4,7 +4,7 @@ namespace Python.EmbeddingTest { - public class PyObjectTest + public class TestPyString { [Test] public void TestUnicode() diff --git a/src/embed_tests/pytuple.cs b/src/embed_tests/TestPyTuple.cs similarity index 99% rename from src/embed_tests/pytuple.cs rename to src/embed_tests/TestPyTuple.cs index 541e13210..2316001ea 100644 --- a/src/embed_tests/pytuple.cs +++ b/src/embed_tests/TestPyTuple.cs @@ -4,7 +4,7 @@ namespace Python.EmbeddingTest { - public class PyTupleTest + public class TestPyTuple { /// /// Test IsTupleType without having to Initialize a tuple. diff --git a/src/embed_tests/pythonexception.cs b/src/embed_tests/TestPythonException.cs similarity index 96% rename from src/embed_tests/pythonexception.cs rename to src/embed_tests/TestPythonException.cs index 0323567d0..3cf4d0aa3 100644 --- a/src/embed_tests/pythonexception.cs +++ b/src/embed_tests/TestPythonException.cs @@ -11,7 +11,7 @@ namespace Python.EmbeddingTest /// Keeping this in the old-style SetUp/TearDown /// to ensure that setup still works. /// - public class PythonExceptionTest + public class TestPythonException { private IntPtr gs; From de3874cf5eac4dcc48980c450e2d03ac512391fc Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 4 Mar 2017 21:49:34 -0700 Subject: [PATCH 235/245] Add PyTuple Ctor tests --- src/embed_tests/TestPyTuple.cs | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/embed_tests/TestPyTuple.cs b/src/embed_tests/TestPyTuple.cs index 2316001ea..417cf2c73 100644 --- a/src/embed_tests/TestPyTuple.cs +++ b/src/embed_tests/TestPyTuple.cs @@ -58,6 +58,42 @@ public void TestPyTupleBadCtor() } } + [Test] + public void TestPyTupleCtorEmptyArray() + { + using (Py.GIL()) + { + var a = new PyObject[] { }; + var t = new PyTuple(a); + + Assert.AreEqual(0, t.Length()); + } + } + + [Test] + public void TestPyTupleCtorArrayPyIntEmpty() + { + using (Py.GIL()) + { + var a = new PyInt[] { }; + var t = new PyTuple(a); + + Assert.AreEqual(0, t.Length()); + } + } + + [Test] + public void TestPyTupleCtorArray() + { + using (Py.GIL()) + { + var a = new PyObject[] {new PyInt(1), new PyString("Foo") }; + var t = new PyTuple(a); + + Assert.AreEqual(2, t.Length()); + } + } + /// /// Test PyTuple.Concat(...) doesn't let invalid appends happen /// and throws and exception. From d7777b93083e4369982c8cdbdca2f393b249a9f5 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 5 Mar 2017 18:55:59 -0700 Subject: [PATCH 236/245] Define and document Py_IncRef/Py_DecRef --- src/runtime/runtime.cs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/runtime/runtime.cs b/src/runtime/runtime.cs index b3520913a..346ea745f 100644 --- a/src/runtime/runtime.cs +++ b/src/runtime/runtime.cs @@ -500,7 +500,6 @@ internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) internal static unsafe void XIncref(IntPtr op) { #if PYTHON_WITH_PYDEBUG - // according to Python doc, Py_IncRef() is Py_XINCREF() Py_IncRef(op); return; #else @@ -522,8 +521,6 @@ internal static unsafe void XIncref(IntPtr op) internal static unsafe void XDecref(IntPtr op) { #if PYTHON_WITH_PYDEBUG - // Py_DecRef calls Python's Py_DECREF - // according to Python doc, Py_DecRef() is Py_XDECREF() Py_DecRef(op); return; #else @@ -568,15 +565,21 @@ internal static unsafe long Refcount(IntPtr op) return Is32Bit ? (*(int*)p) : (*(long*)p); } -#if PYTHON_WITH_PYDEBUG - // Py_IncRef and Py_DecRef are taking care of the extra payload - // in Py_DEBUG builds of Python like _Py_RefTotal + /// + /// Export of Macro Py_XIncRef. Use XIncref instead. + /// Limit this function usage for Testing and Py_Debug builds + /// + /// PyObject Ptr [DllImport(PythonDll)] - private static extern void Py_IncRef(IntPtr ob); + internal static extern void Py_IncRef(IntPtr ob); + /// + /// Export of Macro Py_XDecRef. Use XDecref instead. + /// Limit this function usage for Testing and Py_Debug builds + /// + /// PyObject Ptr [DllImport(PythonDll)] - private static extern void Py_DecRef(IntPtr ob); -#endif + internal static extern void Py_DecRef(IntPtr ob); [DllImport(PythonDll)] internal static extern void Py_Initialize(); From 977ee9603faef020215e2f4e78c99376089de90d Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 5 Mar 2017 18:59:13 -0700 Subject: [PATCH 237/245] Add Tests --- src/embed_tests/Python.EmbeddingTest.csproj | 7 + src/embed_tests/TestCustomMarshal.cs | 25 +++ src/embed_tests/TestPyAnsiString.cs | 96 ++++++++++ src/embed_tests/TestPyFloat.cs | 138 ++++++++++++++ src/embed_tests/TestPyInt.cs | 190 +++++++++++++++++++ src/embed_tests/TestPyLong.cs | 198 +++++++++++++++++++- src/embed_tests/TestPyNumber.cs | 35 ++++ src/embed_tests/TestPySequence.cs | 95 ++++++++++ src/embed_tests/TestPyString.cs | 88 ++++++++- src/embed_tests/TestRuntime.cs | 51 +++++ 10 files changed, 912 insertions(+), 11 deletions(-) create mode 100644 src/embed_tests/TestCustomMarshal.cs create mode 100644 src/embed_tests/TestPyAnsiString.cs create mode 100644 src/embed_tests/TestPyFloat.cs create mode 100644 src/embed_tests/TestPyInt.cs create mode 100644 src/embed_tests/TestPyNumber.cs create mode 100644 src/embed_tests/TestPySequence.cs create mode 100644 src/embed_tests/TestRuntime.cs diff --git a/src/embed_tests/Python.EmbeddingTest.csproj b/src/embed_tests/Python.EmbeddingTest.csproj index 0db3567ae..9c417cd27 100644 --- a/src/embed_tests/Python.EmbeddingTest.csproj +++ b/src/embed_tests/Python.EmbeddingTest.csproj @@ -84,12 +84,19 @@ + + + + + + + diff --git a/src/embed_tests/TestCustomMarshal.cs b/src/embed_tests/TestCustomMarshal.cs new file mode 100644 index 000000000..04c690090 --- /dev/null +++ b/src/embed_tests/TestCustomMarshal.cs @@ -0,0 +1,25 @@ +using System; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + public class TestCustomMarshal + { + [Test] + public static void GetManagedStringTwice() + { + const string expected = "FooBar"; + using (Py.GIL()) + { + IntPtr op = Runtime.Runtime.PyUnicode_FromString(expected); + string s1 = Runtime.Runtime.GetManagedString(op); + string s2 = Runtime.Runtime.GetManagedString(op); + + Assert.AreEqual(1, Runtime.Runtime.Refcount(op)); + Assert.AreEqual(expected, s1); + Assert.AreEqual(expected, s2); + } + } + } +} diff --git a/src/embed_tests/TestPyAnsiString.cs b/src/embed_tests/TestPyAnsiString.cs new file mode 100644 index 000000000..9ba7d6cc6 --- /dev/null +++ b/src/embed_tests/TestPyAnsiString.cs @@ -0,0 +1,96 @@ +using System; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + public class TestPyAnsiString + { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + + [Test] + public void TestStringCtor() + { + const string expected = "foo"; + var actual = new PyAnsiString(expected); + Assert.AreEqual(expected, actual.ToString()); + } + + [Test] + public void TestEmptyStringCtor() + { + const string expected = ""; + var actual = new PyAnsiString(expected); + Assert.AreEqual(expected, actual.ToString()); + } + + [Test] + public void TestPyObjectCtor() + { + const string expected = "Foo"; + + var t = new PyAnsiString(expected); + var actual = new PyAnsiString(t); + + Assert.AreEqual(expected, actual.ToString()); + } + + [Test] + public void TestBadPyObjectCtor() + { + var t = new PyInt(5); + PyAnsiString actual = null; + + var ex = Assert.Throws(() => actual = new PyAnsiString(t)); + + StringAssert.StartsWith("object is not a string", ex.Message); + Assert.IsNull(actual); + } + + [Test] + public void TestCtorPtr() + { + const string expected = "foo"; + + var t = new PyAnsiString(expected); + var actual = new PyAnsiString(t.Handle); + + Assert.AreEqual(expected, actual.ToString()); + } + + [Test] + public void IsStringTrue() + { + var t = new PyAnsiString("foo"); + + Assert.True(PyAnsiString.IsStringType(t)); + } + + [Test] + public void IsStringFalse() + { + var t = new PyInt(5); + + Assert.False(PyAnsiString.IsStringType(t)); + } + + [Test] + [Ignore("Ambiguous behavior between PY2/PY3")] + public void TestUnicode() + { + const string expected = "foo\u00e9"; + PyObject actual = new PyAnsiString(expected); + Assert.AreEqual(expected, actual.ToString()); + } + } +} diff --git a/src/embed_tests/TestPyFloat.cs b/src/embed_tests/TestPyFloat.cs new file mode 100644 index 000000000..f2c85a77f --- /dev/null +++ b/src/embed_tests/TestPyFloat.cs @@ -0,0 +1,138 @@ +using System; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + /// + /// PyFloat implementation isn't complete, thus tests aren't complete. + /// + public class TestPyFloat + { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + + [Test] + public void IntPtrCtor() + { + var i = new PyFloat(1); + var ii = new PyFloat(i.Handle); + Assert.AreEqual(i.Handle, ii.Handle); + } + + [Test] + public void FloatCtor() + { + const float a = 4.5F; + var i = new PyFloat(a); + Assert.True(PyFloat.IsFloatType(i)); + // Assert.Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void PyObjectCtorGood() + { + var i = new PyFloat(5); + var a = new PyFloat(i); + Assert.True(PyFloat.IsFloatType(a)); + // Assert.Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void PyObjectCtorBad() + { + var i = new PyString("Foo"); + PyFloat a = null; + + var ex = Assert.Throws(() => a = new PyFloat(i)); + + StringAssert.StartsWith("object is not a float", ex.Message); + Assert.IsNull(a); + } + + [Test] + public void DoubleCtor() + { + const double a = 4.5; + var i = new PyFloat(a); + Assert.True(PyFloat.IsFloatType(i)); + // Assert.Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void StringIntCtor() + { + const string a = "5"; + var i = new PyFloat(a); + Assert.True(PyFloat.IsFloatType(i)); + // Assert.Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void StringDoubleCtor() + { + const string a = "4.5"; + var i = new PyFloat(a); + Assert.True(PyFloat.IsFloatType(i)); + // Assert.Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void StringBadCtor() + { + const string i = "Foo"; + PyFloat a = null; + + var ex = Assert.Throws(() => a = new PyFloat(i)); + + StringAssert.StartsWith("ValueError : could not convert string to float", ex.Message); + Assert.IsNull(a); + } + + [Test] + public void IsFloatTrue() + { + const double a = 4.5; + var i = new PyFloat(a); + Assert.True(PyFloat.IsFloatType(i)); + } + + [Test] + public void IsFloatFalse() + { + var i = new PyString("Foo"); + Assert.False(PyFloat.IsFloatType(i)); + } + + [Test] + public void AsFloatGood() + { + const double a = 4.5; + var i = new PyFloat(a); + PyFloat s = PyFloat.AsFloat(i); + + Assert.True(PyFloat.IsFloatType(s)); + // Assert.Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void AsFloatBad() + { + var s = new PyString("Foo"); + PyFloat a = null; + + var ex = Assert.Throws(() => a = PyFloat.AsFloat(s)); + StringAssert.StartsWith("ValueError : could not convert string to float", ex.Message); + Assert.IsNull(a); + } + } +} diff --git a/src/embed_tests/TestPyInt.cs b/src/embed_tests/TestPyInt.cs new file mode 100644 index 000000000..0cae171df --- /dev/null +++ b/src/embed_tests/TestPyInt.cs @@ -0,0 +1,190 @@ +using System; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + public class TestPyInt + { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + + [Test] + public void TestCtorInt() + { + const int i = 5; + var a = new PyInt(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorUInt() + { + const uint i = 5; + var a = new PyInt(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorLong() + { + const long i = 5; + var a = new PyInt(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorULong() + { + const ulong i = 5; + var a = new PyInt(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorShort() + { + const short i = 5; + var a = new PyInt(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorUShort() + { + const ushort i = 5; + var a = new PyInt(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorByte() + { + const byte i = 5; + var a = new PyInt(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorSByte() + { + const sbyte i = 5; + var a = new PyInt(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorPtr() + { + var i = new PyInt(5); + var a = new PyInt(i.Handle); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestCtorPyObject() + { + var i = new PyInt(5); + var a = new PyInt(i); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestCtorBadPyObject() + { + var i = new PyString("Foo"); + PyInt a = null; + + var ex = Assert.Throws(() => a = new PyInt(i)); + + StringAssert.StartsWith("object is not an int", ex.Message); + Assert.IsNull(a); + } + + [Test] + public void TestCtorString() + { + const string i = "5"; + var a = new PyInt(i); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestCtorBadString() + { + const string i = "Foo"; + PyInt a = null; + + var ex = Assert.Throws(() => a = new PyInt(i)); + + StringAssert.StartsWith("ValueError : invalid literal for int", ex.Message); + Assert.IsNull(a); + } + + [Test] + public void TestIsIntTypeTrue() + { + var i = new PyInt(5); + Assert.IsTrue(PyInt.IsIntType(i)); + } + + [Test] + public void TestIsIntTypeFalse() + { + var s = new PyString("Foo"); + Assert.IsFalse(PyInt.IsIntType(s)); + } + + [Test] + public void TestAsIntGood() + { + var i = new PyInt(5); + var a = PyInt.AsInt(i); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestAsIntBad() + { + var s = new PyString("Foo"); + PyInt a = null; + + var ex = Assert.Throws(() => a = PyInt.AsInt(s)); + StringAssert.StartsWith("ValueError : invalid literal for int", ex.Message); + Assert.IsNull(a); + } + + [Test] + public void TestConvertToInt32() + { + var a = new PyInt(5); + Assert.IsInstanceOf(typeof(int), a.ToInt32()); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestConvertToInt16() + { + var a = new PyInt(5); + Assert.IsInstanceOf(typeof(short), a.ToInt16()); + Assert.AreEqual(5, a.ToInt16()); + } + + [Test] + public void TestConvertToInt64() + { + var a = new PyInt(5); + Assert.IsInstanceOf(typeof(long), a.ToInt64()); + Assert.AreEqual(5, a.ToInt64()); + } + } +} diff --git a/src/embed_tests/TestPyLong.cs b/src/embed_tests/TestPyLong.cs index ce9fa2ecb..9299bca7e 100644 --- a/src/embed_tests/TestPyLong.cs +++ b/src/embed_tests/TestPyLong.cs @@ -6,15 +6,201 @@ namespace Python.EmbeddingTest { public class TestPyLong { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + [Test] public void TestToInt64() { - using (Py.GIL()) - { - long largeNumber = 8L * 1024L * 1024L * 1024L; // 8 GB - var pyLargeNumber = new PyLong(largeNumber); - Assert.AreEqual(largeNumber, pyLargeNumber.ToInt64()); - } + long largeNumber = 8L * 1024L * 1024L * 1024L; // 8 GB + var pyLargeNumber = new PyLong(largeNumber); + Assert.AreEqual(largeNumber, pyLargeNumber.ToInt64()); + } + + [Test] + public void TestCtorInt() + { + const int i = 5; + var a = new PyLong(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorUInt() + { + const uint i = 5; + var a = new PyLong(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorLong() + { + const long i = 5; + var a = new PyLong(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorULong() + { + const ulong i = 5; + var a = new PyLong(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorShort() + { + const short i = 5; + var a = new PyLong(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorUShort() + { + const ushort i = 5; + var a = new PyLong(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorByte() + { + const byte i = 5; + var a = new PyLong(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorSByte() + { + const sbyte i = 5; + var a = new PyLong(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorDouble() + { + double i = 5.0; + var a = new PyLong(i); + Assert.AreEqual(i, a.ToInt32()); + } + + [Test] + public void TestCtorPtr() + { + var i = new PyLong(5); + var a = new PyLong(i.Handle); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestCtorPyObject() + { + var i = new PyLong(5); + var a = new PyLong(i); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestCtorBadPyObject() + { + var i = new PyString("Foo"); + PyLong a = null; + + var ex = Assert.Throws(() => a = new PyLong(i)); + + StringAssert.StartsWith("object is not a long", ex.Message); + Assert.IsNull(a); + } + + [Test] + public void TestCtorString() + { + const string i = "5"; + var a = new PyLong(i); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestCtorBadString() + { + const string i = "Foo"; + PyLong a = null; + + var ex = Assert.Throws(() => a = new PyLong(i)); + + StringAssert.StartsWith("ValueError : invalid literal", ex.Message); + Assert.IsNull(a); + } + + [Test] + public void TestIsIntTypeTrue() + { + var i = new PyLong(5); + Assert.IsTrue(PyLong.IsLongType(i)); + } + + [Test] + public void TestIsLongTypeFalse() + { + var s = new PyString("Foo"); + Assert.IsFalse(PyLong.IsLongType(s)); + } + + [Test] + public void TestAsLongGood() + { + var i = new PyLong(5); + var a = PyLong.AsLong(i); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestAsLongBad() + { + var s = new PyString("Foo"); + PyLong a = null; + + var ex = Assert.Throws(() => a = PyLong.AsLong(s)); + StringAssert.StartsWith("ValueError : invalid literal", ex.Message); + Assert.IsNull(a); + } + + [Test] + public void TestConvertToInt32() + { + var a = new PyLong(5); + Assert.IsInstanceOf(typeof(int), a.ToInt32()); + Assert.AreEqual(5, a.ToInt32()); + } + + [Test] + public void TestConvertToInt16() + { + var a = new PyLong(5); + Assert.IsInstanceOf(typeof(short), a.ToInt16()); + Assert.AreEqual(5, a.ToInt16()); + } + + [Test] + public void TestConvertToInt64() + { + var a = new PyLong(5); + Assert.IsInstanceOf(typeof(long), a.ToInt64()); + Assert.AreEqual(5, a.ToInt64()); } } } diff --git a/src/embed_tests/TestPyNumber.cs b/src/embed_tests/TestPyNumber.cs new file mode 100644 index 000000000..8e829ce0e --- /dev/null +++ b/src/embed_tests/TestPyNumber.cs @@ -0,0 +1,35 @@ +using System; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + public class TestPyNumber + { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + + [Test] + public void IsNumberTypeTrue() + { + var i = new PyInt(1); + Assert.IsTrue(PyNumber.IsNumberType(i)); + } + + [Test] + public void IsNumberTypeFalse() + { + var s = new PyString("Foo"); + Assert.IsFalse(PyNumber.IsNumberType(s)); + } + } +} diff --git a/src/embed_tests/TestPySequence.cs b/src/embed_tests/TestPySequence.cs new file mode 100644 index 000000000..7c175b1ce --- /dev/null +++ b/src/embed_tests/TestPySequence.cs @@ -0,0 +1,95 @@ +using System; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + public class TestPySequence + { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + + [Test] + public void TestIsSequenceTrue() + { + var t = new PyString("FooBar"); + Assert.True(PySequence.IsSequenceType(t)); + } + + [Test] + public void TestIsSequenceFalse() + { + var t = new PyInt(5); + Assert.False(PySequence.IsSequenceType(t)); + } + + [Test] + public void TestGetSlice() + { + var t = new PyString("FooBar"); + + PyObject s = t.GetSlice(0, 3); + Assert.AreEqual("Foo", s.ToString()); + + PyObject s2 = t.GetSlice(3, 6); + Assert.AreEqual("Bar", s2.ToString()); + + PyObject s3 = t.GetSlice(0, 6); + Assert.AreEqual("FooBar", s3.ToString()); + + PyObject s4 = t.GetSlice(0, 12); + Assert.AreEqual("FooBar", s4.ToString()); + } + + [Test] + public void TestConcat() + { + var t1 = new PyString("Foo"); + var t2 = new PyString("Bar"); + + PyObject actual = t1.Concat(t2); + + Assert.AreEqual("FooBar", actual.ToString()); + } + + [Test] + public void TestRepeat() + { + var t1 = new PyString("Foo"); + + PyObject actual = t1.Repeat(3); + Assert.AreEqual("FooFooFoo", actual.ToString()); + + actual = t1.Repeat(-3); + Assert.AreEqual("", actual.ToString()); + } + + [Test] + public void TestContains() + { + var t1 = new PyString("FooBar"); + + Assert.True(t1.Contains(new PyString("a"))); + Assert.False(t1.Contains(new PyString("z"))); + } + + [Test] + public void TestIndex() + { + var t1 = new PyString("FooBar"); + + Assert.AreEqual(4, t1.Index(new PyString("a"))); + Assert.AreEqual(5, t1.Index(new PyString("r"))); + Assert.AreEqual(-1, t1.Index(new PyString("z"))); + } + } +} diff --git a/src/embed_tests/TestPyString.cs b/src/embed_tests/TestPyString.cs index 943bd7fd4..9d1cdb0e9 100644 --- a/src/embed_tests/TestPyString.cs +++ b/src/embed_tests/TestPyString.cs @@ -6,14 +6,92 @@ namespace Python.EmbeddingTest { public class TestPyString { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + + [Test] + public void TestStringCtor() + { + const string expected = "foo"; + var actual = new PyString(expected); + Assert.AreEqual(expected, actual.ToString()); + } + + [Test] + public void TestEmptyStringCtor() + { + const string expected = ""; + var actual = new PyString(expected); + Assert.AreEqual(expected, actual.ToString()); + } + + [Test] + [Ignore("Ambiguous behavior between PY2/PY3. Needs remapping")] + public void TestPyObjectCtor() + { + const string expected = "Foo"; + + var t = new PyString(expected); + var actual = new PyString(t); + + Assert.AreEqual(expected, actual.ToString()); + } + + [Test] + public void TestBadPyObjectCtor() + { + var t = new PyInt(5); + PyString actual = null; + + var ex = Assert.Throws(() => actual = new PyString(t)); + + StringAssert.StartsWith("object is not a string", ex.Message); + Assert.IsNull(actual); + } + + [Test] + public void TestCtorPtr() + { + const string expected = "foo"; + + var t = new PyString(expected); + var actual = new PyString(t.Handle); + + Assert.AreEqual(expected, actual.ToString()); + } + + [Test] + [Ignore("Ambiguous behavior between PY2/PY3. Needs remapping")] + public void IsStringTrue() + { + var t = new PyString("foo"); + + Assert.True(PyString.IsStringType(t)); + } + + [Test] + public void IsStringFalse() + { + var t = new PyInt(5); + + Assert.False(PyString.IsStringType(t)); + } + [Test] public void TestUnicode() { - using (Py.GIL()) - { - PyObject s = new PyString("foo\u00e9"); - Assert.AreEqual("foo\u00e9", s.ToString()); - } + const string expected = "foo\u00e9"; + PyObject actual = new PyString(expected); + Assert.AreEqual(expected, actual.ToString()); } } } diff --git a/src/embed_tests/TestRuntime.cs b/src/embed_tests/TestRuntime.cs new file mode 100644 index 000000000..22e6db0a9 --- /dev/null +++ b/src/embed_tests/TestRuntime.cs @@ -0,0 +1,51 @@ +using System; +using NUnit.Framework; +using Python.Runtime; + +namespace Python.EmbeddingTest +{ + public class TestRuntime + { + [Test] + public static void Py_IsInitializedValue() + { + Runtime.Runtime.Py_Finalize(); // In case another test left it on. + Assert.AreEqual(0, Runtime.Runtime.Py_IsInitialized()); + Runtime.Runtime.Py_Initialize(); + Assert.AreEqual(1, Runtime.Runtime.Py_IsInitialized()); + Runtime.Runtime.Py_Finalize(); + Assert.AreEqual(0, Runtime.Runtime.Py_IsInitialized()); + } + + [Test] + public static void RefCountTest() + { + Runtime.Runtime.Py_Initialize(); + IntPtr op = Runtime.Runtime.PyUnicode_FromString("FooBar"); + + // New object RefCount should be one + Assert.AreEqual(1, Runtime.Runtime.Refcount(op)); + + // Checking refcount didn't change refcount + Assert.AreEqual(1, Runtime.Runtime.Refcount(op)); + + // New reference doesn't increase refcount + IntPtr p = op; + Assert.AreEqual(1, Runtime.Runtime.Refcount(p)); + + // Py_IncRef/Py_DecRef increase and decrease RefCount + Runtime.Runtime.Py_IncRef(op); + Assert.AreEqual(2, Runtime.Runtime.Refcount(op)); + Runtime.Runtime.Py_DecRef(op); + Assert.AreEqual(1, Runtime.Runtime.Refcount(op)); + + // XIncref/XDecref increase and decrease RefCount + Runtime.Runtime.XIncref(op); + Assert.AreEqual(2, Runtime.Runtime.Refcount(op)); + Runtime.Runtime.XDecref(op); + Assert.AreEqual(1, Runtime.Runtime.Refcount(op)); + + Runtime.Runtime.Py_Finalize(); + } + } +} From 6e4cf9d0fc4443db6f63c2f3c55e838fbda35ee0 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 5 Mar 2017 19:36:27 -0700 Subject: [PATCH 238/245] Refactor Exception checking on tested classes --- src/runtime/pyansistring.cs | 5 +--- src/runtime/pyfloat.cs | 15 ++-------- src/runtime/pyint.cs | 30 ++++---------------- src/runtime/pylong.cs | 55 ++++++++----------------------------- src/runtime/pystring.cs | 5 +--- 5 files changed, 22 insertions(+), 88 deletions(-) diff --git a/src/runtime/pyansistring.cs b/src/runtime/pyansistring.cs index 4843e5e2c..3d1d6ab68 100644 --- a/src/runtime/pyansistring.cs +++ b/src/runtime/pyansistring.cs @@ -45,10 +45,7 @@ public PyAnsiString(PyObject o) public PyAnsiString(string s) { obj = Runtime.PyString_FromString(s); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } diff --git a/src/runtime/pyfloat.cs b/src/runtime/pyfloat.cs index cca436def..edfaca542 100644 --- a/src/runtime/pyfloat.cs +++ b/src/runtime/pyfloat.cs @@ -51,10 +51,7 @@ public PyFloat(PyObject o) public PyFloat(double value) { obj = Runtime.PyFloat_FromDouble(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -69,10 +66,7 @@ public PyFloat(string value) using (var s = new PyString(value)) { obj = Runtime.PyFloat_FromString(s.obj, IntPtr.Zero); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } } @@ -100,10 +94,7 @@ public static bool IsFloatType(PyObject value) public static PyFloat AsFloat(PyObject value) { IntPtr op = Runtime.PyNumber_Float(value.obj); - if (op == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); return new PyFloat(op); } } diff --git a/src/runtime/pyint.cs b/src/runtime/pyint.cs index c84939482..f6911d9d7 100644 --- a/src/runtime/pyint.cs +++ b/src/runtime/pyint.cs @@ -51,10 +51,7 @@ public PyInt(PyObject o) public PyInt(int value) { obj = Runtime.PyInt_FromInt32(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -68,10 +65,7 @@ public PyInt(int value) public PyInt(uint value) : base(IntPtr.Zero) { obj = Runtime.PyInt_FromInt64(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -84,10 +78,7 @@ public PyInt(uint value) : base(IntPtr.Zero) public PyInt(long value) : base(IntPtr.Zero) { obj = Runtime.PyInt_FromInt64(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -101,10 +92,7 @@ public PyInt(long value) : base(IntPtr.Zero) public PyInt(ulong value) : base(IntPtr.Zero) { obj = Runtime.PyInt_FromInt64((long)value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -163,10 +151,7 @@ public PyInt(sbyte value) : this((int)value) public PyInt(string value) { obj = Runtime.PyInt_FromString(value, IntPtr.Zero, 0); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -193,10 +178,7 @@ public static bool IsIntType(PyObject value) public static PyInt AsInt(PyObject value) { IntPtr op = Runtime.PyNumber_Int(value.obj); - if (op == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); return new PyInt(op); } diff --git a/src/runtime/pylong.cs b/src/runtime/pylong.cs index ade7cb42c..286af40df 100644 --- a/src/runtime/pylong.cs +++ b/src/runtime/pylong.cs @@ -51,10 +51,7 @@ public PyLong(PyObject o) public PyLong(int value) { obj = Runtime.PyLong_FromLong(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -68,10 +65,7 @@ public PyLong(int value) public PyLong(uint value) { obj = Runtime.PyLong_FromLong(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -84,10 +78,7 @@ public PyLong(uint value) public PyLong(long value) { obj = Runtime.PyLong_FromLongLong(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -101,10 +92,7 @@ public PyLong(long value) public PyLong(ulong value) { obj = Runtime.PyLong_FromUnsignedLongLong(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -117,10 +105,7 @@ public PyLong(ulong value) public PyLong(short value) { obj = Runtime.PyLong_FromLong(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -134,10 +119,7 @@ public PyLong(short value) public PyLong(ushort value) { obj = Runtime.PyLong_FromLong(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -150,10 +132,7 @@ public PyLong(ushort value) public PyLong(byte value) { obj = Runtime.PyLong_FromLong(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -167,10 +146,7 @@ public PyLong(byte value) public PyLong(sbyte value) { obj = Runtime.PyLong_FromLong(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -183,10 +159,7 @@ public PyLong(sbyte value) public PyLong(double value) { obj = Runtime.PyLong_FromDouble(value); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -199,10 +172,7 @@ public PyLong(double value) public PyLong(string value) { obj = Runtime.PyLong_FromString(value, IntPtr.Zero, 0); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } @@ -229,10 +199,7 @@ public static bool IsLongType(PyObject value) public static PyLong AsLong(PyObject value) { IntPtr op = Runtime.PyNumber_Long(value.obj); - if (op == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); return new PyLong(op); } diff --git a/src/runtime/pystring.cs b/src/runtime/pystring.cs index 624de80eb..c9c4f9f5b 100644 --- a/src/runtime/pystring.cs +++ b/src/runtime/pystring.cs @@ -54,10 +54,7 @@ public PyString(PyObject o) public PyString(string s) { obj = Runtime.PyUnicode_FromUnicode(s, s.Length); - if (obj == IntPtr.Zero) - { - throw new PythonException(); - } + Runtime.CheckExceptionOccurred(); } From 657d674681c33f2be0a27dbb231fd9edfde9222c Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 5 Mar 2017 22:29:55 -0700 Subject: [PATCH 239/245] Clean-up Embedded tests --- src/embed_tests/TestCustomMarshal.cs | 28 +++- src/embed_tests/TestPyInt.cs | 4 +- src/embed_tests/TestPyList.cs | 39 +++-- src/embed_tests/TestPyLong.cs | 4 +- src/embed_tests/TestPyNumber.cs | 4 +- src/embed_tests/TestPyTuple.cs | 157 ++++++++---------- src/embed_tests/TestPythonEngineProperties.cs | 22 +-- src/embed_tests/TestPythonException.cs | 13 +- src/embed_tests/dynamic.cs | 6 +- src/embed_tests/pyimport.cs | 6 +- src/embed_tests/pyrunstring.cs | 6 +- 11 files changed, 140 insertions(+), 149 deletions(-) diff --git a/src/embed_tests/TestCustomMarshal.cs b/src/embed_tests/TestCustomMarshal.cs index 04c690090..5860857a3 100644 --- a/src/embed_tests/TestCustomMarshal.cs +++ b/src/embed_tests/TestCustomMarshal.cs @@ -6,20 +6,30 @@ namespace Python.EmbeddingTest { public class TestCustomMarshal { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + [Test] public static void GetManagedStringTwice() { const string expected = "FooBar"; - using (Py.GIL()) - { - IntPtr op = Runtime.Runtime.PyUnicode_FromString(expected); - string s1 = Runtime.Runtime.GetManagedString(op); - string s2 = Runtime.Runtime.GetManagedString(op); - Assert.AreEqual(1, Runtime.Runtime.Refcount(op)); - Assert.AreEqual(expected, s1); - Assert.AreEqual(expected, s2); - } + IntPtr op = Runtime.Runtime.PyUnicode_FromString(expected); + string s1 = Runtime.Runtime.GetManagedString(op); + string s2 = Runtime.Runtime.GetManagedString(op); + + Assert.AreEqual(1, Runtime.Runtime.Refcount(op)); + Assert.AreEqual(expected, s1); + Assert.AreEqual(expected, s2); } } } diff --git a/src/embed_tests/TestPyInt.cs b/src/embed_tests/TestPyInt.cs index 0cae171df..4117336d8 100644 --- a/src/embed_tests/TestPyInt.cs +++ b/src/embed_tests/TestPyInt.cs @@ -134,14 +134,14 @@ public void TestCtorBadString() public void TestIsIntTypeTrue() { var i = new PyInt(5); - Assert.IsTrue(PyInt.IsIntType(i)); + Assert.True(PyInt.IsIntType(i)); } [Test] public void TestIsIntTypeFalse() { var s = new PyString("Foo"); - Assert.IsFalse(PyInt.IsIntType(s)); + Assert.False(PyInt.IsIntType(s)); } [Test] diff --git a/src/embed_tests/TestPyList.cs b/src/embed_tests/TestPyList.cs index 7a0a132b9..66b479b5c 100644 --- a/src/embed_tests/TestPyList.cs +++ b/src/embed_tests/TestPyList.cs @@ -7,25 +7,36 @@ namespace Python.EmbeddingTest { public class TestPyList { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + [Test] public void TestOnPyList() { - using (Py.GIL()) + var list = new PyList(); + + list.Append(new PyString("foo")); + list.Append(new PyString("bar")); + list.Append(new PyString("baz")); + var result = new List(); + foreach (PyObject item in list) { - var list = new PyList(); - list.Append(new PyString("foo")); - list.Append(new PyString("bar")); - list.Append(new PyString("baz")); - var result = new List(); - foreach (PyObject item in list) - { - result.Add(item.ToString()); - } - Assert.AreEqual(3, result.Count); - Assert.AreEqual("foo", result[0]); - Assert.AreEqual("bar", result[1]); - Assert.AreEqual("baz", result[2]); + result.Add(item.ToString()); } + + Assert.AreEqual(3, result.Count); + Assert.AreEqual("foo", result[0]); + Assert.AreEqual("bar", result[1]); + Assert.AreEqual("baz", result[2]); } } } diff --git a/src/embed_tests/TestPyLong.cs b/src/embed_tests/TestPyLong.cs index 9299bca7e..fe3e13ef5 100644 --- a/src/embed_tests/TestPyLong.cs +++ b/src/embed_tests/TestPyLong.cs @@ -150,14 +150,14 @@ public void TestCtorBadString() public void TestIsIntTypeTrue() { var i = new PyLong(5); - Assert.IsTrue(PyLong.IsLongType(i)); + Assert.True(PyLong.IsLongType(i)); } [Test] public void TestIsLongTypeFalse() { var s = new PyString("Foo"); - Assert.IsFalse(PyLong.IsLongType(s)); + Assert.False(PyLong.IsLongType(s)); } [Test] diff --git a/src/embed_tests/TestPyNumber.cs b/src/embed_tests/TestPyNumber.cs index 8e829ce0e..0261c15c1 100644 --- a/src/embed_tests/TestPyNumber.cs +++ b/src/embed_tests/TestPyNumber.cs @@ -22,14 +22,14 @@ public void Dispose() public void IsNumberTypeTrue() { var i = new PyInt(1); - Assert.IsTrue(PyNumber.IsNumberType(i)); + Assert.True(PyNumber.IsNumberType(i)); } [Test] public void IsNumberTypeFalse() { var s = new PyString("Foo"); - Assert.IsFalse(PyNumber.IsNumberType(s)); + Assert.False(PyNumber.IsNumberType(s)); } } } diff --git a/src/embed_tests/TestPyTuple.cs b/src/embed_tests/TestPyTuple.cs index 417cf2c73..362251049 100644 --- a/src/embed_tests/TestPyTuple.cs +++ b/src/embed_tests/TestPyTuple.cs @@ -6,6 +6,18 @@ namespace Python.EmbeddingTest { public class TestPyTuple { + [OneTimeSetUp] + public void SetUp() + { + PythonEngine.Initialize(); + } + + [OneTimeTearDown] + public void Dispose() + { + PythonEngine.Shutdown(); + } + /// /// Test IsTupleType without having to Initialize a tuple. /// PyTuple constructor use IsTupleType. This decouples the tests. @@ -13,11 +25,8 @@ public class TestPyTuple [Test] public void TestStringIsTupleType() { - using (Py.GIL()) - { - var s = new PyString("foo"); - Assert.IsFalse(PyTuple.IsTupleType(s)); - } + var s = new PyString("foo"); + Assert.False(PyTuple.IsTupleType(s)); } /// @@ -26,72 +35,54 @@ public void TestStringIsTupleType() [Test] public void TestPyTupleIsTupleType() { - using (Py.GIL()) - { - var t = new PyTuple(); - Assert.IsTrue(PyTuple.IsTupleType(t)); - } + var t = new PyTuple(); + Assert.True(PyTuple.IsTupleType(t)); } [Test] public void TestPyTupleEmpty() { - using (Py.GIL()) - { - var t = new PyTuple(); - Assert.AreEqual(0, t.Length()); - } + var t = new PyTuple(); + Assert.AreEqual(0, t.Length()); } [Test] public void TestPyTupleBadCtor() { - using (Py.GIL()) - { - var i = new PyInt(5); - PyTuple t = null; + var i = new PyInt(5); + PyTuple t = null; - var ex = Assert.Throws(() => t = new PyTuple(i)); + var ex = Assert.Throws(() => t = new PyTuple(i)); - Assert.AreEqual("object is not a tuple", ex.Message); - Assert.IsNull(t); - } + Assert.AreEqual("object is not a tuple", ex.Message); + Assert.IsNull(t); } [Test] public void TestPyTupleCtorEmptyArray() { - using (Py.GIL()) - { - var a = new PyObject[] { }; - var t = new PyTuple(a); + var a = new PyObject[] { }; + var t = new PyTuple(a); - Assert.AreEqual(0, t.Length()); - } + Assert.AreEqual(0, t.Length()); } [Test] public void TestPyTupleCtorArrayPyIntEmpty() { - using (Py.GIL()) - { - var a = new PyInt[] { }; - var t = new PyTuple(a); + var a = new PyInt[] { }; + var t = new PyTuple(a); - Assert.AreEqual(0, t.Length()); - } + Assert.AreEqual(0, t.Length()); } [Test] public void TestPyTupleCtorArray() { - using (Py.GIL()) - { - var a = new PyObject[] {new PyInt(1), new PyString("Foo") }; - var t = new PyTuple(a); + var a = new PyObject[] { new PyInt(1), new PyString("Foo") }; + var t = new PyTuple(a); - Assert.AreEqual(2, t.Length()); - } + Assert.AreEqual(2, t.Length()); } /// @@ -108,69 +99,58 @@ public void TestPyTupleCtorArray() [Test] public void TestPyTupleInvalidAppend() { - using (Py.GIL()) - { - PyObject s = new PyString("foo"); - var t = new PyTuple(); + PyObject s = new PyString("foo"); + var t = new PyTuple(); - var ex = Assert.Throws(() => t.Concat(s)); + var ex = Assert.Throws(() => t.Concat(s)); - StringAssert.StartsWith("TypeError : can only concatenate tuple", ex.Message); - Assert.AreEqual(0, t.Length()); - Assert.IsEmpty(t); - } + StringAssert.StartsWith("TypeError : can only concatenate tuple", ex.Message); + Assert.AreEqual(0, t.Length()); + Assert.IsEmpty(t); } [Test] public void TestPyTupleValidAppend() { - using (Py.GIL()) - { - var t0 = new PyTuple(); - var t = new PyTuple(); - t.Concat(t0); - Assert.IsNotNull(t); - Assert.IsInstanceOf(typeof(PyTuple), t); - } + var t0 = new PyTuple(); + var t = new PyTuple(); + t.Concat(t0); + + Assert.IsNotNull(t); + Assert.IsInstanceOf(typeof(PyTuple), t); } [Test] public void TestPyTupleStringConvert() { - using (Py.GIL()) - { - PyObject s = new PyString("foo"); - PyTuple t = PyTuple.AsTuple(s); - Assert.IsNotNull(t); - Assert.IsInstanceOf(typeof(PyTuple), t); - Assert.AreEqual("f", t[0].ToString()); - Assert.AreEqual("o", t[1].ToString()); - Assert.AreEqual("o", t[2].ToString()); - } + PyObject s = new PyString("foo"); + PyTuple t = PyTuple.AsTuple(s); + + Assert.IsNotNull(t); + Assert.IsInstanceOf(typeof(PyTuple), t); + Assert.AreEqual("f", t[0].ToString()); + Assert.AreEqual("o", t[1].ToString()); + Assert.AreEqual("o", t[2].ToString()); } [Test] public void TestPyTupleValidConvert() { - using (Py.GIL()) - { - var l = new PyList(); - PyTuple t = PyTuple.AsTuple(l); - Assert.IsNotNull(t); - Assert.IsInstanceOf(typeof(PyTuple), t); - } + var l = new PyList(); + PyTuple t = PyTuple.AsTuple(l); + + Assert.IsNotNull(t); + Assert.IsInstanceOf(typeof(PyTuple), t); } [Test] public void TestNewPyTupleFromPyTuple() { - using (Py.GIL()) - { - var t0 = new PyTuple(); - var t = new PyTuple(t0); - Assert.IsNotNull(t); - Assert.IsInstanceOf(typeof(PyTuple), t); - } + var t0 = new PyTuple(); + var t = new PyTuple(t0); + + Assert.IsNotNull(t); + Assert.IsInstanceOf(typeof(PyTuple), t); } /// @@ -179,16 +159,13 @@ public void TestNewPyTupleFromPyTuple() [Test] public void TestInvalidAsTuple() { - using (Py.GIL()) - { - var i = new PyInt(5); - PyTuple t = null; + var i = new PyInt(5); + PyTuple t = null; - var ex = Assert.Throws(() => t = PyTuple.AsTuple(i)); + var ex = Assert.Throws(() => t = PyTuple.AsTuple(i)); - Assert.AreEqual("TypeError : 'int' object is not iterable", ex.Message); - Assert.IsNull(t); - } + Assert.AreEqual("TypeError : 'int' object is not iterable", ex.Message); + Assert.IsNull(t); } } } diff --git a/src/embed_tests/TestPythonEngineProperties.cs b/src/embed_tests/TestPythonEngineProperties.cs index 9623ff25d..01c6ae7e3 100644 --- a/src/embed_tests/TestPythonEngineProperties.cs +++ b/src/embed_tests/TestPythonEngineProperties.cs @@ -13,8 +13,8 @@ public static void GetBuildinfoDoesntCrash() { string s = PythonEngine.BuildInfo; - Assert.IsTrue(s.Length > 5); - Assert.IsTrue(s.Contains(",")); + Assert.True(s.Length > 5); + Assert.True(s.Contains(",")); } } @@ -25,9 +25,9 @@ public static void GetCompilerDoesntCrash() { string s = PythonEngine.Compiler; - Assert.IsTrue(s.Length > 0); - Assert.IsTrue(s.Contains("[")); - Assert.IsTrue(s.Contains("]")); + Assert.True(s.Length > 0); + Assert.True(s.Contains("[")); + Assert.True(s.Contains("]")); } } @@ -38,8 +38,8 @@ public static void GetCopyrightDoesntCrash() { string s = PythonEngine.Copyright; - Assert.IsTrue(s.Length > 0); - Assert.IsTrue(s.Contains("Python Software Foundation")); + Assert.True(s.Length > 0); + Assert.True(s.Contains("Python Software Foundation")); } } @@ -50,8 +50,8 @@ public static void GetPlatformDoesntCrash() { string s = PythonEngine.Platform; - Assert.IsTrue(s.Length > 0); - Assert.IsTrue(s.Contains("x") || s.Contains("win")); + Assert.True(s.Length > 0); + Assert.True(s.Contains("x") || s.Contains("win")); } } @@ -62,8 +62,8 @@ public static void GetVersionDoesntCrash() { string s = PythonEngine.Version; - Assert.IsTrue(s.Length > 0); - Assert.IsTrue(s.Contains(",")); + Assert.True(s.Length > 0); + Assert.True(s.Contains(",")); } } diff --git a/src/embed_tests/TestPythonException.cs b/src/embed_tests/TestPythonException.cs index 3cf4d0aa3..5470b246f 100644 --- a/src/embed_tests/TestPythonException.cs +++ b/src/embed_tests/TestPythonException.cs @@ -4,28 +4,21 @@ namespace Python.EmbeddingTest { - /// - /// Test Python Exceptions - /// - /// - /// Keeping this in the old-style SetUp/TearDown - /// to ensure that setup still works. - /// public class TestPythonException { - private IntPtr gs; + private IntPtr _gs; [SetUp] public void SetUp() { PythonEngine.Initialize(); - gs = PythonEngine.AcquireLock(); + _gs = PythonEngine.AcquireLock(); } [TearDown] public void Dispose() { - PythonEngine.ReleaseLock(gs); + PythonEngine.ReleaseLock(_gs); PythonEngine.Shutdown(); } diff --git a/src/embed_tests/dynamic.cs b/src/embed_tests/dynamic.cs index bfdc8fcc2..94397072a 100644 --- a/src/embed_tests/dynamic.cs +++ b/src/embed_tests/dynamic.cs @@ -7,18 +7,18 @@ namespace Python.EmbeddingTest { public class DynamicTest { - private Py.GILState gil; + private Py.GILState _gs; [SetUp] public void SetUp() { - gil = Py.GIL(); + _gs = Py.GIL(); } [TearDown] public void Dispose() { - gil.Dispose(); + _gs.Dispose(); } /// diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index 17547d69a..d25d0b8c4 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -19,13 +19,13 @@ namespace Python.EmbeddingTest /// public class PyImportTest { - private IntPtr gs; + private IntPtr _gs; [SetUp] public void SetUp() { PythonEngine.Initialize(); - gs = PythonEngine.AcquireLock(); + _gs = PythonEngine.AcquireLock(); /* Append the tests directory to sys.path * using reflection to circumvent the private @@ -41,7 +41,7 @@ public void SetUp() [TearDown] public void Dispose() { - PythonEngine.ReleaseLock(gs); + PythonEngine.ReleaseLock(_gs); PythonEngine.Shutdown(); } diff --git a/src/embed_tests/pyrunstring.cs b/src/embed_tests/pyrunstring.cs index b17bb87f8..81a1b07ca 100644 --- a/src/embed_tests/pyrunstring.cs +++ b/src/embed_tests/pyrunstring.cs @@ -6,18 +6,18 @@ namespace Python.EmbeddingTest { public class RunStringTest { - private Py.GILState gil; + private Py.GILState _gs; [SetUp] public void SetUp() { - gil = Py.GIL(); + _gs = Py.GIL(); } [TearDown] public void Dispose() { - gil.Dispose(); + _gs.Dispose(); } [Test] From 8ce4e0e78ba6028cfb1447ce6c0d06950afd23aa Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sun, 5 Mar 2017 23:01:26 -0700 Subject: [PATCH 240/245] Add PyList tests --- src/embed_tests/TestPyList.cs | 130 ++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git a/src/embed_tests/TestPyList.cs b/src/embed_tests/TestPyList.cs index 66b479b5c..e9acfbb45 100644 --- a/src/embed_tests/TestPyList.cs +++ b/src/embed_tests/TestPyList.cs @@ -19,6 +19,136 @@ public void Dispose() PythonEngine.Shutdown(); } + [Test] + public void TestStringIsListType() + { + var s = new PyString("foo"); + Assert.False(PyList.IsListType(s)); + } + + [Test] + public void TestListIsListType() + { + var s = new PyList(); + Assert.True(PyList.IsListType(s)); + } + + [Test] + public void TestStringAsListType() + { + var i = new PyInt(5); + PyList t = null; + + var ex = Assert.Throws(() => t = PyList.AsList(i)); + + Assert.AreEqual("TypeError : 'int' object is not iterable", ex.Message); + Assert.IsNull(t); + } + + [Test] + public void TestListAsListType() + { + var l = new PyList(); + PyList t = PyList.AsList(l); + + Assert.IsNotNull(t); + Assert.IsInstanceOf(typeof(PyList), t); + } + + [Test] + public void TestEmptyCtor() + { + var s = new PyList(); + + Assert.IsInstanceOf(typeof(PyList), s); + Assert.AreEqual(0, s.Length()); + } + + [Test] + public void TestPyObjectArrayCtor() + { + var ai = new PyObject[] {new PyInt(3), new PyInt(2), new PyInt(1) }; + var s = new PyList(ai); + + Assert.IsInstanceOf(typeof(PyList), s); + Assert.AreEqual(3, s.Length()); + Assert.AreEqual("3", s[0].ToString()); + Assert.AreEqual("2", s[1].ToString()); + Assert.AreEqual("1", s[2].ToString()); + } + + [Test] + public void TestPyObjectCtor() + { + var a = new PyList(); + var s = new PyList(a); + + Assert.IsInstanceOf(typeof(PyList), s); + Assert.AreEqual(0, s.Length()); + } + + [Test] + public void TestBadPyObjectCtor() + { + var i = new PyInt(5); + PyList t = null; + + var ex = Assert.Throws(() => t = new PyList(i)); + + Assert.AreEqual("object is not a list", ex.Message); + Assert.IsNull(t); + } + + [Test] + public void TestAppend() + { + var ai = new PyObject[] { new PyInt(3), new PyInt(2), new PyInt(1) }; + var s = new PyList(ai); + s.Append(new PyInt(4)); + + Assert.AreEqual(4, s.Length()); + Assert.AreEqual("4", s[3].ToString()); + } + + [Test] + public void TestInsert() + { + var ai = new PyObject[] { new PyInt(3), new PyInt(2), new PyInt(1) }; + var s = new PyList(ai); + s.Insert(0, new PyInt(4)); + + Assert.AreEqual(4, s.Length()); + Assert.AreEqual("4", s[0].ToString()); + } + + [Test] + public void TestReverse() + { + var ai = new PyObject[] { new PyInt(3), new PyInt(1), new PyInt(2) }; + var s = new PyList(ai); + + s.Reverse(); + + Assert.AreEqual(3, s.Length()); + Assert.AreEqual("2", s[0].ToString()); + Assert.AreEqual("1", s[1].ToString()); + Assert.AreEqual("3", s[2].ToString()); + } + + [Test] + public void TestSort() + { + var ai = new PyObject[] { new PyInt(3), new PyInt(1), new PyInt(2) }; + var s = new PyList(ai); + + s.Sort(); + + Assert.AreEqual(3, s.Length()); + Assert.AreEqual("1", s[0].ToString()); + Assert.AreEqual("2", s[1].ToString()); + Assert.AreEqual("3", s[2].ToString()); + } + [Test] public void TestOnPyList() { From ae8e6f08df50fdad48cf69e6f1e1f3652510d90e Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Mar 2017 12:48:33 -0700 Subject: [PATCH 241/245] Add test for pyscript global variable casting Test for #420 --- .../fixtures/PyImportTest/cast_global_var.py | 7 +++++++ src/embed_tests/pyimport.cs | 15 +++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 src/embed_tests/fixtures/PyImportTest/cast_global_var.py diff --git a/src/embed_tests/fixtures/PyImportTest/cast_global_var.py b/src/embed_tests/fixtures/PyImportTest/cast_global_var.py new file mode 100644 index 000000000..f9499539e --- /dev/null +++ b/src/embed_tests/fixtures/PyImportTest/cast_global_var.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- + +FOO = 1 + + +def test_foo(): + return FOO diff --git a/src/embed_tests/pyimport.cs b/src/embed_tests/pyimport.cs index d25d0b8c4..3bb9a34d6 100644 --- a/src/embed_tests/pyimport.cs +++ b/src/embed_tests/pyimport.cs @@ -64,5 +64,20 @@ public void TestSysArgsImportException() PyObject module = PythonEngine.ImportModule("PyImportTest.sysargv"); Assert.IsNotNull(module); } + + /// + /// Test Global Variable casting. GH#420 + /// + [Test] + public void TestCastGlobalVar() + { + dynamic foo = Py.Import("PyImportTest.cast_global_var"); + Assert.AreEqual("1", foo.FOO.ToString()); + Assert.AreEqual("1", foo.test_foo().ToString()); + + foo.FOO = 2; + Assert.AreEqual("2", foo.FOO.ToString()); + Assert.AreEqual("2", foo.test_foo().ToString()); + } } } From 898e13ec975312f3a50b50b6b922c470abe0e7eb Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Tue, 7 Mar 2017 22:03:52 -0700 Subject: [PATCH 242/245] Clean-up README.md example --- README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6a721e70f..daa8b53d6 100644 --- a/README.md +++ b/README.md @@ -56,17 +56,22 @@ static void Main(string[] args) using (Py.GIL()) { dynamic np = Py.Import("numpy"); + Console.WriteLine(np.cos(np.pi * 2)); + dynamic sin = np.sin; - Console.WriteLine(np.cos(np.pi*2)); Console.WriteLine(sin(5)); + double c = np.cos(5) + sin(5); Console.WriteLine(c); /* this block is temporarily disabled due to regression #249 dynamic a = np.array(new List { 1, 2, 3 }); - dynamic b = np.array(new List { 6, 5, 4 }, Py.kw("dtype", np.int32)); Console.WriteLine(a.dtype); + + dynamic b = np.array(new List { 6, 5, 4 }, Py.kw("dtype", np.int32)); Console.WriteLine(b.dtype); - Console.WriteLine(a * b); */ + + Console.WriteLine(a * b); + */ Console.ReadKey(); } } @@ -80,7 +85,7 @@ Output: -0.6752620892 float64 int32 -[6. 10. 12.] +[ 6. 10. 12.] ``` [appveyor shield]: https://img.shields.io/appveyor/ci/pythonnet/pythonnet/master.svg?label=AppVeyor From 7d457efc7599684f0b236de69dada4c18aa430d3 Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Wed, 8 Mar 2017 08:35:58 -0700 Subject: [PATCH 243/245] Fix typo in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index daa8b53d6..2794298a6 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ from System.Windows.Forms import Form to apply keyword arguments. - All python objects should be declared as `dynamic` type. - Mathematical operations involving python and literal/managed types must - have the python object first, eg. `np.pi_2` works, `2_np.pi` doesn't. + have the python object first, eg. `np.pi * 2` works, `2 * np.pi` doesn't. ### Example From 21d1636c12f74fb5777ab4478a1ec5f8f935fe21 Mon Sep 17 00:00:00 2001 From: denfromufa Date: Fri, 10 Mar 2017 22:59:55 -0600 Subject: [PATCH 244/245] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf2384e9f..20b564627 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Added `requirements.txt` - Added to `PythonEngine` methods `Eval` and `Exec` (#389) - Added implementations of `ICustomMarshal` (#407) +- Added docker images +- Added hooks in pyinstaller and cx_freeze for pythonnet ### Changed From c3b59db2c1ffdb92e86257304b3588274277e14a Mon Sep 17 00:00:00 2001 From: Victor Uriarte Date: Sat, 11 Mar 2017 07:34:43 -0700 Subject: [PATCH 245/245] =?UTF-8?q?Bump=20version:=202.3.0.dev1=20?= =?UTF-8?q?=E2=86=92=202.3.0=20release?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- CHANGELOG.md | 10 ++++++---- conda.recipe/meta.yaml | 2 +- setup.py | 2 +- src/runtime/resources/clr.py | 2 +- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index f79dfb480..30af44995 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 2.3.0.dev1 +current_version = 2.3.0 parse = (?P\d+)\.(?P\d+)\.(?P\d+)(\.(?P[a-z]+)(?P\d+))? serialize = {major}.{minor}.{patch}.{release}{dev} diff --git a/CHANGELOG.md b/CHANGELOG.md index 20b564627..0c7de23c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ This project adheres to [Semantic Versioning][]. This document follows the conventions laid out in [Keep a CHANGELOG][]. -## [unreleased][] +## [2.3.0][] - 2017-03-11 ### Added @@ -24,8 +24,8 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - Added `requirements.txt` - Added to `PythonEngine` methods `Eval` and `Exec` (#389) - Added implementations of `ICustomMarshal` (#407) -- Added docker images -- Added hooks in pyinstaller and cx_freeze for pythonnet +- Added docker images (#322) +- Added hooks in `pyinstaller` and `cx_freeze` for `pythonnet` (#66) ### Changed @@ -543,7 +543,9 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. [semantic versioning]: http://semver.org/ -[unreleased]: ../../compare/v2.2.2...HEAD +[unreleased]: ../../compare/v2.3.0...HEAD + +[2.3.0]: ../../compare/v2.2.2...v2.3.0 [2.2.2]: ../../compare/v2.2.1...v2.2.2 diff --git a/conda.recipe/meta.yaml b/conda.recipe/meta.yaml index eaa8747b2..98602481f 100644 --- a/conda.recipe/meta.yaml +++ b/conda.recipe/meta.yaml @@ -1,6 +1,6 @@ package: name: pythonnet - version: "2.3.0.dev1" + version: "2.3.0" build: skip: True # [not win] diff --git a/setup.py b/setup.py index bb2a4d140..b85e2c8ad 100644 --- a/setup.py +++ b/setup.py @@ -365,7 +365,7 @@ def run(self): setup( name="pythonnet", - version="2.3.0.dev1", + version="2.3.0", description=".Net and Mono integration for Python", url='https://pythonnet.github.io/', license='MIT', diff --git a/src/runtime/resources/clr.py b/src/runtime/resources/clr.py index ccd17889f..91f1f6b15 100644 --- a/src/runtime/resources/clr.py +++ b/src/runtime/resources/clr.py @@ -2,7 +2,7 @@ Code in this module gets loaded into the main clr module. """ -__version__ = "2.3.0.dev1" +__version__ = "2.3.0" class clrproperty(object):