python mock and libraries that are not installed

前端 未结 1 1567
别那么骄傲
别那么骄傲 2021-02-07 17:38

I am working on software for a robot, which is normally run on the Raspberry Pi. Let\'s consider the imports of two files:

motor.py (runs the motors):

1条回答
  •  清歌不尽
    2021-02-07 17:45

    You can use patch.dict() to patch sys.modules and mock RPi module as showed in pointed documentation.

    Use follow code at the top of your test module:

    >>> from mock import MagicMock, patch
    >>> mymodule = MagicMock()
    >>> patch.dict("sys.modules", RPi=mymodule).start()
    >>> from RPi import GPIO as gpio
    >>> gpio
    
    >>> import os
    >>> os
    
    

    In Python3 you have same behavior.


    In your specific case use patch.dict is little bit overkill; maybe you aren't interested in patch context and original state recover. So you can simplify it by set sys.modules["RPi"] directly:

    >>> from unittest.mock import MagicMock
    >>> mymodule = MagicMock()
    >>> import sys
    >>> sys.modules["RPi"] = mymodule
    >>> from RPi import GPIO as gpio
    >>> gpio
    
    >>> import os
    >>> os
    
    

    0 讨论(0)
提交回复
热议问题