# -*- coding: utf-8 -*-"""Test CLR modules and the CLR import hook."""import clrimport timeimport typesimport warningsfrom fnmatch import fnmatchimport pytestfrom .utils import is_clr_class, is_clr_module, is_clr_root_module# testImplicitAssemblyLoad() passes on deprecation warning; perfect! ## clr.AddReference('System.Windows.Forms')def test_import_hook_works():"""Test that the import hook works correctly both using theincluded runtime and an external runtime. This must bethe first test run in the unit tests!"""from System import Stringdef test_import_clr():import clrassert is_clr_root_module(clr)def test_version_clr():import clrassert clr.__version__ >= "3.0.0"assert clr.__version__[-1] != "\n"def test_preload_var():import clrassert 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()import System.Configurationcontent = dir(System.Configuration)assert len(content) > 10, contentfinally:clr.setPreload(False)def test_module_interface():"""Test the interface exposed by CLR module objects."""import Systemassert 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_fileassert 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 Systemassert is_clr_module(System)assert System.__name__ == 'System'import sysassert isinstance(sys, types.ModuleType)assert sys.__name__ == 'sys'import http.client as httplibassert isinstance(httplib, types.ModuleType)assert httplib.__name__ == 'http.client'def test_simple_import_with_alias():"""Test simple import with aliasing."""import System as mySystemassert is_clr_module(mySystem)assert mySystem.__name__ == 'System'import sys as mySysassert isinstance(mySys, types.ModuleType)assert mySys.__name__ == 'sys'import http.client as myHttplibassert isinstance(myHttplib, types.ModuleType)assert myHttplib.__name__ == 'http.client'def test_dotted_name_import():"""Test dotted-name import."""import System.Reflectionassert is_clr_module(System.Reflection)assert System.Reflection.__name__ == 'System.Reflection'import xml.domassert 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.Reflectionassert is_clr_module(System.Reflection)assert System.Reflection.__name__ == 'System.Reflection'import System.Reflectionassert is_clr_module(System.Reflection)assert System.Reflection.__name__ == 'System.Reflection'def test_dotted_name_import_with_alias():"""Test dotted-name import with aliasing."""import System.Reflection as SysRefassert is_clr_module(SysRef)assert SysRef.__name__ == 'System.Reflection'import xml.dom as myDomassert isinstance(myDom, types.ModuleType)assert myDom.__name__ == 'xml.dom'def test_simple_import_from():"""Test simple 'import from'."""from System import Reflectionassert is_clr_module(Reflection)assert Reflection.__name__ == 'System.Reflection'from xml import domassert 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 Collassert is_clr_module(Coll)assert Coll.__name__ == 'System.Collections'from xml import dom as myDomassert isinstance(myDom, types.ModuleType)assert myDom.__name__ == 'xml.dom'def test_dotted_name_import_from():"""Test dotted-name 'import from'."""from System.Collections import Specializedassert is_clr_module(Specialized)assert Specialized.__name__ == 'System.Collections.Specialized'from System.Collections.Specialized import StringCollectionassert is_clr_class(StringCollection)assert StringCollection.__name__ == 'StringCollection'from xml.dom import pulldomassert isinstance(pulldom, types.ModuleType)assert pulldom.__name__ == 'xml.dom.pulldom'from xml.dom.pulldom import PullDOMassert isinstance(PullDOM, type)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 Specassert is_clr_module(Spec)assert Spec.__name__ == 'System.Collections.Specialized'from System.Collections.Specialized import StringCollection as SCassert is_clr_class(SC)assert SC.__name__ == 'StringCollection'from xml.dom import pulldom as myPulldomassert isinstance(myPulldom, types.ModuleType)assert myPulldom.__name__ == 'xml.dom.pulldom'from xml.dom.pulldom import PullDOM as myPullDOMassert isinstance(myPullDOM, type)assert myPullDOM.__name__ == 'PullDOM'def test_from_module_import_star():"""Test from module import * behavior."""clr.AddReference("System")count = len(locals().keys())m = __import__('System', globals(), locals(), ['*'])assert m.__name__ == 'System'assert is_clr_module(m)assert len(locals().keys()) > count + 1def test_implicit_assembly_load():"""Test implicit assembly loading via import."""with pytest.raises(ImportError):# MS.Build should not have been added as a reference yet# (and should exist for mono)# The implicit behavior has been disabled in 3.0# therefore this should failimport Microsoft.Buildwith warnings.catch_warnings(record=True) as w:try:clr.AddReference("System.Windows.Forms")except Exception:pytest.skip()import System.Windows.Forms as Formsassert is_clr_module(Forms)assert Forms.__name__ == 'System.Windows.Forms'from System.Windows.Forms import Formassert is_clr_class(Form)assert Form.__name__ == 'Form'assert len(w) == 0def test_explicit_assembly_load():"""Test explicit assembly loading using standard CLR tools."""from System.Reflection import Assemblyimport System, sysassembly = Assembly.LoadWithPartialName('Microsoft.CSharp')assert assembly is not Noneimport Microsoft.CSharpassert 'Microsoft.CSharp' in sys.modulesassembly = Assembly.LoadWithPartialName('SpamSpamSpamSpamEggsAndSpam')assert assembly is Nonedef 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 Systemassert 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.SpamSpamSpamdef test_lookup_no_namespace_type():"""Test lookup of types without a qualified namespace."""import Python.Testimport clrassert is_clr_class(clr.NoNamespaceType)def test_module_lookup_recursion():"""Test for recursive lookup handling."""with pytest.raises(ImportError):from System import Systemwith pytest.raises(AttributeError):import System_ = System.Systemdef test_module_get_attr():"""Test module getattr behavior."""import Systemimport System.Runtimeint_type = System.Int32assert is_clr_class(int_type)module = System.Runtimeassert is_clr_module(module)with pytest.raises(AttributeError):_ = System.Spamwith pytest.raises(TypeError):_ = getattr(System, 1)def test_module_attr_abuse():"""Test handling of attempts to set module attributes."""# 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 SystemSystem.__dict__['foo'] = 0return 1assert test()def test_module_type_abuse():"""Test handling of attempts to break the module type."""import Systemmtype = 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 ListAssembliesverbose = list(ListAssemblies(True))short = list(ListAssemblies(False))assert u'System' in shortassert u'Culture=' in verbose[0]assert u'Version=' in verbose[0]def test_clr_add_reference():from clr import AddReferencefrom System.IO import FileNotFoundExceptionfor name in ("System", "Python.Runtime"):assy = AddReference(name)assy_name = assy.GetName().Nameassert assy_name == namewith pytest.raises(FileNotFoundException):AddReference("somethingtotallysilly")def test_clr_add_reference_bad_path():import sysfrom clr import AddReferencefrom System.IO import FileNotFoundExceptionbad_path = "hello0円world"sys.path.append(bad_path)try:with pytest.raises(FileNotFoundException):AddReference("test_clr_add_reference_bad_path")finally:sys.path.remove(bad_path)def test_clr_get_clr_type():"""Test clr.GetClrType()."""from clr import GetClrTypeimport Systemfrom System import IComparablefrom System import ArgumentExceptionassert GetClrType(System.String).FullName == "System.String"comparable = GetClrType(IComparable)assert comparable.FullName == "System.IComparable"assert comparable.IsInterfaceassert GetClrType(int).FullName == "Python.Runtime.PyInt"assert GetClrType(str).FullName == "System.String"assert GetClrType(float).FullName == "System.Double"dblarr = System.Array[System.Double]assert GetClrType(dblarr).FullName == "System.Double[]"with pytest.raises(TypeError):GetClrType(1)with pytest.raises(TypeError):GetClrType("thiswillfail")def test_assembly_load_thread_safety():from Python.Test import ModuleTest# spin up .NET thread which loads assemblies and triggers AppDomain.AssemblyLoad eventModuleTest.RunThreads()time.sleep(1e-5)for _ in range(1, 100):# call import clr, which in AssemblyManager.GetNames iterates through the loaded typesimport clr# import some .NET typesfrom System import DateTimefrom System import Guidfrom System.Collections.Generic import Dictionary_ = Dictionary[Guid, DateTime]()ModuleTest.JoinThreads()@pytest.mark.skipif()def test_assembly_load_recursion_bug():"""Test fix for recursion bug documented in #627"""sys_config = pytest.importorskip("System.Configuration", reason="System.Configuration can't be imported")content = dir(sys_config.ConfigurationManager)assert len(content) > 5, content
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。