What is the canonical way to check if a function has been called in Python unittest without use of a mock?
Question: If I have a class similar to the 1 below and I want to test the various cases
for the bar function, how can I accomplish this without mocking the private
functions? In other words, how in Python's unittest library could I achieve
something similar to this:

    
    
    def test_bar():
        f = Foo()
        f.bar(3)
        expect(self._is_positive_number).toBeCalled()
    

**foo.py**

    
    
    class Foo():
        def bar(self, x):
           if type(x) is not int:
               print('Please enter a valid integer')
               return False
    
           if x > 0:
               self._is_positive_number()
           elif x == 0:
               self._is_zero()
           else 
               self._is_negative()
    
        def _is_positive_number(self):
            print('Positive')
            return True
    
        def _is_zero(self):
            print('Zero')
            return True
    
        def _is_negative_number(self):
            print('Negative')
            return True
    


Answer: As far as I know, there's no way to do this without mocking out the private
methods. However, the `mock` library (available as `unittest.mock` in the
standard library as of 3.3, a separate installation otherwise) makes this
relatively painless:

    
    
    try:
        # Python 3.3 or later
        import unittest.mock as mock
    except ImportError:
        # Make sure you install it first
        import mock
    
    class TestFoo(unittest.TestCase):
        def setUp(self):
            self.f = Foo()
    
        def test_bar(self):
            with mock.patch.object(self.f, '_is_positive_number') as is_pos:
                self.f.bar(3)
                self.assertTrue(is_pos.called)
    

