python mock and libraries that are not installed

前端 未结 1 1569
别那么骄傲
别那么骄傲 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
    <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'>
    
    0 讨论(0)
提交回复
热议问题