1

how to test class private method in nosetest ?

My code

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

My nosetest

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
newBike
  • 14,385
  • 29
  • 109
  • 192

1 Answers1

0

You can access Txt.__parse_config() private method by prepending a class name before the method name: Txt._Txt__parse_config().

Demo:

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

For more info on what is happening, see What is the meaning of a single- and a double-underscore before an object name?.

Hope that helps.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195