【问题标题】:Unittest for context-manager fails with AttributeError: __exit__上下文管理器的单元测试失败,出现 AttributeError: __exit__
【发布时间】:2015-02-13 01:40:41
【问题描述】:

我正在尝试了解使用上下文管理器(带有语句)对代码进行单元测试的正确方法。

这是我的示例代码:

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'

这是我的单元测试代码:

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')

示例代码运行良好,但上面的 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)

是什么导致了这个错误?我错过了什么?

【问题讨论】:

    标签: python with-statement python-unittest


    【解决方案1】:

    resources 类在使用 with 语句时需要实例化:

    with ctxmgr.resources() as r:
    #                    ^^
    

    演示:

    >>> 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'
    ...
    >>> with resources as r:
    ...     r
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: __exit__
    >>>
    >>> with resources() as r:
    ...     r
    ...
    <__main__.resources object at 0x02112510>
    >>>
    

    【讨论】:

      猜你喜欢
      • 2022-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多