Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do I write unit tests that can access private attributes without exposing them?

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?

like image 379
grg-n-sox Avatar asked Nov 08 '11 15:11

grg-n-sox


People also ask

How do you access the private attribute in Python?

In Python, there is no existence of Private methods that cannot be accessed except inside a class. However, to define a private method prefix the member name with the double underscore “__”. Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.

Can we write unit tests for private methods?

Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.

How do you test private methods in unit testing?

To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.

How do you access private members outside class in Python?

Python doesn't have real private variables, so use the __ prefix (two underlines at the beginning make a variable) from PEP 8. Use instance _class-name__private-attribute try to access private variables outside the class in Python.


1 Answers

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?

like image 161
Fred Larson Avatar answered Sep 19 '22 13:09

Fred Larson