[英]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. 我正在寻找最干净的方法来编写python私有方法的单元测试。
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. 我知道通常您不想测试私有方法,但是我们继承了python文件的巨大庞然大物,需要将其重构为更可维护的模块。 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.
我们不了解它的逻辑,但知道它可以工作,因此希望使用TDD来确保我们的重构不会破坏代码,目前90%的代码位于私有方法中,并且该模块对可靠的测试完全是通过黑盒测试进行的。 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. 在python中,“私有”方法仅向开发人员签名,它们应该是私有的,实际上您可以访问每个方法。 When you start a method name with two underscores Python does some name "magic" to make it harder to access.
当您使用两个下划线开头的方法名称时,Python会使用一些“魔术”名称,以使其难以访问。 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: 要访问“专用” __bar方法,请尝试以下操作:
f = Foo()
f._Foo__bar('a')
More about identifiers could be found in docs 可以在文档中找到有关标识符的更多信息
Hope this is what you are looking for. 希望这是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.