the unittest mock library mock and magic mock classes the unittest mock library provides the mock class and the magicmock class the mock class is the base class for mock objects the magicmock class is subclass of the mock class it is called the magicmock class as it provides default implementations for several magic method such as __len__()__str__()and __iter__(as simple example consider the following class to be testedclass someclass()def _hidden_method(self)return def public_method(selfx)return self hidden_method( this class defines two methodsone is intended as part of the public interface of the class (the public_method()and one it intended only for internal or private use (the _hidden_method()notice that the hidden method uses the convention of preceding its name by an underbar (' 'let us assume that we wish to test the behaviour of the public_method(and want to mock out the _hidden_method(we can do this by writing test that will create mock object and use this in place of the real _hidden_method(we could probably use either the mock class or the magicmock class for thishowever due to the additional functionality provided by the magicmock class it is common practice to use that class we will therefore do the same the test to be created will be defined within method within test class the names of the test method and the test class are by convention descriptive and thus will describe what is being testedfor examplefrom unittest mock import from unittest import testcase from unittest import main class test_someclass_public_interface(testcase)def test_public_method(self)test_object someclass(set up canned response on mock method test_object _hidden_method magicmock(name 'hidden_method'test_object _hidden_method return_value test the object result test_object public_method( self assertequal( result'return value from public_method incorrect'