开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (11)
标签 (29)
master
fix-binaryformatter-usage
compare-maybetype-by-name
python3.13
noncopyableanalyzer
null-check-before-bind
python-3.13
linting-and-formatting
gitpod
backports-2.5
improve-ci
v3.0.4
v3.0.3
v3.0.2
v3.0.1
v3.0.0-r1
v3.0.0
v3.0.0-rc6
v3.0.0-rc5
v3.0.0-rc4
v3.0.0-rc3
v3.0.0-rc2
v3.0.0-rc1
v3.0.0-a2
v3.0.0-a1
v2.5.2
v2.5.1
v2.5.0
v2.5.0-rc1
v2.4.0
v2.4.0-rc2
master
分支 (11)
标签 (29)
master
fix-binaryformatter-usage
compare-maybetype-by-name
python3.13
noncopyableanalyzer
null-check-before-bind
python-3.13
linting-and-formatting
gitpod
backports-2.5
improve-ci
v3.0.4
v3.0.3
v3.0.2
v3.0.1
v3.0.0-r1
v3.0.0
v3.0.0-rc6
v3.0.0-rc5
v3.0.0-rc4
v3.0.0-rc3
v3.0.0-rc2
v3.0.0-rc1
v3.0.0-a2
v3.0.0-a1
v2.5.2
v2.5.1
v2.5.0
v2.5.0-rc1
v2.4.0
v2.4.0-rc2
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (11)
标签 (29)
master
fix-binaryformatter-usage
compare-maybetype-by-name
python3.13
noncopyableanalyzer
null-check-before-bind
python-3.13
linting-and-formatting
gitpod
backports-2.5
improve-ci
v3.0.4
v3.0.3
v3.0.2
v3.0.1
v3.0.0-r1
v3.0.0
v3.0.0-rc6
v3.0.0-rc5
v3.0.0-rc4
v3.0.0-rc3
v3.0.0-rc2
v3.0.0-rc1
v3.0.0-a2
v3.0.0-a1
v2.5.2
v2.5.1
v2.5.0
v2.5.0-rc1
v2.4.0
v2.4.0-rc2
pythonnet
/
tests
/
test_exceptions.py
pythonnet
/
tests
/
test_exceptions.py
test_exceptions.py 12.85 KB
一键复制 编辑 原始数据 按行查看 历史
Félix Bourbonnais 提交于 2022年01月24日 23:04 +08:00 . Add tests for exception leaking.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
# -*- coding: utf-8 -*-
"""Test exception support."""
import sys
import System
import pytest
import pickle
# begin code from https://utcc.utoronto.ca/~cks/space/blog/python/GetAllObjects
import gc
# Recursively expand slist's objects
# into olist, using seen to track
# already processed objects.
def _getr(slist, olist, seen):
for e in slist:
if id(e) in seen:
continue
seen[id(e)] = None
olist.append(e)
tl = gc.get_referents(e)
if tl:
_getr(tl, olist, seen)
# The public function.
def get_all_objects():
gcl = gc.get_objects()
olist = []
seen = {}
# Just in case:
seen[id(gcl)] = None
seen[id(olist)] = None
seen[id(seen)] = None
# _getr does the real work.
_getr(gcl, olist, seen)
return olist
# end code from https://utcc.utoronto.ca/~cks/space/blog/python/GetAllObjects
def leak_check(func):
def do_leak_check():
func()
gc.collect()
exc = {x for x in get_all_objects() if isinstance(x, Exception) and not isinstance(x, pytest.PytestDeprecationWarning)}
print(len(exc))
if len(exc):
for x in exc:
print('-------')
print(repr(x))
print(gc.get_referrers(x))
print(len(gc.get_referrers(x)))
assert False
gc.collect()
return do_leak_check
def test_unified_exception_semantics():
"""Test unified exception semantics."""
e = System.Exception('Something bad happened')
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
with pytest.raises(NullReferenceException) as cm:
raise NullReferenceException("Aiiieee!")
exc = cm.value
assert isinstance(exc, NullReferenceException)
assert exc.Message == 'Aiiieee!'
def test_managed_exception_propagation():
"""Test propagation of exceptions raised in managed code."""
from System import Decimal, OverflowException
with pytest.raises(OverflowException):
Decimal.ToInt64(Decimal.MaxValue)
def test_managed_exception_conversion():
"""Test conversion of managed exceptions."""
from System import OverflowException
from Python.Test import ExceptionTest
e = ExceptionTest.GetBaseException()
assert isinstance(e, System.Exception)
e = ExceptionTest.GetExplicitException()
assert isinstance(e, OverflowException)
assert isinstance(e, System.Exception)
e = ExceptionTest.GetWidenedException()
assert isinstance(e, OverflowException)
assert isinstance(e, System.Exception)
v = ExceptionTest.SetBaseException(System.Exception('error'))
assert v
v = ExceptionTest.SetExplicitException(OverflowException('error'))
assert v
v = ExceptionTest.SetWidenedException(OverflowException('error'))
assert v
def test_catch_exception_from_managed_method():
"""Test catching an exception from a managed method."""
from Python.Test import ExceptionTest
from System import OverflowException
with pytest.raises(OverflowException) as cm:
ExceptionTest().ThrowException()
e = cm.value
assert isinstance(e, OverflowException)
def test_catch_exception_from_managed_property():
"""Test catching an exception from a managed property."""
from Python.Test import ExceptionTest
from System import OverflowException
with pytest.raises(OverflowException) as cm:
_ = ExceptionTest().ThrowProperty
e = cm.value
assert isinstance(e, OverflowException)
with pytest.raises(OverflowException) as cm:
ExceptionTest().ThrowProperty = 1
e = cm.value
assert isinstance(e, OverflowException)
def test_catch_exception_managed_class():
"""Test catching the managed class of an exception."""
from System import OverflowException
with pytest.raises(OverflowException):
raise OverflowException('overflow')
def test_catch_exception_python_class():
"""Test catching the python class of an exception."""
from System import OverflowException
with pytest.raises(Exception):
raise OverflowException('overflow')
def test_catch_exception_base_class():
"""Test catching the base of an exception."""
from System import OverflowException, ArithmeticException
with pytest.raises(ArithmeticException):
raise OverflowException('overflow')
def test_catch_exception_nested_base_class():
"""Test catching the nested base of an exception."""
from System import OverflowException, SystemException
with pytest.raises(SystemException):
raise OverflowException('overflow')
def test_catch_exception_with_assignment():
"""Test catching an exception with assignment."""
from System import OverflowException
with pytest.raises(OverflowException) as cm:
raise OverflowException('overflow')
e = cm.value
assert isinstance(e, OverflowException)
def test_catch_exception_unqualified():
"""Test catching an unqualified exception."""
from System import OverflowException
try:
raise OverflowException('overflow')
except:
pass
else:
self.fail("failed to catch unqualified exception")
def test_catch_baseexception():
"""Test catching an unqualified exception with BaseException."""
from System import OverflowException
with pytest.raises(BaseException):
raise OverflowException('overflow')
def test_apparent_module_of_exception():
"""Test the apparent module of an exception."""
from System import OverflowException
assert System.Exception.__module__ == 'System'
assert OverflowException.__module__ == 'System'
def test_str_of_exception():
"""Test the str() representation of an exception."""
from System import NullReferenceException, Convert, FormatException
e = NullReferenceException('')
assert str(e) == ''
e = NullReferenceException('Something bad happened')
assert str(e).startswith('Something bad happened')
with pytest.raises(FormatException) as cm:
Convert.ToDateTime('this will fail')
def test_python_compat_of_managed_exceptions():
"""Test managed exceptions compatible with Python's implementation"""
from System import OverflowException
msg = "Simple message"
e = OverflowException(msg)
assert str(e) == msg
assert e.args == (msg,)
assert isinstance(e.args, tuple)
strexp = "OverflowException('Simple message"
assert repr(e)[:len(strexp)] == strexp
def test_exception_is_instance_of_system_object():
"""Test behavior of isinstance(<managed exception>, 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
# 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(<managed exception>, 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):
assert isinstance(o, Object)
else:
assert not isinstance(o, Object)
def test_pickling_exceptions():
exc = System.Exception("test")
dumped = pickle.dumps(exc)
loaded = pickle.loads(dumped)
assert exc.args == loaded.args
def test_chained_exceptions():
from Python.Test import ExceptionTest
with pytest.raises(Exception) as cm:
ExceptionTest.ThrowChainedExceptions()
exc = cm.value
msgs = ("Outer exception",
"Inner exception",
"Innermost exception",)
for msg in msgs:
assert exc.Message == msg
assert exc.__cause__ == exc.InnerException
exc = exc.__cause__
def test_iteration_exception():
from Python.Test import ExceptionTest
from System import OverflowException
exception = OverflowException("error")
val = ExceptionTest.ThrowExceptionInIterator(exception).__iter__()
assert next(val) == 1
assert next(val) == 2
with pytest.raises(OverflowException) as cm:
next(val)
exc = cm.value
assert exc == exception
# after exception is thrown iterator is no longer valid
with pytest.raises(StopIteration):
next(val)
def test_iteration_innerexception():
from Python.Test import ExceptionTest
from System import OverflowException
exception = System.Exception("message", OverflowException("error"))
val = ExceptionTest.ThrowExceptionInIterator(exception).__iter__()
assert next(val) == 1
assert next(val) == 2
with pytest.raises(OverflowException) as cm:
next(val)
exc = cm.value
assert exc == exception.InnerException
# after exception is thrown iterator is no longer valid
with pytest.raises(StopIteration):
next(val)
def leak_test(func):
def do_test_leak():
# PyTest leaks things, gather the current state
orig_exc = {x for x in get_all_objects() if isinstance(x, Exception)}
func()
exc = {x for x in get_all_objects() if isinstance(x, Exception)}
possibly_leaked = exc - orig_exc
assert not possibly_leaked
return do_test_leak
@leak_test
def test_dont_leak_exceptions_simple():
from Python.Test import ExceptionTest
try:
ExceptionTest.DoThrowSimple()
except System.ArgumentException:
print('type error, as expected')
@leak_test
def test_dont_leak_exceptions_inner():
from Python.Test import ExceptionTest
try:
ExceptionTest.DoThrowWithInner()
except TypeError:
print('type error, as expected')
except System.ArgumentException:
print('type error, also expected')
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/MicroDistanceStudio/pythonnet.git
git@gitee.com:MicroDistanceStudio/pythonnet.git
MicroDistanceStudio
pythonnet
pythonnet
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /