I am trying to improve how I write my unit test cases for my Python programs. I am noticing in some cases, it would be really helpful to have access to private members to ensure that a method is functioning properly. An example case would be when trying to test a method for proper behavior that has no expected return value other than None. I know the easy and wrong way of doing this would be to just make the private attributes into protected attributes instead and test them directly. However, I would like to find a way that doesn't expose the interface as much.
So how do I test private attributes within classes without exposing them in the interface, or, if applicable, a better way of testing such a scenario so that private attribute access would not necessarily be needed for proper unit testing?
Nothing is private in Python. If you are using the double underscore prefix on member variables, the name is simply mangled. You can access it by qualifying the name in the form _Class__member
. This will access the __member
variable in the class Class
.
See also this question: Why are Python's 'private' methods not actually private?