Search code examples
pythonpython-unittestpython-mock

patch does not work with different import statement


My questions is related to the following code snippets. In the first one, I am importing time.sleep with the "from ... import ..."-style:

from time import sleep

class Tests( unittest.TestCase ):
    def test_sleep( self ):
        with patch( "time.sleep" ) as sleepMock:
            sleep( 0.01 )
            sleepMock.assert_called_with( 0.01 )

With the second one, I go with the "import ..."-style:

import time

class Tests( unittest.TestCase ):
    def test_sleep( self ):
        with patch( "time.sleep" ) as sleepMock:
            time.sleep( 0.01 )
            sleepMock.assert_called_with( 0.01 )

The second one works well as expected. But the first one is not patching time.sleep. Why is the first one not working although I am importing the same function? How would the patch statement look like in the first example to succesfully mock 'time.sleep'? Or even better: Is there a way to patch this module, with which it is not relevant how I import the time.sleep function in my production code?


Solution

  • Test case 1:

    from time import sleep
    import unittest
    from unittest.mock import patch
    
    
    class Tests(unittest.TestCase):
        def test_sleep(self):
            with patch("__main__.sleep") as sleepMock:
                sleep(0.01)
                sleepMock.assert_called_with(0.01)
    
    
    if __name__ == '__main__':
        unittest.main()
    

    Result:

    python3 64550935-a.py
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    
    OK
    

    Test case 2:

    import time
    import unittest
    from unittest.mock import patch
    
    
    class Tests(unittest.TestCase):
        def test_sleep(self):
            with patch("time.sleep") as sleepMock:
                time.sleep(0.01)
                sleepMock.assert_called_with(0.01)
    
    
    if __name__ == '__main__':
        unittest.main()
    

    Result:

    python3 64550935-b.py
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    
    OK
    

    Take a look at the patch example of official docs.