如何在python的软件包中模拟一个模块

时间:2019-02-25 21:38:03

标签: python unit-testing python-unittest.mock

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

详细说明

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

在编写单元测试时,我遇到一个问题:我有一个包,其中有一个模块,而从交叉库中复制另一个模块时却创建了交叉编译的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:从工具包中模拟一个嗨包。

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()

运行单元测试时,出现以下错误

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

是否有任何建议/更正/指标,以使其正常工作?

0 个答案:

没有答案