【发布时间】:2015-03-05 07:35:57
【问题描述】:
在 python 2.7 中,是否可以测试模块私有?
运行后:
import unittest
__private_stuff = 1 # if it would have single underscore, it would not be a problem.
class ComplexTestCase(unittest.TestCase):
def test_internal_symbol(self):
self.assertEqual(__private_stuff, 1)
unittest.main(__name__)
结果是:
E
======================================================================
ERROR: test_internal_symbol (__main__.ComplexTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\files\y.py", line 7, in test_internal_symbol
self.assertEqual(__private_stuff, 1)
NameError: global name '_ComplexTestCase__private_stuff' is not defined
----------------------------------------------------------------------
有什么办法解决吗?
(不修改我要添加测试的代码)
替代方案(我想避免)
一种方法是重命名方法。
其他方法是添加额外的重命名符号private_stuff = __private_stuff。
但这很快就会变得非常乏味。
代码库使用这些“__xyz”作为公共符号(用于其他模块),其中有很多。
还有总是存在“_xyz”和“xyz”符号。
(试图找到“为什么”的答案,想出了唯一合理的解释
是前导下划线用于标记“修改”,因为在数学公式中使用“素数”。
例如x 和 x' 相似,但不一样)
【问题讨论】:
标签: python python-2.7 unit-testing