运行 python 中的单元测试如何修补机器上不存在的模块?

How to patch a module that does not exist on the machine running the unit test in python?

我在自定义 SBC 上有 python 代码 运行ning,它使用自定义库与硬件交互(称之为 customlib)。

不过,我想 运行 在我的开发机器上对代码进行一些单元测试。我不想在我的机器上安装这个自定义库,因为这是一个费力且烦人的过程。

问题:是否可以修补该库以便我仍然可以 运行 在我的开发机器上进行单元测试?

应用结构:

.
├── app.py
├── sensor
│   ├── __init__.py
│   └── main.py
└── test_sensor.py

app.py 目前没有任何代码

# __init__.py
from .main import a
# main.py
import customlib
def a():
  customlib.func()
# test_sensor.py
import unittest
from unittest.mock import patch

class TestBasicSense(unittest.TestCase):
    @patch("sensor.customlib")
    def test_get(self):
        import sensor
        sensor.a()

if __name__ == "main":
    unittest.main()

当我 运行 python -m unittest 我收到导入错误:

  File "/projects/myapp/sensor/main.py", line 2, in <module>
    import customlib
ModuleNotFoundError: No module named 'customlib'

我可以创建一个虚拟的 customlib 库并将其安装在我的开发机器上,但这似乎是不必要的污染。

感谢任何帮助。

我在类似情况下使用了以下内容:将导入包装在 try/catch 块中:

# main.py
try:
  import customlib
except:
  customlib = None
# ... the rest of the code

然后在测试中打补丁,确保在 main.py 中打补丁,而不仅仅是在模块级别打补丁:

# test_sensor.py
from unittest.mock import patch
from unittest.mock import MagicMock
import sensor

class TestBasicSense(unittest.TestCase):
    def test_get(self):
        fake_lib = MagicMock()
        fake_lib.func = MagicMock()
        with patch('sensor.main.customlib', new=fake_lib)
            sensor.a()
            fake_lib.func.assert_called()