简体   繁体   中英

How can I test a python private method (yes I do have reason to test them)

I am looking for the cleanest way to write unit tests for python private methods.

I know that usually you don't want to test private methods, but we have inherited a gigantic behemoth of a python file which we need to refactor into more maintainable modules. We don't understand it's logic, but know it works, and so are looking to use TDD to ensure our refactoring does not break the code, and currently the 90% of the code is located in private methods and the module does too much to reliable test it all purely by black box testing. I fully expect I'll write some tests that will get removed once the refactor is complete, but for now I'd like to be able to plug into some private methods to test them to increase my confidence that my refactor has not broken key logic as I transition to a more maintainable (and testable) layout.

In python "private" methods are only sign for developer that they should be private, in fact you can access every method. When you start a method name with two underscores Python does some name "magic" to make it harder to access. In fact it does not enforce anything like other languages do.

Let say that we have following class:

class Foo:
 def __bar(self, arg):
     print(arg)
 def baz(self, arg):
     self.__bar(arg)

To access "private" __bar method try this:

f = Foo()
f._Foo__bar('a')

More about identifiers could be found in docs

Hope this is what you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM