小编Sri*_*Ram的帖子

上下文管理器的Unittest失败,出现AttributeError:__ exit__

我正在尝试理解使用context-manager(带语句)对代码进行单元测试的正确方法.

这是我的示例代码:

class resources():
    def __init__(self):
        self.data = 'at-init'

    def __enter__(self):
        self.data = 'at-enter'
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.data = 'at-exit'
Run Code Online (Sandbox Code Playgroud)

这是我的unittest代码:

import unittest
import ctxmgr     

class TestResources(unittest.TestCase):
    def setUp(self):
        pass

    def test_ctxmgr(self):
        with ctxmgr.resources as r:
            self.assertEqual(r.data, 'at-enter')
Run Code Online (Sandbox Code Playgroud)

示例代码运行正常,但上面的unittest代码失败,

======================================================================
ERROR: test_ctxmgr (__main__.TestResources)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_ctxmgr.py", line 12, in test_ctxmgr
    with ctxmgr.resources as r:
AttributeError: __exit__

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (errors=1)
Run Code Online (Sandbox Code Playgroud)

导致此错误的原因是什么?我错过了什么?

python with-statement python-unittest

8
推荐指数
1
解决办法
2910
查看次数

标签 统计

python ×1

python-unittest ×1

with-statement ×1