Reputation: 6459
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 its logic, but we 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.
Upvotes: 7
Views: 7589
Reputation: 786
In Python, "private" methods are only a 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’s say that we have the following class:
class Foo:
def __bar(self, arg):
print(arg)
def baz(self, arg):
self.__bar(arg)
To access the "private" __bar method, try this:
f = Foo()
f._Foo__bar('a')
More about identifiers could be found in the documentation.
Upvotes: 19