python mock and libraries that are not installed

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 12:45:52

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
<MagicMock name='mock.GPIO' id='139664555819920'>
>>> import os
>>> os
<module 'os' from '/usr/lib/python2.7/os.pyc'>

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
<MagicMock name='mock.GPIO' id='140511459454648'>
>>> import os
>>> os
<module 'os' from '/usr/lib/python3.4/os.py'>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!