# -*- coding: utf-8 -*-# TODO: Add tests for ClassicClass, NewStyleClass?"""Test CLR class support."""import clrimport Python.Test as Testimport Systemimport pytestfrom .utils import DictProxyTypedef test_basic_reference_type():"""Test usage of CLR defined reference types."""assert System.String.Empty == ""def test_basic_value_type():"""Test usage of CLR defined value types."""assert System.Int32.MaxValue == 2147483647def test_class_standard_attrs():"""Test standard class attributes."""from Python.Test import ClassTestassert ClassTest.__name__ == 'ClassTest'assert ClassTest.__module__ == 'Python.Test'assert isinstance(ClassTest.__dict__, DictProxyType)assert len(ClassTest.__doc__) > 0def test_class_docstrings():"""Test standard class docstring generation"""from Python.Test import ClassTestvalue = 'Void .ctor()'assert ClassTest.__doc__ == valuedef test_class_default_str():"""Test the default __str__ implementation for managed objects."""s = System.String("this is a test")assert str(s) == "this is a test"def test_class_default_repr():"""Test the default __repr__ implementation for managed objects."""s = System.String("this is a test")assert repr(s).startswith("<System.String object")def test_non_public_class():"""Test that non-public classes are inaccessible."""with pytest.raises(ImportError):from Python.Test import InternalClasswith pytest.raises(AttributeError):_ = Test.InternalClassdef test_non_exported():"""Test [PyExport(false)]"""with pytest.raises(ImportError):from Python.Test import NonExportablewith pytest.raises(AttributeError):_ = Test.NonExportabledef test_basic_subclass():"""Test basic subclass of a managed class."""from System.Collections import Hashtableclass MyTable(Hashtable):def how_many(self):return self.Counttable = MyTable()assert table.__class__.__name__.endswith('MyTable')assert type(table).__name__.endswith('MyTable')assert len(table.__class__.__bases__) == 1assert table.__class__.__bases__[0] == Hashtableassert table.how_many() == 0assert table.Count == 0table.set_Item('one', 'one')assert table.how_many() == 1assert table.Count == 1def test_subclass_with_no_arg_constructor():"""Test subclass of a managed class with a no-arg constructor."""from Python.Test import ClassCtorTest1class SubClass(ClassCtorTest1):def __init__(self, name):self.name = name# This failed in earlier versions_ = SubClass('test')def test_subclass_with_various_constructors():"""Test subclass of a managed class with various constructors."""from Python.Test import ClassCtorTest2class SubClass(ClassCtorTest2):def __init__(self, v):ClassCtorTest2.__init__(self, v)self.value2 = vinst = SubClass('test')assert inst.value == 'test'assert inst.value2 == 'test'class SubClass2(ClassCtorTest2):def __init__(self, v):ClassCtorTest2.__init__(self, v)self.value2 = vinst = SubClass2('test')assert inst.value == 'test'assert inst.value2 == 'test'def test_struct_construction():"""Test construction of structs."""from Python.Test import Point# no default constructor, must supply argumentswith pytest.raises(TypeError):p = Point()p = Point(0, 0)assert p.X == 0assert p.Y == 0p.X = 10p.Y = 10assert p.X == 10assert p.Y == 10# test strange __new__ interactions# test weird metatype# test recursion# testdef test_ienumerable_iteration():"""Test iteration over objects supporting IEnumerable."""from Python.Test import ClassTestlist_ = ClassTest.GetArrayList()for item in list_:assert (item > -1) and (item < 10)dict_ = ClassTest.GetHashtable()for item in dict_:cname = item.__class__.__name__assert cname.endswith('DictionaryEntry')def test_ienumerator_iteration():"""Test iteration over objects supporting IEnumerator."""from Python.Test import ClassTestchars = ClassTest.GetEnumerator()for item in chars:assert item in 'test string'def test_iterable():"""Test what objects are Iterable"""from collections.abc import Iterablefrom Python.Test import ClassTestassert isinstance(System.String.Empty, Iterable)assert isinstance(ClassTest.GetArrayList(), Iterable)assert isinstance(ClassTest.GetEnumerator(), Iterable)assert (not isinstance(ClassTest, Iterable))assert (not isinstance(ClassTest(), Iterable))class ShouldBeIterable(ClassTest):def __iter__(self):return iter([])assert isinstance(ShouldBeIterable(), Iterable)def test_override_get_item():"""Test managed subclass overriding __getitem__."""from System.Collections import Hashtableclass MyTable(Hashtable):def __getitem__(self, key):value = Hashtable.__getitem__(self, key)return 'my ' + str(value)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'assert table.Count == 3def test_override_set_item():"""Test managed subclass overriding __setitem__."""from System.Collections import Hashtableclass 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'assert table['one'] == 'my one'assert table['two'] == 'my two'assert table['three'] == 'my three'assert table.Count == 3def test_add_and_remove_class_attribute():from System import TimeSpanfor _ in range(100):TimeSpan.new_method = lambda self_: self_.TotalMinutests = TimeSpan.FromHours(1)assert ts.new_method() == 60del TimeSpan.new_methodassert not hasattr(ts, "new_method")def test_comparisons():from System import DateTimeOffsetfrom Python.Test import ClassTestd1 = DateTimeOffset.Parse("2016-11-14")d2 = DateTimeOffset.Parse("2016-11-15")assert (d1 == d2) == Falseassert (d1 != d2) == Trueassert (d1 < d2) == Trueassert (d1 <= d2) == Trueassert (d1 >= d2) == Falseassert (d1 > d2) == Falseassert (d1 == d1) == Trueassert (d1 != d1) == Falseassert (d1 < d1) == Falseassert (d1 <= d1) == Trueassert (d1 >= d1) == Trueassert (d1 > d1) == Falseassert (d2 == d1) == Falseassert (d2 != d1) == Trueassert (d2 < d1) == Falseassert (d2 <= d1) == Falseassert (d2 >= d1) == Trueassert (d2 > d1) == Truewith pytest.raises(TypeError):d1 < Nonewith pytest.raises(TypeError):d1 < System.Guid()# ClassTest does not implement IComparablec1 = ClassTest()c2 = ClassTest()with pytest.raises(TypeError):c1 < c2def test_self_callback():"""Test calling back and forth between this and a c# baseclass."""class CallbackUser(Test.SelfCallbackTest):def DoCallback(self):self.PyCallbackWasCalled = Falseself.SameReference = Falsereturn self.Callback(self)def PyCallback(self, self2):self.PyCallbackWasCalled = Trueself.SameReference = self == self2testobj = CallbackUser()testobj.DoCallback()assert testobj.PyCallbackWasCalledassert testobj.SameReferencedef test_method_inheritance():"""Ensure that we call the overridden method instead of the one provided inthe base class."""base = Test.BaseClass()derived = Test.DerivedClass()assert base.IsBase() == Trueassert derived.IsBase() == Falsedef test_callable():"""Test that only delegate subtypes are callable"""def foo():passassert callable(System.String("foo")) == Falseassert callable(System.Action(foo)) == True
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。