如何在nosetest中测试类私有方法

时间:2014-03-21 04:02:35

标签: python-2.7 nose nosetests

如何在nosetest中测试类私有方法?

我的代码

class Txt(object):
    """docstring for Txt"""
    def __init__(self, im_file):
        super(Txt, self).__init__()
        self.im_file = im_file

    @classmethod
    def __parse_config(cls, im_file):
        for line in im_file:
            print(line)
        pass

我的鼻子

class TestTxt(object):
    """docstring for TestTxt"""
    @classmethod
    def setup_class(cls):
        cls.testing_file = '\n'.join([
                'rtsp_link: rtsp://172.19.1.101',
            ])
    def test_load(self):
        Txt.parse_config(StringIO(self.testing_file))

        pass

1 个答案:

答案 0 :(得分:0)

您可以通过在方法名称之前添加类名来访问Txt.__parse_config()私有方法:Txt._Txt__parse_config()

演示:

>>> class A():
...     _private = 1
...     __super_private = 2
... 
>>> A._private
1
>>> A.__super_private
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class A has no attribute '__super_private'
>>> A._A__super_private
2

有关正在发生的事情的详细信息,请参阅What is the meaning of a single- and a double-underscore before an object name?

希望有所帮助。