0

TL;DR:如何从 python 包中模拟单个模块

详细说明

我们正在使用基于 Beaglebone black 的自定义板,并且我们有不同的 git 存储库,其中包含不同的 python 脚本/模块。现在在大多数存储库中,我们维护脚本/模块的单元测试,并且无论脚本/模块依赖于其他模块,我们都会模拟该模块。

在编写 unittest 时,我遇到了一个问题,即我有一个包,其中存在一个模块,而另一个模块是从不同的 repo 复制的,同时创建了交叉编译的 rfs。

问题描述
我已经创建了示例模块结构,我如何在我的原始项目中使用它。

ankur@:~/temp/python/mock_test $ tree
.
├── __init__.py
├── mock_hi.py
├── orig_script.py
├── test_orig_file.py
└── tools
    ├── hello.py
    └── __init__.py

在上述结构中

  1. orig_script.py : 主脚本
  2. test_orig_file.py :主脚本的单元测试文件
  3. tools : 包含不同包的包目录,例如hellohi
  4. mock_hi.py :从工具包中模拟一个 hi 包。

orig_script.py 的内容

#/usr/bin/env python

from tools import hello
from tools import hi

def all_greentings():
    hello.world()
    hi.there()
    pass


# stuff to run always here such as class/def
def main():
    all_greentings()
    pass

if __name__ == "__main__":
   # stuff only to run when not called via 'import' here
   main()

test_orig_file.py 的内容

#!/usr/bin/env python
import unittest
import orig_script
from mock_hi import hi, there

class orig_test_class(unittest.TestCase):

    def test_hi_mock(self):
        orig_script.all_greentings()
        print("Done!")

mock_hi.py 的内容

#!/usr/bin/env python

import sys
import types
from mock import Mock

# mocking  module.
mn = 'tools.hi'
m_obj = types.ModuleType(mn)
sys.modules[mn] = m_obj
m_obj.there = Mock(name=mn+'.there')

tools/hello.py 内容如下

#/usr/bin/env python

def world():
    print("Hello, World!")


if __name__ == "__main__":
   # stuff only to run when not called via 'import' here
   world()

当我运行 unittest 时,出现以下错误

ankur@:~/temp/python/mock_test $ python -m unittest orig_script.py 
Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/lib/python2.7/unittest/__main__.py", line 12, in <module>
    main(module=None)
  File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__
    self.parseArgs(argv)
  File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs
    self.createTests()
  File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests
    self.module)
  File "/usr/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName
    module = __import__('.'.join(parts_copy))
  File "orig_script.py", line 4, in <module>
    from tools import hi
ImportError: cannot import name hi

有什么建议/更正/指针让它工作吗?

4

0 回答 0